var PDJS;
(function (PDJS) {
    class Ajax {
        static onBeforeSend(callback) {
            this._onBeforeSend.add(callback);
        }
        static onSuccess(callback) {
            this._onSuccess.add(callback);
        }
        static onError(callback) {
            this._onError.add(callback);
        }
        static onComplete(callback) {
            this._onComplete.add(callback);
        }
        static call(options) {
            var ajaxEvents = {
                beforeSend: function (jqXHR, settings) {
                    if (_.isFunction(options.beforeSend)) {
                        options.beforeSend.apply(this, arguments);
                    }
                    Ajax._onBeforeSend.each((callback) => {
                        callback({
                            xhr: jqXHR,
                            settings: settings,
                            status: null
                        });
                    });
                },
                success: function (data, textStatus, jqXHR) {
                    if (_.isFunction(options.success)) {
                        options.success.apply(this, arguments);
                    }
                    Ajax._onSuccess.each((callback) => {
                        callback({
                            xhr: jqXHR,
                            settings: null,
                            status: textStatus
                        });
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    jqXHR.errorHandled = false;
                    if (_.isFunction(options.error)) {
                        options.error.apply(this, arguments);
                    }
                    Ajax._onError.each((callback) => {
                        callback({
                            xhr: jqXHR,
                            settings: null,
                            status: textStatus
                        });
                    });
                    if (!jqXHR.errorHandled) {
                        new PDJS.AjaxErrorHandler({
                            config: this,
                            jqXHR: jqXHR
                        });
                    }
                },
                complete: function (jqXHR, textStatus) {
                    if (_.isFunction(options.complete)) {
                        options.complete.apply(this, arguments);
                    }
                    Ajax._onComplete.each((callback) => {
                        callback({
                            xhr: jqXHR,
                            settings: null,
                            status: textStatus
                        });
                    });
                    if (!jqXHR.suppressEvent) {
                        Jade.Application
                            .instance
                            .contexts
                            .global
                            .events
                            .publish("Ajax:Request:Complete");
                    }
                }
            };
            return $.ajax($.extend({}, options, ajaxEvents));
        }
    }
    Ajax._onBeforeSend = new Jade.Collection();
    Ajax._onSuccess = new Jade.Collection();
    Ajax._onError = new Jade.Collection();
    Ajax._onComplete = new Jade.Collection();
    PDJS.Ajax = Ajax;
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class AjaxErrorHandler {
        constructor(options) {
            this._options = _.extend({
                config: null,
                jqXHR: null
            }, options);
            if (this.isRedirect()) {
                return;
            }
            this.checkForErrors();
        }
        get options() {
            return this._options;
        }
        checkForErrors() {
            let errors = PDJS.Shared
                .ErrorFactory.convert(this.options.jqXHR);
            let keylessErrors = errors.filter(error => error.key == null);
            let hasKeylessErrors = keylessErrors.length > 0;
            if (!hasKeylessErrors) {
                return;
            }
            PDJS.Shared.Dialogs.ErrorDialogLauncher.open({
                errors: errors.map(error => error.toJSON())
            });
        }
        isRedirect() {
            var redirect = this.options
                .jqXHR
                .getResponseHeader('Http-Redirect');
            if (redirect != null) {
                window.location.href = redirect;
            }
            return redirect != null;
        }
    }
    PDJS.AjaxErrorHandler = AjaxErrorHandler;
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class Application extends Jade.Application {
        constructor(options) {
            super(options);
        }
        static get events() {
            return PDJS.ApplicationEventsHub;
        }
        get instanceId() {
            return this.m_instanceId;
        }
        set instanceId(value) {
            this.m_instanceId = value;
        }
        static get instance() {
            return Application.internalInstance;
        }
        get databaseId() {
            return Jade.String.format("PDDB_{0}_{1}", this.id, PDJS.Profiles.Profile.current.identity.id.toString());
        }
        get area() {
            return this.m_area;
        }
        set area(value) {
            this.m_area = value;
        }
        static get profile() {
            return PDJS.Profiles.Profile.current;
        }
        onInit(options) {
            this.id = options.applicationId;
            this.instanceId = Jade.Guid.new();
            this.area = options.area;
            Jade.Data.Database.create(this.databaseId);
            super.onInit(options);
        }
    }
    PDJS.Application = Application;
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class EventsHubBase {
            static get global() {
                return PDJS.Application
                    .instance
                    .contexts
                    .global
                    .events;
            }
            static get current() {
                return PDJS.Application
                    .instance
                    .contexts
                    .current
                    .events;
            }
            static get hasContext() {
                return PDJS.Application
                    .instance
                    .contexts
                    .global != null &&
                    PDJS.Application
                        .instance
                        .contexts
                        .current != null;
            }
        }
        Shared.EventsHubBase = EventsHubBase;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    let Events;
    (function (Events) {
        Events["VersionChanged"] = "version/changed";
        Events["WindowResized"] = "window/resized";
    })(Events = PDJS.Events || (PDJS.Events = {}));
    class ApplicationEventsHub extends PDJS.Shared.EventsHubBase {
        static versionChangedPublish() {
            this.global.publish(Events.VersionChanged);
        }
        static windowResizedPublish() {
            this.global.publish(Events.WindowResized);
        }
        static versionChangedSubscribe(handler) {
            return this.global.subscribe(Events.VersionChanged, handler);
        }
        static windowResizedSubscribe(handler) {
            return this.global.subscribe(Events.WindowResized, handler);
        }
    }
    PDJS.ApplicationEventsHub = ApplicationEventsHub;
    PDJS.Application.onStart(() => {
        Jade.Application
            .instance
            .contexts
            .global
            .events
            .subscribe("Window:Resized", () => {
            ApplicationEventsHub.windowResizedPublish();
        });
    });
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class JS {
        static get ProspectDirector() {
            return window["ProspectDirector"];
        }
        static get PD() {
            return window["PD"];
        }
        static get Plugins() {
            return window["Plugins"];
        }
    }
    PDJS.JS = JS;
    Jade.Application.onStart(() => {
        CanvasJS.GroupModel.componentTypeDefault = "ProspectDirector.Web.UI.Canvas.Group";
        FeatureBlendJS.FeatureBlend.errorTooltipSkin = "validation-error";
        Jade.IconSet.add({
            id: "pdjs",
            rootPath: "~/scripts/pdjs/internal/images"
        });
        Jade.IconSet.add({
            id: "canvasjs",
            rootPath: "~/scripts/canvas-js/internal/images"
        });
        Jade.IconSet.add({
            id: "jadejs",
            rootPath: "~/scripts/jade-ui/internal/images"
        });
        Jade.IconSet.add({
            id: "pd",
            rootPath: "~/application/icons"
        });
        Jade.IconSet.add({
            id: "pdv2",
            rootPath: "~/areas/shared/assets/internal/icons"
        });
    });
    Jade.ContextManager.onContextChange((e) => {
        if (e.newContext != null && e.newContext.isDialogContext) {
            setTimeout(() => {
            }, 1000);
        }
    });
    Jade.Application.onStart(() => {
        $(document).ready(() => {
            switch (Jade.Application.instance.name) {
                case "hub":
                    new PDJS.Hub.ApplicationBar({
                        container: $(".-pd-framework-menu")
                    });
                    break;
                case "manage":
                    break;
            }
        });
        $("BODY").on("click", "A[target]", (e) => {
            let node = $(e.target);
            let target = node.attr("target");
            if (Jade.String.isNullOrWhiteSpace(target)) {
                return;
            }
            let href = node.attr("href");
            let targetValues = [
                "_blank",
                "_self",
                "_parent",
                "_top"
            ];
            if (targetValues.indexOf(target) === -1) {
                window.open(href, target);
                return false;
            }
            if (target === "_blank") {
                window.open(href);
                return false;
            }
        });
    });
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class StartUp {
        static get areaName() {
            return this.m_areaName;
        }
        static set areaName(value) {
            this.m_areaName = value;
        }
        static get virtualDirectory() {
            return this.m_virtualDirectory;
        }
        static set virtualDirectory(value) {
            this.m_virtualDirectory = value;
        }
        static startHub(virtualDirectory, success, failure) {
            success = success || (() => { });
            failure = failure || (() => { });
            this.virtualDirectory = virtualDirectory;
            this.areaName = "hub";
            this.start(() => {
                this.renderContent();
                success();
            }, failure);
        }
        static startManage(virtualDirectory, success, failure) {
            success = success || (() => { });
            failure = failure || (() => { });
            this.virtualDirectory = virtualDirectory;
            this.areaName = "manage";
            this.start(() => {
                self.window.name = PDJS.System.Environment.current.settings.manageWindowId;
                this.renderContent();
                new PDJS.Manage.ApplicationBar({
                    container: ".-pd-framework-menu"
                });
                success();
            }, failure);
        }
        static start(success, failure) {
            PDJS.Ajax.call({
                url: `/${this.virtualDirectory}/Shared/Start/${this.areaName}`,
                success: (e) => {
                    this.startEnvironment(e);
                    this.startPD(e);
                    this.startPDJS(e);
                    success(e);
                },
                error: (e) => {
                    failure();
                },
            });
        }
        static startEnvironment(e) {
            PDJS.System.Environment.load(e);
            PDJS.System.Environment.setScrollBarSize();
        }
        static startPD(e) {
            PDJS.JS.PD.boot({
                APPLICATION_ID: e.settings.applicationId,
                USER_ID: e.profile.identity.id,
                USER_NAME: e.profile.identity.accountName,
                VIRTUAL_DIRECTORY: e.settings.virtualDirectory,
                AUTH_MODE: e.settings.authenticationMode
            });
        }
        static startPDJS(e) {
            new PDJS.Application({
                area: this.areaName,
                name: this.areaName,
                virtualDirectory: `/${e.settings.virtualDirectory}`,
                applicationId: e.settings.applicationId,
                label: this.areaName
            });
        }
        static renderContent() {
            PDJS.Application.onStart(() => {
                let viewport = $(".-pd-framework-view");
                let contents = $(".-pd-framework-view-content").get(0).innerHTML;
                viewport.append(contents);
            });
        }
    }
    PDJS.StartUp = StartUp;
})(PDJS || (PDJS = {}));
var plupload;
(function (plupload) {
    let UploaderEvent;
    (function (UploaderEvent) {
        UploaderEvent["BeforeUpload"] = "BeforeUpload";
        UploaderEvent["Browse"] = "Browse";
        UploaderEvent["ChunkUploaded"] = "ChunkUploaded";
        UploaderEvent["Destroy"] = "Destroy";
        UploaderEvent["Error"] = "Error";
        UploaderEvent["FileFiltered"] = "FileFiltered";
        UploaderEvent["FilesAdded"] = "FilesAdded";
        UploaderEvent["FilesRemoved"] = "FilesRemoved";
        UploaderEvent["FileUploaded"] = "FileUploaded";
        UploaderEvent["FileRemoved"] = "FileRemoved";
        UploaderEvent["UploadProgress"] = "UploadProgress";
        UploaderEvent["UploadComplete"] = "UploadComplete";
        UploaderEvent["QueueChanged"] = "QueueChanged";
        UploaderEvent["StateChanged"] = "StateChanged";
    })(UploaderEvent = plupload.UploaderEvent || (plupload.UploaderEvent = {}));
    ;
    let FileStatus;
    (function (FileStatus) {
        FileStatus[FileStatus["QUEUED"] = 1] = "QUEUED";
        FileStatus[FileStatus["UPLOADING"] = 2] = "UPLOADING";
        FileStatus[FileStatus["FAILED"] = 4] = "FAILED";
        FileStatus[FileStatus["DONE"] = 5] = "DONE";
    })(FileStatus = plupload.FileStatus || (plupload.FileStatus = {}));
    ;
    let UploaderState;
    (function (UploaderState) {
        UploaderState[UploaderState["STARTED"] = 1] = "STARTED";
        UploaderState[UploaderState["STOPPED"] = 2] = "STOPPED";
    })(UploaderState = plupload.UploaderState || (plupload.UploaderState = {}));
    ;
    ;
    ;
})(plupload || (plupload = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        class Model {
            constructor(state) {
                this.m_state = new Jade.StateBag();
                this.state.on("change", () => {
                    this.onStateChanged();
                    this.onStateChangeCallback();
                });
                this.state.set(state, { silent: true });
            }
            get onStateChangeCallback() {
                if (_.isFunction(this.m_onStateChangeCallback)) {
                    return this.m_onStateChangeCallback;
                }
                else {
                    return () => { };
                }
                ;
            }
            set onStateChangeCallback(value) {
                if (_.isFunction(value)) {
                    this.m_onStateChangeCallback = value;
                }
            }
            get state() {
                return this.m_state;
            }
            toJSON() {
                return this.state.toJSON();
            }
            has(name) {
                return this[name] != undefined;
            }
            onStateChanged() {
            }
        }
        Core.Model = Model;
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        class InternalScript extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get documentId() {
                return this.state.get("documentId");
            }
            get documentNode() {
                return $(`[document-id=${this.documentId}]`);
            }
            get documentElement() {
                return this.documentNode.get(0);
            }
            get script() {
                return this.state.get("script");
            }
            addScript() {
                if (Jade.String.isNullOrWhiteSpace(this.script)) {
                    return;
                }
                let scriptElement = document.createElement("script");
                this.documentElement.parentNode.insertBefore(scriptElement, this.documentElement);
                scriptElement.innerHTML = this.script;
                Array.from(scriptElement.querySelectorAll("script")).forEach(oldScript => {
                    const newScript = document.createElement("script");
                    const attributes = Array.from(oldScript.attributes);
                    attributes.forEach(attr => {
                        let value = attr.value;
                        if (attr.name === "src") {
                            value = `${value}?${Jade.Guid.new()}`;
                        }
                        newScript.setAttribute(attr.name, value);
                    });
                    newScript.appendChild(document.createTextNode(oldScript.innerHTML));
                    oldScript.parentNode.replaceChild(newScript, oldScript);
                });
            }
        }
        Canvas.InternalScript = InternalScript;
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        class InternalStyles extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get documentId() {
                return this.state.get("documentId");
            }
            get documentNode() {
                return $(`[document-id=${this.documentId}]`);
            }
            get documentElement() {
                return this.documentNode.get(0);
            }
            get styles() {
                return this.state.get("styles");
            }
            get stylesId() {
                return `style-${this.documentId}`;
            }
            get stylesNode() {
                return $(`${this.stylesId}`);
            }
            addStyles() {
                if (Jade.String.isNullOrWhiteSpace(this.styles)) {
                    return;
                }
                let styleNode = document.createElement("style");
                styleNode.id = this.stylesId;
                this.documentElement.parentNode.insertBefore(styleNode, this.documentElement);
                styleNode.innerHTML = this.getStylesContent();
            }
            removeStyles() {
                $(`#${this.stylesId}`).remove();
            }
            updateStyles() {
                let styleNode = $(`#${this.stylesId}`);
                if (styleNode.length > 0) {
                    styleNode.get(0).innerHTML = this.getStylesContent();
                }
            }
            getStylesContent() {
                return `@scope (div[document-id="${this.documentId}"].-canvasjs-document) { ${this.styles} }`;
            }
        }
        Canvas.InternalStyles = InternalStyles;
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        Jade.ContextManager.onContextChange((e) => {
            CanvasJS.Actual.Environment.reset();
            CanvasJS.Design.Environment.reset();
        });
        Jade.Application.onStart(() => {
            FeatureBlendJS.FeatureBlend.editorExtenders.add("dynamics", (e) => {
                return new PDJS.Canvas.Design.Dynamics.DynamicsEditor(e);
            });
            Jade.UI.Controls.RibbonBar.registerTooltipFunction((handle, label, content, options) => {
                PDJS.Shared.PopOver.tooltipRibbon(handle, { title: label, description: content }, options);
            });
        });
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class CanvasRefresh {
                static validate(e) {
                    CanvasJS.Actual.Environment
                        .document
                        .controls
                        .each((element) => {
                        if (element instanceof Actual.Forms.FormField) {
                            element.validationErrors.clear();
                        }
                    });
                    let formId = null;
                    _.each(e.validationErrors, (value, key) => {
                        let control = CanvasJS.Actual.Environment
                            .document
                            .controls
                            .getById(key);
                        if (control != null && control instanceof Actual.Forms.FormField) {
                            control.validationErrors.add(value);
                            formId = control.formId;
                        }
                    });
                    Canvas.Actual.Forms.FormFieldAnimation.start(formId, 1500, Canvas.Actual.Forms.FormFieldAnimationType.error);
                }
                static populate(e) {
                    if (e.document == null) {
                        return;
                    }
                    let documentView = CanvasJS.Actual.Environment.document;
                    let documentModel = new PDJS.Canvas.Core.Documents.ActualDocument(e.document);
                    documentView.controls.clear();
                    documentView.source.fill(documentModel.toJSON());
                    CanvasJS.Actual.Environment.document.source.elements.each((source) => {
                        let element = source.resolver.getView(CanvasJS.CanvasType.Actual);
                        CanvasJS.Actual.Environment
                            .document
                            .controls
                            .add(element);
                    });
                }
            }
            Actual.CanvasRefresh = CanvasRefresh;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class CanvasViewBox extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_document = null;
                    if (this.createContext) {
                        Jade.Application.instance.contexts.destroyContext({
                            id: Jade.Application.instance.contexts.current.ID
                        });
                        Jade.Application.instance.contexts.createContext({
                            makeDefault: true
                        });
                    }
                }
                get createContext() {
                    return this.state.get("createContext", true);
                }
                get document() {
                    return this.m_document;
                }
                get documentId() {
                    return this.state.get("documentId");
                }
                get documentState() {
                    return this.state.get("documentState");
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get rowIds() {
                    return this.state.get("rowIds", []);
                }
                get hasChanges() {
                    var _a, _b;
                    return (_b = (_a = this.m_document) === null || _a === void 0 ? void 0 : _a.source) === null || _b === void 0 ? void 0 : _b.hasChanges;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass("-canvasjs-actual");
                    this.node.css({
                        height: "100%",
                        width: "100%"
                    });
                    if (this.documentState == null) {
                        this.requestDocument();
                    }
                    else {
                        this.loadDocument(this.documentState);
                    }
                }
                requestDocument() {
                    let documentService = new PDJS.Services.Canvas.DocumentService();
                    documentService.loadActualDocument({
                        documentId: this.documentId,
                        entityId: this.entityId,
                        rowId: this.rowIds.length == 1 ? this.rowIds[0] : 0,
                        success: (e) => {
                            this.loadDocument(e.data);
                        }
                    });
                }
                loadDocument(state) {
                    let source = new Canvas.Core.Documents.ActualDocument(state);
                    this.m_document = new Actual.DocumentView({
                        $source: source,
                        documentId: this.documentId,
                        entityId: this.entityId,
                        isBatchMode: this.rowIds.length > 1
                    });
                    this.controls.add(this.m_document);
                    Actual.ElementFocus.setDefaultFocus(this.m_document);
                }
            }
            Actual.CanvasViewBox = CanvasViewBox;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class CanvasViewBoxOnCreate extends Jade.UI.Control {
                get documentState() {
                    return this.state.get("documentState");
                }
                get document() {
                    return this.state.get("document");
                }
                onActivate(e) {
                    this.node.addClass("-canvasjs-actual");
                    this.node.css({
                        height: "100%",
                        width: "100%"
                    });
                    if (this.documentState != null) {
                        let documentView = new Actual.DocumentView({
                            $source: new Canvas.Core.Documents.ActualDocument(this.documentState)
                        });
                        this.controls.add(documentView);
                        Actual.ElementFocus.setDefaultFocus(documentView);
                    }
                }
                getDocumentJSON() {
                    return CanvasJS.Actual.Environment.document.toJSON();
                }
            }
            Actual.CanvasViewBoxOnCreate = CanvasViewBoxOnCreate;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            let CssClass;
            (function (CssClass) {
                CssClass["ElementError"] = "-pdjs-element-actual-error";
            })(CssClass = Actual.CssClass || (Actual.CssClass = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class DocumentView extends CanvasJS.Actual.DocumentActualViewBase {
                constructor(options) {
                    super(options);
                    this.subscriptions.add("Explorer:Content:Unload", () => {
                        this.destroy();
                    });
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass("-pdjs-canvas-document-actual");
                    this.node.attr("document-id", this.source.id);
                    this.addExternalFiles();
                    this.addInternalStyles();
                    this.addInternalScript();
                }
                onStateChanged() {
                    this.node.css({
                        height: "100%",
                        width: "100%",
                        backgroundColor: this.source.backgroundColor,
                        overflow: "auto",
                        position: "relative"
                    });
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("canvas/destroyed");
                }
                addInternalScript() {
                    let internalScript = new Canvas.InternalScript({
                        documentId: this.source.id,
                        documentNode: this.node,
                        script: this.source.internalScript
                    });
                    internalScript.addScript();
                }
                addInternalStyles() {
                    let internalStyles = new Canvas.InternalStyles({
                        documentId: this.source.id,
                        styles: this.source.internalStyles
                    });
                    internalStyles.addStyles();
                }
                addExternalFiles() {
                    this.source.externalFiles.forEach((url) => {
                        url = Jade.Path.resolve(url);
                        let ext = Jade.Path.getFileExtension(url);
                        let node = this.node.get(0);
                        let parentNode = this.node.get(0).parentNode;
                        if (ext == ".js") {
                            let scriptNode = document.createElement("script");
                            scriptNode.src = `${url}?v=${Date.now()}`;
                            parentNode.insertBefore(scriptNode, node);
                        }
                        if (ext == ".css") {
                            let linkNode = document.createElement("link");
                            linkNode.type = "text/css";
                            linkNode.rel = "stylesheet";
                            linkNode.href = `${url}?v=${Date.now()}`;
                            parentNode.insertBefore(linkNode, node);
                        }
                    });
                }
            }
            Actual.DocumentView = DocumentView;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class ElementFocus {
                static setDefaultFocus(document) {
                    document.source.tabIndexes.each((id) => {
                        let element = document.controls.getById(id);
                        let focusable = null;
                        if (Jade.InterfaceGuard.is(element, Canvas.Core.IFocusableGuard)) {
                            focusable = element;
                        }
                        if (focusable != null && focusable.acceptsFocus) {
                            focusable.focus();
                            return false;
                        }
                    });
                }
            }
            Actual.ElementFocus = ElementFocus;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class ElementView extends CanvasJS.Actual.ElementActualViewBase {
            }
            Actual.ElementView = ElementView;
            class ElementViewBase extends ElementView {
                get source() {
                    return this.m_source;
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.showElementErrors(this.source.errors);
                }
                showElementErrors(errors) {
                    if (errors.length > 0) {
                        this.controls.clear();
                        this.node.empty();
                        this.controls.add(new Actual.ElementViewError({
                            componentName: this.source.componentName,
                            errors: errors,
                            height: this.height,
                            width: this.width
                        }));
                    }
                }
            }
            Actual.ElementViewBase = ElementViewBase;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            class ElementViewError extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get errors() {
                    return this.state.get("errors");
                }
                get componentName() {
                    return this.state.get("componentName");
                }
                get messageNode() {
                    return this.node.find("div[role=message]");
                }
                get height() {
                    return this.state.get("height");
                }
                get width() {
                    return this.state.get("width");
                }
                template() {
                    return `<div class="${Actual.CssClass.ElementError}">
                        <table style="height:${this.height}px;width:${this.width}px;">
                            <tr>
                                <td>
                                    <div role="message" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:${this.width}px;padding:0 5px 0 5px;">
                                        ${this.getLabelContent(true)}
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>`;
                }
                onActivate(e) {
                    super.onComplete(e);
                    PDJS.Shared.PopOver.tooltip(this.node, this.getErrorMessage());
                    if (this.height < 50 && this.width < 150) {
                        this.messageNode.html(this.getLabelContent());
                        this.messageNode.css({
                            paddingLeft: 0,
                            backgroundPosition: "center center",
                            backgroundRepeat: "no-repeat",
                            width: "100%",
                            boxSizing: "border-box"
                        });
                    }
                }
                getIcon() {
                    return Jade.IconSet.get("pdjs").resolve("error.png", Jade.IconSetSizeSpecificDirectory.x32);
                }
                getErrorMessage() {
                    let result = "";
                    result += `<div style="min-width: 150px;white-space:nowrap;font-size:13px;font-weight:bold;padding-bottom:5px;text-decoration:underline;">${this.componentName}</div>`;
                    _.each(this.errors, (error) => {
                        result += `<div style="padding:0 0 5px 0;min-width:150px;font-size:13px;color:red;">${error.message}</div>`;
                    });
                    result += `<div style="min-width: 150px;white-space:nowrap;font-size:13px;">Contact your system administrator if the issues persist.</div>`;
                    return `<div>${result}</div>`;
                }
                getLabelContent(text = false) {
                    return `<img src="${this.getIcon()}" style="vertical-align:middle;margin-bottom:3px;" /> ${text ? "&nbsp;" + this.componentName + " Error" : ""}`;
                }
            }
            Actual.ElementViewError = ElementViewError;
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Charts;
            (function (Charts) {
                class Chart extends Actual.ElementViewBase {
                    get kendo() {
                        return this.m_kendo;
                    }
                    set kendo(value) {
                        this.m_kendo = value;
                    }
                    get chartNode() {
                        return this.node.find("[role=chart]");
                        ;
                    }
                    template() {
                        return `<div role="chart"></div>`;
                    }
                    refresh() {
                        let chartOptions = null;
                        let shouldRefresh = this.kendo != null
                            && this.nodeHeight > 10
                            && this.nodeWidth > 10;
                        if (shouldRefresh) {
                            chartOptions = this.getChartOptions();
                            this.kendo.setOptions(chartOptions);
                            this.kendo.refresh();
                        }
                        this.hideLoadingMessage();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.isBrowserResizeAware = true;
                        this.m_kendo = this.chartNode
                            .kendoChart(this.getChartOptions())
                            .data("kendoChart");
                        this.node.css({
                            overflow: "hidden"
                        });
                        this.menu_init();
                        this.informationBar_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (this.source.data == null) {
                            this.showLoadingMessage();
                            this.source.getCachedData({
                                success: (e) => {
                                    this.m_informationBar.update();
                                    this.showElementErrors(e.errors);
                                }
                            });
                        }
                        else {
                            setTimeout(() => {
                                this.refresh();
                            }, 100);
                        }
                    }
                    onBrowserResize() {
                        if (this.anchorRight != null || this.anchorBottom != null) {
                            this.refresh();
                        }
                    }
                    onStateChanged() {
                        var _a;
                        super.onStateChanged();
                        this.chartNode.css({
                            position: "absolute",
                            top: 0,
                            right: 0,
                            bottom: 0,
                            left: 0,
                            boxSizing: "border-box",
                            padding: 0,
                            margin: 0,
                            borderWidth: this.source.style.chartArea.borderWidth,
                            borderStyle: "solid",
                            borderColor: (_a = this.source.style.chartArea.borderColor) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-area-border-color)"
                        });
                        this.refresh();
                    }
                    getChartOptions() {
                        let result = null;
                        let chartState = $.extend(true, this.source.toJSON(), {
                            data: this.source.data
                        });
                        result = Canvas.Shared.Charts.ChartOptionsFactory.create(chartState).getOptions();
                        result = $.extend(true, result, {
                            seriesDefaults: {
                                type: this.source.seriesType
                            },
                            chartArea: {
                                height: this.nodeHeight == 0 ? 10 : this.getChartHeight(),
                                width: this.nodeWidth == 0 ? 10 : this.nodeWidth,
                            }
                        });
                        return result;
                    }
                    getChartHeight() {
                        return this.nodeHeight - (this.source.informationBarVisible ? 25 : 0);
                    }
                    hideLoadingMessage() {
                        if (this.m_message != null && this.source.cacheRefreshStatus != Canvas.Core.CachedElementRefreshStatus.Pending) {
                            this.controls.remove(this.m_message);
                        }
                    }
                    showLoadingMessage() {
                        this.hideLoadingMessage();
                        this.m_message = new PDJS.Shared.UI.Controls.LoadingMessageControl({
                            message: "Loading..."
                        });
                        this.controls.add(this.m_message);
                    }
                    menu_init() {
                        if (!this.source.actionMenuVisible) {
                            return;
                        }
                        this.m_menu = new Canvas.Shared.ElementMenu({
                            position: Canvas.Shared.ElementMenuPosition.topRight,
                            visible: true
                        });
                        if (this.source.actionMenuRefresh) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                icon: "refresh.16px.font",
                                label: "Refresh",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    this.showLoadingMessage();
                                    this.source.getCachedData({
                                        force: true,
                                        success: (e) => {
                                            this.showElementErrors(e.errors);
                                        }
                                    });
                                }
                            }));
                        }
                        let boardContent = () => {
                            return `<div class="-pdjs-canavas-element-menu-item-last-updated">
                            <b>Last Updated:</b><br/>
                            ${kendo.toString(new Date(this.source.cacheLastUpdated), "g")}
                        </div>`;
                        };
                        this.m_menu.items.add(new Canvas.Shared.ElementMenuItemBoard({
                            content: boardContent(),
                            show: (e) => {
                                e.content = boardContent();
                            }
                        }));
                        this.controls.add(this.m_menu);
                    }
                    informationBar_init() {
                        this.m_informationBar = new Canvas.Shared.ElementBar({
                            source: this.source,
                            showRefresh: this.source.informationBarRefresh,
                            visible: this.source.informationBarVisible,
                            onRefresh: () => {
                                this.showLoadingMessage();
                                this.source.getCachedData({
                                    force: true,
                                    success: (e) => {
                                        this.m_informationBar.update();
                                        this.showElementErrors(e.errors);
                                    }
                                });
                            }
                        });
                        this.controls.add(this.m_informationBar);
                    }
                }
                Charts.Chart = Chart;
            })(Charts = Actual.Charts || (Actual.Charts = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            class IFocusableGuard extends Jade.InterfaceGuard {
                get signature() {
                    return {
                        id: "628b891c-740c-4a70-9a05-bf8a3046ab48",
                        label: "IFocusableGuard"
                    };
                }
            }
            Core.IFocusableGuard = IFocusableGuard;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                let Button = class Button extends Actual.ElementViewBase {
                    get acceptsFocus() {
                        return this.source.enabled;
                    }
                    get buttonIconNode() {
                        return this.buttonNode.find("div:nth-child(2)");
                    }
                    get buttonImageNode() {
                        return this.buttonIconNode.find("img");
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get buttonTextNode() {
                        return this.buttonNode.find("div:nth-child(3)");
                    }
                    get imageUrl() {
                        return Jade.Path.resolve(`~/resources/${this.source.image}`);
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-button">
                        <button>
                            <div></div>
                            <div><img/></div>
                            <div></div>
                            <div></div>
                        </button>
                    </div>`;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                    }
                    onClick(e) {
                        if (this.source.enabled && this.source.hasOnClickAction) {
                            PDJS.Shared.Actions.Action.invoke(this.source.onClickAction);
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.buttonNode.prop("disabled", !this.source.enabled);
                        this.buttonNode.css({
                            borderRadius: this.source.borderRadius
                        });
                        if (this.source.hasImage) {
                            this.buttonImageNode.show();
                            this.buttonImageNode.attr("src", this.imageUrl);
                        }
                        else {
                            this.buttonImageNode.hide();
                        }
                        if (this.source.hasLabel) {
                            this.buttonTextNode.show();
                            this.buttonTextNode.text(this.source.label);
                        }
                        else {
                            this.buttonTextNode.hide();
                        }
                        this.buttonImageNode.css({
                            maxWidth: this.buttonNode.width(),
                            maxHeight: this.buttonNode.height()
                        });
                        this.source.hasImage && this.source.hasLabel ?
                            this.buttonIconNode.css({ paddingRight: "5px" }) :
                            this.buttonIconNode.css({ paddingRight: "0" });
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.node, this.source.tooltip);
                        }
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                };
                Button = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Core.IFocusableGuard)
                ], Button);
                Common.Button = Button;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                let Hyperlink = class Hyperlink extends Actual.ElementViewBase {
                    get linkNode() {
                        return this.node.find("A");
                    }
                    get acceptsFocus() {
                        return this.source.enabled;
                    }
                    template() {
                        return `<div style="display:flex;align-items:center;position:absolute;top:0;left:0;right:0;bottom:0;">
                        <a href='#' style='width:100%;' tabIndex="${this.source.activeTabIndex}"></a>
                    </div>`;
                    }
                    focus() {
                        this.linkNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .4
                        });
                        this.linkNode.text(this.source.label);
                        this.linkNode.prop("disabled", !this.source.enabled);
                        this.linkNode.css({
                            color: this.source.foreColor,
                            fontName: this.source.fontName,
                            fontSize: this.source.fontSize,
                            textAlign: this.source.textAlignment
                        });
                        this.linkNode.on(Jade.BrowserEvent.MOUSEENTER, () => {
                            this.linkNode.css({ color: this.source.hoverForeColor });
                        });
                        this.linkNode.on(Jade.BrowserEvent.MOUSELEAVE, () => {
                            this.linkNode.css({ color: this.source.foreColor });
                        });
                        this.linkNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.linkNode, this.source.tooltip);
                        }
                    }
                    onClick(e) {
                        if (this.source.enabled && this.source.hasOnClickAction) {
                            PDJS.Shared.Actions.Action.invoke(this.source.onClickAction);
                        }
                    }
                };
                Hyperlink = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Core.IFocusableGuard)
                ], Hyperlink);
                Common.Hyperlink = Hyperlink;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                class Image extends Actual.ElementViewBase {
                    get imageNode() {
                        return this.node.find("img");
                    }
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;text-align:center;">
                        <img style="height:100%;"/>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.imageNode.prop("src", this.getImageUrl());
                        this.imageNode.prop("disabled", this.source.enabled);
                        this.imageNode.css({
                            borderRadius: borderRadius
                        });
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .5
                        });
                        this.imageNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.imageNode, this.source.tooltip);
                        }
                    }
                    onClick(e) {
                        if (this.source.enabled && this.source.hasOnClickAction) {
                            PDJS.Shared.PopOver.hide(this.imageNode);
                            PDJS.Shared.Actions.Action.invoke(this.source.onClickAction);
                        }
                    }
                    getImageUrl() {
                        let result = null;
                        if (this.source.imageUrl == null) {
                            result = Jade.Path.resolve("~/application/icons/misc/1024x1024/photo_portrait.png");
                        }
                        else {
                            if (this.source.imageUrl.indexOf("/") === 0) {
                                result = Jade.Path.resolve(`~/resources${this.source.imageUrl}`);
                            }
                            else if (this.source.imageUrl.indexOf("~") === 0) {
                                result = Jade.Path.resolve(this.source.imageUrl);
                            }
                            else {
                                result = Jade.Path.resolve(`~/resources/${this.source.imageUrl}`);
                            }
                        }
                        return result;
                    }
                }
                Common.Image = Image;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                class Markup extends Actual.ElementViewBase {
                    get contentNode() {
                        return this.node.find("[role=content]");
                    }
                    template() {
                        return `<div>
                        <div role="content"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.contentNode.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            color: "var(--visiv-theme-base-1-text-color)",
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: `${this.source.borderWidth}px`,
                            padding: `${this.source.padding}px`,
                            overflow: this.source.scrolling == "none" ? "none" : "auto",
                            overflowX: this.source.scrolling == "horizontal" ? "scroll" : "hidden",
                            overflowY: this.source.scrolling == "vertical" ? "scroll" : "hidden"
                        });
                        this.contentNode.html(this.source.markup);
                    }
                }
                Common.Markup = Markup;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                class Report extends Actual.ElementViewBase {
                    get reportNode() {
                        return this.node.find("[role=report]");
                    }
                    get iframeNode() {
                        return this.node.find("iframe");
                    }
                    get iframeID() {
                        return `iframe-${this.ID}`;
                    }
                    get iframeElement() {
                        return document.getElementById(this.iframeID);
                    }
                    template() {
                        return `<div class="-pdjs-canvas-report">
                        <div role="report">
                            <iframe id="${this.iframeID}" style="height:100%;width:100%;border:0 transparent;" />
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.informationBar_init();
                        this.subscriptions.add(PDJS.Shared.Themes.EventsHub.setThemeSubscribe(() => {
                            this.loadReport(true);
                        }));
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (this.source.data == null) {
                            this.showLoadingMessage();
                            this.source.getCachedData({
                                success: (e) => {
                                    this.m_informationBar.update();
                                    this.showElementErrors(e.errors);
                                }
                            });
                        }
                        else {
                            this.loadReport();
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.reportNode.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: this.source.informationBarVisible ? "25px" : "0",
                            color: "var(--visiv-theme-base-1-text-color)",
                            backgroundColor: "var(--visiv-theme-base-1-back-color)",
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth
                        });
                        this.loadReport();
                    }
                    loadReport(reload = false) {
                        let content = `
                    <link type="text/css" rel="stylesheet" href="${Jade.Path.resolve("~/shared/theme/hub", { v: reload ? Jade.Guid.new() : "" })}">
                    <style>
                        body {
                            background-color: var(--visiv-theme-base-1-back-color);
                            color: var(--visiv-theme-base-1-text-color);
                        }
                    </style>
                    ${this.source.data}
                    <script> function printContent() { window.print(); }</script>
                `;
                        if (this.iframeElement != null && this.iframeElement.contentDocument != null) {
                            this.iframeElement.contentDocument.clear();
                            this.iframeElement.contentDocument.open();
                            this.iframeElement.contentDocument.write(content);
                            this.iframeElement.contentDocument.close();
                        }
                        this.hideLoadingMessage();
                    }
                    hideLoadingMessage() {
                        if (this.m_message != null && this.source.cacheRefreshStatus != Canvas.Core.CachedElementRefreshStatus.Pending) {
                            this.controls.remove(this.m_message);
                        }
                    }
                    showLoadingMessage() {
                        this.hideLoadingMessage();
                        this.m_message = new PDJS.Shared.UI.Controls.LoadingMessageControl({
                            message: "Loading...",
                            margin: parseInt(this.source.borderWidth)
                        });
                        this.controls.add(this.m_message);
                    }
                    menu_init() {
                        if (!this.source.actionMenuVisible) {
                            return;
                        }
                        this.m_menu = new Canvas.Shared.ElementMenu({
                            position: Canvas.Shared.ElementMenuPosition.topRight,
                            visible: true,
                            loaded: () => {
                                this.m_menu.node.css({
                                    backgroundColor: "var(--visiv-theme-base-1-back-color)",
                                    height: "26px",
                                    width: "26px",
                                    right: 0,
                                    top: 0,
                                    padding: "4px",
                                    border: "1px solid var(--visiv-theme-input-border-color)"
                                });
                            }
                        });
                        if (this.source.actionMenuRefresh) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                icon: "refresh.16px.font",
                                label: "Refresh",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    this.showLoadingMessage();
                                    this.source.getCachedData({
                                        force: true,
                                        success: (e) => {
                                            this.showElementErrors(e.errors);
                                        }
                                    });
                                }
                            }));
                        }
                        if (this.source.actionMenuPrint) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                icon: "print.16px.font",
                                label: "Print...",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    setTimeout(() => {
                                        var iframe = window.frames ? window.frames[this.iframeID] : document.getElementById(this.iframeID);
                                        var ifWin = iframe.contentWindow || iframe;
                                        ifWin.focus();
                                        ifWin.printContent();
                                    }, 200);
                                    return false;
                                }
                            }));
                        }
                        if (this.source.actionMenuOpen) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                label: "Open in new window",
                                icon: "arrow-right.16px.font",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    setTimeout(() => {
                                        let reportWindow = window.open("", this.ID, "");
                                        reportWindow.document.clear();
                                        reportWindow.document.open();
                                        reportWindow.document.write(this.source.data);
                                        reportWindow.document.close();
                                    }, 100);
                                }
                            }));
                        }
                        let boardContent = () => {
                            return `<div class="-pdjs-canavas-element-menu-item-last-updated">
                            <b>Last Updated:</b><br/>
                            ${kendo.toString(new Date(this.source.cacheLastUpdated), "g")}
                        </div>`;
                        };
                        this.m_menu.items.add(new Canvas.Shared.ElementMenuItemBoard({
                            content: boardContent(),
                            show: (e) => {
                                e.content = boardContent();
                            }
                        }));
                        this.controls.add(this.m_menu);
                    }
                    informationBar_init() {
                        this.m_informationBar = new Canvas.Shared.ElementBar({
                            source: this.source,
                            showRefresh: this.source.informationBarRefresh,
                            visible: this.source.informationBarVisible,
                            onRefresh: () => {
                                this.showLoadingMessage();
                                this.source.getCachedData({
                                    force: true,
                                    success: (e) => {
                                        this.m_informationBar.update();
                                        this.showElementErrors(e.errors);
                                    }
                                });
                            }
                        });
                        this.controls.add(this.m_informationBar);
                    }
                }
                Common.Report = Report;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Common;
            (function (Common) {
                class Text extends Actual.ElementViewBase {
                    get contentNode() {
                        return this.node.find("DIV[role=content]");
                    }
                    get containerNode() {
                        return this.node.find("DIV[role=container]");
                    }
                    template() {
                        return `<div class="${Canvas.Shared.CanvasCss.TextElement}">
                        <div role="container">
                            <div role="content"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let noBorder = this.source.borderStyle == "none";
                        this.contentNode.css({
                            width: "100%",
                            textAlign: this.source.horizontalAlignment
                        });
                        this.containerNode.css({
                            display: "flex",
                            flexWrap: "wrap",
                            alignItems: this.source.verticalAlignment,
                            position: "absolute",
                            boxSizing: "border-box",
                            maxWidth: "border-box",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            borderStyle: this.source.borderStyle,
                            borderWidth: noBorder ? "0" : `${this.source.borderWidth}`,
                            paddingTop: this.source.paddingTop == 0 ? 0 : `${this.source.paddingTop}px`,
                            paddingRight: this.source.paddingRight == 0 ? 0 : `${this.source.paddingRight}px`,
                            paddingBottom: this.source.paddingBottom == 0 ? 0 : `${this.source.paddingBottom}px`,
                            paddingLeft: this.source.paddingLeft == 0 ? 0 : `${this.source.paddingLeft}px`
                        });
                        let element = this.containerNode.get(0);
                        element.style.backgroundColor =
                            this.source.backgroundColor == null ? "transparent" : `${this.source.backgroundColor}`;
                        element.style.borderColor = noBorder ? "var(--visiv-theme-base-1-text-color)" :
                            this.source.borderColor == null ? "transparent" : `${this.source.borderColor}`;
                        this.contentNode.html(this.source.text);
                    }
                }
                Common.Text = Text;
            })(Common = Actual.Common || (Actual.Common = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                let FormElementBase = class FormElementBase extends Actual.ElementViewBase {
                    constructor(options) {
                        super(options);
                    }
                    get formId() {
                        return this.source.formId;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                };
                FormElementBase = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Core.IFocusableGuard)
                ], FormElementBase);
                Forms.FormElementBase = FormElementBase;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class Form {
                    static submit(args) {
                        let buttons = this.getFormButtons(args.document, args.formId);
                        if (buttons.length == 0) {
                            return;
                        }
                        this.setButtonsEnabled(buttons, false);
                        let oldState = CanvasJS.Actual.Environment.document.source.toJSON();
                        args.document.source.saveForm({
                            entityId: args.document.entityId,
                            formButtonId: args.buttonId,
                            onSuccess: (e) => {
                                Actual.CanvasRefresh.populate(_.extend(e, {
                                    formId: args.formId,
                                    document: e.document
                                }));
                                Forms.FormFieldAnimation.start(args.formId, 1500, Forms.FormFieldAnimationType.success);
                                this.reloadElementStatesAfterPost(oldState);
                                this.setButtonsEnabled(buttons);
                                this.resetFormFieldValueChangedState(args.document, args.formId);
                                let response = new PDJS.Shared.Rules.ScriptResponse(e);
                                response.handle();
                            },
                            onValidationError: (e) => {
                                Actual.CanvasRefresh.validate({
                                    validationErrors: e.validationErrors
                                });
                                Forms.FormFieldAnimation.start(args.formId, 1500, Forms.FormFieldAnimationType.error);
                                this.reloadElementStatesAfterPost(oldState);
                                this.setButtonsEnabled(buttons);
                            },
                            onScriptError: (e) => {
                                Forms.FormFieldAnimation.start(args.formId, 1500, Forms.FormFieldAnimationType.error);
                                let response = new PDJS.Shared.Rules.ScriptResponse(e);
                                response.handle();
                                this.setButtonsEnabled(buttons);
                            },
                            onError: () => {
                                Forms.FormFieldAnimation.stop(args.formId);
                                this.setButtonsEnabled(buttons);
                            }
                        });
                    }
                    static getFormButtons(document, formId) {
                        let result = [];
                        document.controls.each((control) => {
                            if (control instanceof Forms.FormButton && control.formId === formId) {
                                result[result.length] = control;
                            }
                        });
                        return result;
                    }
                    static setButtonsEnabled(buttons, enabled = null) {
                        _.each(buttons, (view) => {
                            view.buttonNode.prop("disabled", enabled !== null ? !enabled : !view.source.activeEnabledState);
                        });
                    }
                    static resetFormFieldValueChangedState(document, formId) {
                        document.controls.each((control) => {
                            if (control instanceof Forms.FormField && control.formId === formId) {
                                control.source.valueChanged = false;
                            }
                        });
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .publish("canvas/form/reset", {
                            formId: formId
                        });
                    }
                    static reloadElementStatesAfterPost(oldState) {
                        let oldDocument = new Canvas.Core.Documents.ActualDocument(oldState);
                        let newDocument = CanvasJS.Actual.Environment.document.source;
                        let oldModels = {};
                        oldDocument.elements.each((oldModel) => {
                            if (oldModel.reloadModelAfterPost) {
                                oldModels[oldModel.id] = oldModel;
                            }
                        });
                        newDocument.elements.each((newModel) => {
                            if (newModel.reloadModelAfterPost) {
                                let oldModel = oldModels[newModel.id];
                                if (oldModel != null) {
                                    newModel.reloadModel(oldModel);
                                }
                            }
                        });
                    }
                }
                Forms.Form = Form;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormButton extends Forms.FormElementBase {
                    get acceptsFocus() {
                        return this.source.activeEnabledState;
                    }
                    get buttonIconNode() {
                        return this.buttonNode.find("div:nth-child(2)");
                    }
                    get buttonImageNode() {
                        return this.buttonIconNode.find("img");
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get buttonTextNode() {
                        return this.buttonNode.find("div:nth-child(3)");
                    }
                    get imageUrl() {
                        return Jade.Path.resolve(`~/resources/${this.source.image}`);
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-form-button">
                        <button tabIndex="${this.source.activeTabIndex}">
                            <div></div>
                            <div><img/></div>
                            <div></div>
                            <div></div>
                        </button>
                    </div>`;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.node, this.source.tooltip);
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.buttonNode.prop("disabled", !this.source.activeEnabledState);
                        this.buttonNode.css({
                            borderRadius: borderRadius
                        });
                        if (this.source.hasImage) {
                            this.buttonImageNode.show();
                            this.buttonImageNode.attr("src", this.imageUrl);
                        }
                        else {
                            this.buttonImageNode.hide();
                        }
                        if (this.source.hasLabel) {
                            this.buttonTextNode.show();
                            this.buttonTextNode.text(this.source.label);
                        }
                        else {
                            this.buttonTextNode.hide();
                        }
                        this.buttonImageNode.css({
                            maxWidth: this.buttonNode.width(),
                            maxHeight: this.buttonNode.height()
                        });
                        this.source.hasImage && this.source.hasLabel ?
                            this.buttonIconNode.css({ paddingRight: "5px" }) :
                            this.buttonIconNode.css({ paddingRight: "0" });
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.node, this.source.tooltip);
                        }
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        PDJS.Shared.PopOver.remove(this.node);
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                    onClick(e) {
                        PDJS.Shared.PopOver.hide(this.node.get(0));
                        this.signalSubmit();
                        this.submit();
                    }
                    signalSubmit() {
                        CanvasJS.Actual.Environment
                            .document
                            .controls
                            .each((element) => {
                            if (element instanceof Forms.FormField && element.formId == this.formId) {
                                element.onSubmit();
                            }
                        });
                        Forms.FormFieldAnimation.start(this.source.formId, 0, Forms.FormFieldAnimationType.pending);
                    }
                    submit() {
                        Forms.Form.submit({
                            document: CanvasJS.Actual.Environment.document,
                            buttonId: this.ID,
                            formId: this.formId
                        });
                    }
                }
                Forms.FormButton = FormButton;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormField extends Forms.FormElementBase {
                    constructor() {
                        super(...arguments);
                        this.m_validationErrors = new Jade.ObservableCollection(null, {
                            onAfterAdd: (e) => {
                                this.onValidationErrorChange();
                            },
                            onAfterRemove: (e) => {
                                this.onValidationErrorChange();
                            }
                        });
                    }
                    get formId() {
                        return this.source.formId;
                    }
                    get validationErrors() {
                        return this.m_validationErrors;
                    }
                    get labelNode() {
                        return this.formFieldNode.children("div[role=label]");
                    }
                    get controlNode() {
                        return this.formFieldNode.children("div[role=control]");
                    }
                    get deck() {
                        return this.m_deck;
                    }
                    get formFieldNode() {
                        return this.node.find(`.${Canvas.Shared.CanvasCss.FormField}`);
                    }
                    get acceptsFocus() {
                        return this.source.activeEnabledState;
                    }
                    focus() {
                    }
                    onSubmit() {
                    }
                    template() {
                        return `<div class="${Canvas.Shared.CanvasCss.FormField}">
                        <div role="label">${this.source.activeLabel}:</div>
                        <div role="control" data-controls>
                        </div>
                    </div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.deck_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.labelNode.text(`${this.source.activeLabel}:`);
                        this.labelNode.css({
                            color: this.source.activeLabelColor
                        });
                        if (this.source.activeEnabledState) {
                            this.formFieldNode.removeClass(PDJS.Shared.UI.CssClass.Disabled);
                        }
                        else {
                            this.formFieldNode.addClass(PDJS.Shared.UI.CssClass.Disabled);
                        }
                    }
                    onValidationErrorChange() {
                        if (this.validationErrors.count > 0) {
                            let errors = `<div>${this.validationErrors.toArray().join("<br/>")}</div>`;
                            PDJS.Shared.PopOver.validation(this.labelNode, errors);
                            this.node.addClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                        }
                        else {
                            PDJS.Shared.PopOver.remove(this.labelNode);
                            this.node.removeClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: ""
                            });
                        }
                    }
                    deck_init() {
                        this.m_deck = new Forms.FormFieldDeck({
                            insertAt: `.${Canvas.Shared.CanvasCss.FormField}`
                        });
                        this.controls.add(this.m_deck);
                        this.deck.controls.add(new Forms.FormFieldToolTip({
                            formField: this
                        }));
                    }
                }
                Forms.FormField = FormField;
                class FormFieldBase extends FormField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.FormFieldBase = FormFieldBase;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class BuiltInField extends Forms.FormFieldBase {
                }
                Forms.BuiltInField = BuiltInField;
                class BuildInFieldBase extends BuiltInField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.BuildInFieldBase = BuildInFieldBase;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class ExtensionField extends Forms.FormFieldBase {
                    onActivate(e) {
                        super.onActivate(e);
                        this.source.inBatchMode = CanvasJS
                            .Actual
                            .Environment
                            .document
                            .state
                            .get("isBatchMode");
                        this.deck.controls.add(new Forms.FormFieldBatchEdit({
                            extensionField: this
                        }));
                    }
                }
                Forms.ExtensionField = ExtensionField;
                class ExtensionFieldBase extends ExtensionField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.ExtensionFieldBase = ExtensionFieldBase;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityDescriptionField extends Forms.BuildInFieldBase {
                    get inputNode() {
                        return this.node.find("textarea");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.controlNode.append(`<textarea 
                                        tabIndex="${this.source.activeTabIndex}"
                                        class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" 
                                        style="overflow-y:scroll;">
                                        ${this.source.value}
                                    </textarea>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.input_onBlur, this));
                        this.inputNode.val(this.source.value);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                    focus() {
                        this.inputNode.focus();
                    }
                    input_onBlur(e) {
                        this.source.value = this.inputNode.val();
                    }
                }
                Forms.EntityDescriptionField = EntityDescriptionField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityIconField extends Forms.BuildInFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    focus() {
                        this.comboBox.focusMask();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.value != null) {
                            this.comboBox.selection = {
                                icon: this.source.value,
                                name: this.source.value.replace("_", " ")
                            };
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                        this.comboBox.tabIndex = this.source.activeTabIndex;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityIconFieldComboBox({
                            defaultMask: "Select...",
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                            onSelectionChanged: (e) => {
                                this.source.value = e != null ? e.icon : null;
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                }
                Forms.EntityIconField = EntityIconField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityNameField extends Forms.BuildInFieldBase {
                    get inputNode() {
                        return this.node.find("input[type=text]");
                    }
                    focus() {
                        this.inputNode.focus();
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.controlNode.append(`<input 
                                        type="text"
                                        value="${this.source.value}" 
                                        tabIndex="${this.source.activeTabIndex}"
                                        class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" />`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.input_onBlur, this));
                        this.inputNode.val(this.source.value);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                    input_onBlur(e) {
                        this.source.value = this.inputNode.val();
                    }
                }
                Forms.EntityNameField = EntityNameField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityParentField extends Forms.BuildInFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    get navigate() {
                        return this.m_navigate;
                    }
                    focus() {
                        this.comboBox.showMask();
                        this.comboBox.focusMask();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                        this.navigate_init();
                        this.source.activeLabel === "Parent:" ?
                            this.comboBox.defaultMask = `Select Parent...` :
                            this.comboBox.defaultMask = `Select ${this.source.activeLabel}...`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.parentId != null) {
                            this.comboBox.selection = {
                                entityID: this.source.parentId,
                                entityName: this.source.parentName,
                                entityTypeIcon: this.source.parentTypeIcon,
                                entityTypeName: this.source.parentTypeName,
                                entityTypeId: null
                            };
                        }
                        this.node.addClass("-pdjs-canvas-shared-entity-parent-field");
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                        this.navigate.entityId = this.source.parentId;
                        this.navigate.entityName = this.source.parentName;
                        this.comboBox.tabIndex = this.source.activeTabIndex;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityParentFieldComboBox({
                            defaultMask: "Select...",
                            entityTypeId: this.source.entityTypeId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                            onSelectionChanged: (selection) => {
                                this.source.parentId = selection != null ? selection.entityID : null;
                                this.source.parentName = selection != null ? selection.entityName : "";
                                this.publishEntityParentChangedEvent();
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                    navigate_init() {
                        this.m_navigate = new Canvas.Shared.Forms.NavigateLink({});
                        this.controls.add(this.m_navigate);
                    }
                    publishEntityParentChangedEvent() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .publish(EntityParentField.PARENT_CHANGED_EVENT, {
                            parentId: this.source.parentId,
                            entityTypeId: this.source.entityTypeId
                        });
                    }
                }
                EntityParentField.PARENT_CHANGED_EVENT = "canavas-entity-parent-field-value-changed";
                Forms.EntityParentField = EntityParentField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityProcessField extends Forms.BuildInFieldBase {
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_assignment = new Canvas.Shared.Forms.EntityProcessField({
                            tabIndex: this.source.activeTabIndex,
                            entityTypeId: this.source.entityTypeId,
                            keyIcon: this.source.keyIcon,
                            keyName: this.source.keyName,
                            processName: this.source.processName,
                            stageId: this.source.stageId,
                            stageName: this.source.stageName,
                            stageIcon: this.source.stageIcon,
                            statusId: this.source.statusId,
                            statusName: this.source.statusName,
                            statusIcon: this.source.statusIcon,
                            showKey: this.source.showKey,
                            showProcess: this.source.showProcess,
                            showStage: this.source.showStage,
                            showStatus: this.source.showStatus,
                            onChange: () => {
                                this.source.stageId = this.m_assignment.stageId;
                                this.source.statusId = this.m_assignment.statusId;
                            }
                        });
                        this.controls.add(this.m_assignment);
                    }
                }
                Forms.EntityProcessField = EntityProcessField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class BooleanField extends Forms.ExtensionFieldBase {
                    get itemLabelNode() {
                        return this.controlNode.find("div[role=input-label]");
                    }
                    get checkboxNode() {
                        return this.controlNode.find("input[type=checkbox]");
                    }
                    focus() {
                        this.checkboxNode.focus();
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BooleanField);
                        this.controlNode.append(`<label class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}">
                                        <input type="checkbox" tabIndex="${this.source.activeTabIndex}" />
                                        <div role="input-label">
                                            ${this.source.itemLabel}
                                        </div>
                                    </label>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let iconPath = null;
                        if (this.source.itemIcon != null) {
                            iconPath = Jade.IconSet.get("pd")
                                .resolve(this.source.itemIcon, Jade.IconSetSizeSpecificDirectory.x16);
                            this.itemLabelNode.css({
                                paddingLeft: "24px",
                                backgroundImage: `url(${iconPath})`,
                                backgroundRepeat: "no-repeat",
                                backgroundPosition: "3px 3px"
                            });
                        }
                        else {
                            this.itemLabelNode.css({
                                paddingLeft: "4px"
                            });
                        }
                        this.checkboxNode.prop("checked", this.source.value);
                        this.checkboxNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.source.value = this.checkboxNode.prop("checked");
                        });
                        this.checkboxNode.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.controlNode.addClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                        this.checkboxNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.controlNode.removeClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BooleanField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.checkboxNode.prop("disabled", !this.source.activeEnabledState);
                    }
                }
                Forms.BooleanField = BooleanField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class DateField extends Forms.ExtensionFieldBase {
                    get format() {
                        return this.source.format || this.source.columnFormat;
                    }
                    focus() {
                        this.m_dateTextBox.maskNode.focus();
                    }
                    onSubmit() {
                        this.validationErrors.clear();
                        this.source.value = this.m_dateTextBox.value;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_dateTextBox = new PDJS.Shared.UI.Controls.DateTextBox({
                            insertAt: "[role=control]",
                            format: this.format,
                            onChange: (e) => {
                                this.source.value = e.value;
                            }
                        });
                        this.controls.add(this.m_dateTextBox);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_dateTextBox.setValue(this.source.value);
                        this.m_dateTextBox.tabIndex = this.source.activeTabIndex;
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.DateField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_dateTextBox.enabled = this.source.activeEnabledState;
                    }
                }
                Forms.DateField = DateField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class DecimalField extends Forms.ExtensionFieldBase {
                    get textBox() {
                        return this.m_numericTextBox;
                    }
                    focus() {
                        this.m_numericTextBox.focusText();
                        this.m_numericTextBox.showText();
                    }
                    onSubmit() {
                        this.validationErrors.clear();
                        this.source.value = this.textBox.getValue();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.decimal,
                            format: this.source.activeFormat,
                            change: (value) => {
                                this.source.value = value;
                            }
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.textBox.setValue(this.source.value);
                        this.textBox.tabIndex = this.source.activeTabIndex;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.textBox.enabled = this.source.activeEnabledState;
                    }
                }
                Forms.DecimalField = DecimalField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class EntityField extends Forms.ExtensionFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    get navigate() {
                        return this.m_navigate;
                    }
                    focus() {
                        this.comboBox.focusMask();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                        this.navigate_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.entityId != null) {
                            this.comboBox.selection = {
                                entityID: this.source.entityId,
                                entityName: this.source.entityName,
                                entityTypeIcon: this.source.entityTypeIcon,
                                entityTypeName: this.source.entityTypeName
                            };
                        }
                        this.comboBox.tabIndex = this.source.activeTabIndex;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                        this.navigate.entityId = this.source.entityId;
                        this.navigate.entityName = this.source.entityName;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityFieldComboBox({
                            defaultMaskText: "Select...",
                            viewId: this.source.viewId,
                            viewStateId: this.source.viewStateId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                            onSelectionChanged: (selection) => {
                                this.source.entityId = selection != null ? selection.entityID : null;
                                this.source.entityName = selection != null ? selection.entityName : "";
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                    navigate_init() {
                        this.m_navigate = new Canvas.Shared.Forms.NavigateLink({});
                        this.controls.add(this.m_navigate);
                    }
                }
                Forms.EntityField = EntityField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class Int32Field extends Forms.ExtensionFieldBase {
                    get format() {
                        return this.source.format || this.source.columnFormat;
                    }
                    get originalValue() {
                        return this.state.get("originalValue");
                    }
                    set originalValue(value) {
                        this.state.set("originalValue", value);
                    }
                    focus() {
                        this.m_numericTextBox.focusText();
                        this.m_numericTextBox.showText();
                    }
                    onSubmit() {
                        this.validationErrors.clear();
                        this.source.value = this.m_numericTextBox.getValue();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer,
                            format: this.format,
                            change: (value) => {
                                this.source.value = value;
                            }
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_numericTextBox.setValue(this.source.value);
                        this.m_numericTextBox.tabIndex = this.source.activeTabIndex;
                        this.originalValue = this.source.value;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_numericTextBox.enabled = this.source.activeEnabledState;
                    }
                }
                Forms.Int32Field = Int32Field;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class Int64Field extends Forms.ExtensionFieldBase {
                    focus() {
                        this.m_numericTextBox.focusText();
                        this.m_numericTextBox.showText();
                    }
                    onSubmit() {
                        this.validationErrors.clear();
                        this.source.value = this.m_numericTextBox.getValue();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer,
                            format: this.source.activeFormat,
                            change: (value) => {
                                this.source.value = value;
                            }
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_numericTextBox.setValue(this.source.value);
                        this.m_numericTextBox.tabIndex = this.source.activeTabIndex;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_numericTextBox.enabled = this.source.activeEnabledState;
                    }
                }
                Forms.Int64Field = Int64Field;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class MultiSelectField extends Forms.ExtensionFieldBase {
                    get multiSelect() {
                        return this.m_multiSelect;
                    }
                    focus() {
                        this.multiSelect.focus();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.init_multiSelect();
                    }
                    onAttach(e) {
                        this.controlNode.addClass(Canvas.Shared.CanvasCss.FormFieldAnimationTarget);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.controlNode.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.controlNode.addClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                        this.controlNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.controlNode.removeClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                        this.multiSelect.items.each((item) => {
                            item.checked = this.source.value.indexOf(item.itemId) > -1;
                        });
                        this.multiSelect.node.addClass(Canvas.Shared.CanvasCss.FormFieldAnimationTarget);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.multiSelect.enabled = this.source.activeEnabledState;
                        this.multiSelect.tabIndex = this.source.activeTabIndex;
                    }
                    init_multiSelect() {
                        this.m_multiSelect = new PDJS.Shared.UI.Controls.MultiSelect({
                            onItemChecked: (e) => {
                                this.source.value = [];
                                this.multiSelect.items.each((item) => {
                                    if (item.checked) {
                                        this.source.value[this.source.value.length] = item.itemId;
                                    }
                                });
                            }
                        });
                        this.controls.add(this.m_multiSelect);
                        _.each(this.source.items, (item) => {
                            this.multiSelect.controls.add(new PDJS.Shared.UI.Controls.MultiSelectItem({
                                itemId: item.id,
                                label: item.label,
                                icon: item.icon
                            }));
                        });
                    }
                }
                Forms.MultiSelectField = MultiSelectField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class SingleSelectField extends Forms.ExtensionFieldBase {
                    focus() {
                        this.m_comboBox.focusMask();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let selectedItem = this.source.getSelectedItem();
                        this.m_comboBox.selection = selectedItem;
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.SingleSelectField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_comboBox.enabled = this.source.activeEnabledState;
                        this.m_comboBox.tabIndex = this.source.activeTabIndex;
                    }
                    comboBox_init() {
                        this.m_comboBox = new PDJS.Shared.UI.Controls.SingleSelectList({
                            defaultMask: "Select...",
                            data: this.source.items,
                            onCreateListItem(e) {
                                return new PDJS.Shared.UI.Controls.SingleSelectListItem({
                                    data: e
                                });
                            },
                            onSelectionChanged: (selection) => {
                                if (selection != null) {
                                    this.source.selectedId = selection.id;
                                }
                                else {
                                    this.source.selectedId = null;
                                }
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                }
                Forms.SingleSelectField = SingleSelectField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class StringField extends Forms.ExtensionFieldBase {
                    get inputNode() {
                        return this.source.multiLine ? this.textareaNode : this.textNode;
                    }
                    get textareaNode() {
                        return this.controlNode.children("textarea[role=text]");
                    }
                    get textNode() {
                        return this.controlNode.children("input[role=text]");
                    }
                    focus() {
                        this.inputNode.focus();
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.controlNode.append(`
                <textarea
                    role="text"
                    tabIndex="${this.source.activeTabIndex}"
                    class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}"
                    style="overflow-y:scroll;">
                    </textarea>
                <input
                    role="text"
                    type="text"
                    tabIndex="${this.source.activeTabIndex}"
                    class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" />
            `);
                        this.source.multiLine ?
                            this.textNode.hide() :
                            this.textareaNode.hide();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.controlNode.on(Jade.BrowserEvent.BLUR, "[role=text]", _.bind(this.input_onBlur, this));
                        this.controlNode.on(Jade.BrowserEvent.FOCUS, "[role=text]", _.bind(this.input_onFocus, this));
                        this.inputNode.val(this.source.value);
                    }
                    onSubmit() {
                        this.source.value = this.inputNode.val();
                        this.validationErrors.clear();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.controlNode.addClass(this.source.multiLine ? "multiline" : "singleline");
                        this.controlNode.removeClass(this.source.multiLine ? "singleline" : "multiline");
                        this.inputNode.val(this.source.value);
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                    input_onBlur(e) {
                        this.source.value = this.inputNode.val();
                        this.inputNode.removeClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                    input_onFocus(e) {
                        this.inputNode.addClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                }
                Forms.StringField = StringField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class UserField extends Forms.ExtensionFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    focus() {
                        this.comboBox.focusMask();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.userId != null) {
                            this.comboBox.selection = {
                                userID: this.source.userId,
                                userName: this.source.userName
                            };
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_comboBox.enabled = this.source.activeEnabledState;
                        this.m_comboBox.tabIndex = this.source.activeTabIndex;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.UserFieldComboBox({
                            defaultMaskText: "Select...",
                            viewId: this.source.viewId,
                            viewStateId: this.source.viewStateId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                            onSelectionChanged: (selection) => {
                                this.source.userId = selection != null ? this.m_comboBox.selection.userID : null;
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                }
                Forms.UserField = UserField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                let FormFieldAnimationType;
                (function (FormFieldAnimationType) {
                    FormFieldAnimationType["none"] = "";
                    FormFieldAnimationType["pending"] = "-pdjs-form-submit-pending";
                    FormFieldAnimationType["error"] = "-pdjs-form-submit-error";
                    FormFieldAnimationType["success"] = "-pdjs-form-submit-success";
                })(FormFieldAnimationType = Forms.FormFieldAnimationType || (Forms.FormFieldAnimationType = {}));
                class FormFieldAnimation {
                    static start(formId, autoStop, animation = FormFieldAnimationType.none) {
                        this.iterateFormFields(formId, (field) => {
                            field.node.removeClass(FormFieldAnimationType.error);
                            field.node.removeClass(FormFieldAnimationType.success);
                            field.node.removeClass(FormFieldAnimationType.pending);
                            if (animation != FormFieldAnimationType.none) {
                                field.node.addClass(animation);
                            }
                        });
                        if (autoStop > 0) {
                            Jade.ContextManager.setTimeout(() => {
                                this.stop(formId, animation);
                            }, autoStop);
                        }
                    }
                    static stop(formId, animation = FormFieldAnimationType.none) {
                        if (animation == FormFieldAnimationType.pending) {
                            return;
                        }
                        this.iterateFormFields(formId, (element) => {
                            element.node.removeClass(FormFieldAnimationType.error);
                            element.node.removeClass(FormFieldAnimationType.success);
                            element.node.removeClass(FormFieldAnimationType.pending);
                        });
                    }
                    static iterateFormFields(formId, callback) {
                        if (CanvasJS.Actual.Environment.document == null) {
                            return;
                        }
                        CanvasJS.Actual.Environment.document.controls.each((element) => {
                            if (element instanceof Forms.FormField && element.formId == formId) {
                                if (_.isFunction(callback)) {
                                    callback(element);
                                }
                            }
                        });
                    }
                }
                Forms.FormFieldAnimation = FormFieldAnimation;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormFieldDeckItem extends Jade.UI.Control {
                }
                Forms.FormFieldDeckItem = FormFieldDeckItem;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormFieldBatchEdit extends Forms.FormFieldDeckItem {
                    constructor(options) {
                        super(options);
                    }
                    get extensionField() {
                        return this.state.get("extensionField");
                    }
                    get checkBoxNode() {
                        return this.node.find("input");
                    }
                    get inBatch() {
                        return this.checkBoxNode.is(":checked");
                    }
                    get isVisible() {
                        return !this.extensionField.source.isDisabled
                            && !this.extensionField.source.isReadOnly
                            && this.extensionField.source.inBatchMode;
                    }
                    template() {
                        return `<div class="-pd-form-field-deck-item" style="padding-top:7px;cursor:pointer;"><input type='checkbox'/></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.isVisible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                        this.checkBoxNode.on("click", _.bind(this.checkBox_onClick, this));
                    }
                    checkBox_onClick(e) {
                        this.extensionField.source.inBatch = this.inBatch;
                    }
                }
                Forms.FormFieldBatchEdit = FormFieldBatchEdit;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormFieldDeck extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    template() {
                        return `<div class="-pd-form-field-deck"></div>`;
                    }
                }
                Forms.FormFieldDeck = FormFieldDeck;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormFieldToolTip extends Forms.FormFieldDeckItem {
                    constructor(options) {
                        super(options);
                    }
                    get formField() {
                        return this.state.get("formField");
                    }
                    template() {
                        let tooltipIcon = Jade.IconSet.get("pdjs")
                            .resolve("question.png", Jade.IconSetSizeSpecificDirectory.x16);
                        return `<div class="-pd-form-field-deck-item" style="padding: 5px 1px 2px 1px;cursor:pointer;"><img src='${tooltipIcon}'/></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.formField.source.hasTooltip) {
                            this.node.show();
                            PDJS.Shared.PopOver.tooltip(this.node, this.formField.source.tooltip);
                        }
                        else {
                            this.node.hide();
                        }
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        PDJS.Shared.PopOver.remove(this.node);
                    }
                }
                Forms.FormFieldToolTip = FormFieldToolTip;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class FormFieldValidation {
                    static start(formId, autoStop, animation = Forms.FormFieldAnimationType.none) {
                        this.iterateFormFields(formId, (element) => {
                            element.node.removeClass(Forms.FormFieldAnimationType.error);
                            element.node.removeClass(Forms.FormFieldAnimationType.success);
                            element.node.removeClass(Forms.FormFieldAnimationType.pending);
                            if (animation != Forms.FormFieldAnimationType.none) {
                                element.node.addClass(animation);
                            }
                        });
                        if (autoStop > 0) {
                            setTimeout(() => {
                                this.stop(formId, animation);
                            }, autoStop);
                        }
                    }
                    static stop(formId, animation = Forms.FormFieldAnimationType.none) {
                        if (animation == Forms.FormFieldAnimationType.pending) {
                            return;
                        }
                        this.iterateFormFields(formId, (element) => {
                            element.node.removeClass(Forms.FormFieldAnimationType.error);
                            element.node.removeClass(Forms.FormFieldAnimationType.success);
                            element.node.removeClass(Forms.FormFieldAnimationType.pending);
                        });
                    }
                    static iterateFormFields(formId, callback) {
                        CanvasJS.Actual.Environment.document.controls.each((element) => {
                            if (element instanceof Forms.FormField && element.formId == formId) {
                                if (_.isFunction(callback)) {
                                    callback(element);
                                }
                            }
                        });
                    }
                }
                Forms.FormFieldValidation = FormFieldValidation;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class BatchField extends Forms.FormFieldBase {
                    get batch() {
                        return this.m_batch;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BatchField);
                        this.batch_init();
                    }
                    focus() {
                        this.batch.focus();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (!Jade.String.isNullOrWhiteSpace(this.source.filterTerm)) {
                            this.batch.filter.mask.showText();
                        }
                        if (this.source.isReloadingModel) {
                            this.batch.reload(this.source.listItems, this.source.filterTerm);
                        }
                    }
                    batch_init() {
                        this.m_batch = new PDJS.Shared.UI.Controls.BatchField({
                            dialogViewStateId: this.source.viewStateId,
                            dialogTitle: this.source.dialogTitle,
                            dialogHeight: this.source.dialogHeight,
                            dialogWidth: this.source.dialogWidth,
                            dialogFilters: this.source.contextFilters,
                            showCheckboxes: this.source.showCheckboxes,
                            change: (items) => {
                                this.source.listItems.splice(0, this.source.listItems.length);
                                items.forEach((item) => {
                                    this.source.listItems[this.source.listItems.length] = item;
                                });
                                this.source.filterTerm = this.batch.filter.value;
                            }
                        });
                        this.controls.add(this.batch);
                    }
                }
                Forms.BatchField = BatchField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class BatchFieldDialog extends Jade.UI.Dialogs.DialogOf {
                    get filters() {
                        return this.state.get("filters", []);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.getSelections().toArray();
                    }
                    template() {
                        return super.template(`
                <div style="position:absolute;inset:0;box-sizing:border-box;">
                    <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;">
                    
                    </div>
                    <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    static open(options) {
                        return new BatchFieldDialog(options);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[data-role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.ObjectId,
                                            name: item.ObjectName,
                                            type: item.ObjectType
                                        };
                                    });
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            },
                            needContext: (e) => {
                                _.each(this.filters, (item) => {
                                    e.filters[e.filters.length] = item.toJSON();
                                });
                            }
                        });
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Item Selected",
                                message: "No item has been selected. Select an item and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                }
                Forms.BatchFieldDialog = BatchFieldDialog;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Forms;
            (function (Forms) {
                class TextField extends Forms.FormFieldBase {
                    get inputNode() {
                        return this.node.find("[role=text]");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.controlNode.append(this.createInput());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.inputNode.val(this.source.value);
                    }
                    focus() {
                        this.inputNode.focus();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.controlNode.html(this.createInput());
                        this.controlNode.addClass(this.source.multiLine ? "multiline" : "singleline");
                        this.controlNode.removeClass(this.source.multiLine ? "singleline" : "multiline");
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                        if (!Jade.String.isNullOrWhiteSpace(this.source.value)) {
                            this.inputNode.val(this.source.value);
                        }
                    }
                    createInput() {
                        let result = "";
                        let cssClass = Canvas.Shared.CanvasCss.FormFieldAnimationTarget;
                        if (this.source.multiLine) {
                            result = `<textarea role="text" tabIndex="${this.source.activeTabIndex}" class="${cssClass}" style="overflow-y:scroll;"></textarea>`;
                        }
                        else {
                            result = `<input role="text" type="text"  tabIndex="${this.source.activeTabIndex}" class="${cssClass}" />`;
                        }
                        return result;
                    }
                    onSubmit() {
                        this.source.value = this.inputNode.val();
                        this.validationErrors.clear();
                    }
                }
                Forms.TextField = TextField;
            })(Forms = Actual.Forms || (Actual.Forms = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Process;
            (function (Process) {
                let DecisionButton = class DecisionButton extends Actual.ElementViewBase {
                    get acceptsFocus() {
                        return this.source.enabled;
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;">
                        <button style="height:100%;width:100%;box-sizing:border-box;" tabIndex="${this.source.activeTabIndex}"></button>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.text(this.source.activeLabel);
                        this.buttonNode.prop("disabled", !this.source.enabled);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            PDJS.Shared.PopOver.tooltip(this.node, this.source.tooltip);
                        }
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    onClick(e) {
                        if (this.source.enabled) {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                                title: "Execute Decision",
                                message: "Are you sure you want to execute this decision?",
                                select: (e) => {
                                    if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                                        this.executeDecision();
                                    }
                                    e.close();
                                }
                            });
                        }
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle("button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle("button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle("button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle("button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle("button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                    executeDecision() {
                        let service = new PDJS.Services.Process.ProcessService();
                        service.executeDecision({
                            decisionId: this.source.decisionId,
                            entityId: this.source.entityId,
                            success: (e) => {
                                let response = new PDJS.Canvas.Shared.Process.ExecuteDecisionResponse(e.data);
                                response.handle();
                            }
                        });
                    }
                };
                DecisionButton = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Core.IFocusableGuard)
                ], DecisionButton);
                Process.DecisionButton = DecisionButton;
            })(Process = Actual.Process || (Actual.Process = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Process;
            (function (Process) {
                class ProcessDecisions extends Actual.ElementViewBase {
                    template() {
                        return `<div class="-pdjs-canvas-process-decisions" style="position:absolute;inset:0;" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessDecisions({});
                        this.controls.add(this.m_view);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_view.load(this.source.toJSON());
                    }
                }
                Process.ProcessDecisions = ProcessDecisions;
            })(Process = Actual.Process || (Actual.Process = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Process;
            (function (Process) {
                let ProcessState = class ProcessState extends Actual.ElementViewBase {
                    template() {
                        return `<div class="-pdjs-canvas-process-state" style="position:absolute;inset:0;" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.currentStage == null) {
                            this.message_init();
                        }
                        else {
                            this.processState_init();
                        }
                    }
                    processState_init() {
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessState({});
                        this.controls.add(this.m_view);
                        this.m_view.load(this.source);
                    }
                    message_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.Message({
                            message: "Process has not been assigned."
                        }));
                        this.node.css({
                            color: "var(--visiv-theme-input-text-color)"
                        });
                    }
                };
                ProcessState = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], ProcessState);
                Process.ProcessState = ProcessState;
            })(Process = Actual.Process || (Actual.Process = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Process;
            (function (Process) {
                let ProcessView = class ProcessView extends Actual.ElementViewBase {
                    get acceptsFocus() {
                        return true;
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;" data-controls></div>`;
                    }
                    focus() {
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.currentStage == null) {
                            this.message_init();
                        }
                        else {
                            this.processView_init();
                        }
                    }
                    processView_init() {
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessView({});
                        this.controls.add(this.m_view);
                        this.m_view.load(this.source);
                    }
                    message_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.Message({
                            message: "Process has not been assigned."
                        }));
                        this.node.css({
                            backgroundColor: "var(--visiv-theme-input-back-color)",
                            border: "1px solid var(--visiv-theme-input-border-color)",
                            color: "var(--visiv-theme-input-text-color)"
                        });
                    }
                };
                ProcessView = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Core.IFocusableGuard)
                ], ProcessView);
                Process.ProcessView = ProcessView;
            })(Process = Actual.Process || (Actual.Process = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class Shape extends Actual.ElementViewBase {
                }
                Shapes.Shape = Shape;
                class ShapeBase extends Shape {
                    get source() {
                        return this.m_source;
                    }
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;"></div>`;
                    }
                }
                Shapes.ShapeBase = ShapeBase;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class Ellipse extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        let shape = new Canvas.Shared.Shapes.Ellipse({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth
                        });
                        this.controls.add(shape);
                    }
                }
                Shapes.Ellipse = Ellipse;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class Line extends Actual.ElementViewBase {
                    onInit(e) {
                        super.onInit(e);
                        let shape = new Canvas.Shared.Shapes.Line({
                            endCapShape: this.source.endCapShape,
                            endCapColor: this.source.endCapColor,
                            endCapHeight: this.source.endCapHeight,
                            endCapWidth: this.source.endCapWidth,
                            lineColor: this.source.lineColor,
                            lineWeight: this.source.lineWeight,
                            startCapColor: this.source.startCapColor,
                            startCapHeight: this.source.startCapHeight,
                            startCapShape: this.source.startCapShape,
                            startCapWidth: this.source.startCapWidth
                        });
                        this.controls.add(shape);
                    }
                }
                Shapes.Line = Line;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class Rectangle extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        let shape = new Canvas.Shared.Shapes.Rectangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            borderRadius: this.source.borderRadius
                        });
                        this.controls.add(shape);
                    }
                }
                Shapes.Rectangle = Rectangle;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class Triangle extends Shapes.ShapeBase {
                }
                Shapes.Triangle = Triangle;
                class TriangleBase extends Triangle {
                    get source() {
                        return this.source;
                    }
                }
                Shapes.TriangleBase = TriangleBase;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class IsoscelesTriangle extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        let shape = new Canvas.Shared.Shapes.IsoscelesTriangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            rotation: this.source.rotation,
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.controls.add(shape);
                    }
                }
                Shapes.IsoscelesTriangle = IsoscelesTriangle;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Shapes;
            (function (Shapes) {
                class RightTriangle extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        let shape = new Canvas.Shared.Shapes.RightTriangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            rotation: this.source.rotation,
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.controls.add(shape);
                    }
                }
                Shapes.RightTriangle = RightTriangle;
            })(Shapes = Actual.Shapes || (Actual.Shapes = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Actual;
        (function (Actual) {
            var Views;
            (function (Views) {
                class EventHistoryView extends Actual.ElementViewBase {
                    template() {
                        return `<div style="position:absolute;inset:0;" role="grid"></div>`;
                    }
                    onBrowserResize() {
                        super.onBrowserResize();
                        this.m_grid.redraw();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.children("[role=grid]"),
                            height: "100%",
                            viewStateId: this.source.viewStateId,
                            selectionMode: "none",
                            needContext: (e) => {
                                e.filters = this.source.contextFilters;
                            }
                        });
                    }
                }
                Views.EventHistoryView = EventHistoryView;
            })(Views = Actual.Views || (Actual.Views = {}));
        })(Actual = Canvas.Actual || (Canvas.Actual = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            class ElementModel extends CanvasJS.ElementModel {
                get document() {
                    return this.getDocument();
                }
                get dynamics() {
                    return this.state.get("dynamics", []);
                }
                set dynamics(value) {
                    this.state.set("dynamics", value);
                }
                get reloadModelAfterPost() {
                    return this.m_reloadModelAfterPost;
                }
                set reloadModelAfterPost(value) {
                    this.m_reloadModelAfterPost = value;
                }
                get isReloadingModel() {
                    return this.m_isReloadingModel;
                }
                set isReloadingModel(value) {
                    this.m_isReloadingModel = value;
                }
                reloadModel(model) {
                    if (this.reloadModelAfterPost) {
                        this.suspendStateChanged = true;
                        this.isReloadingModel = true;
                        this.onReloadModel(model);
                        this.onStateChangeCallback();
                        this.isReloadingModel = false;
                        this.suspendStateChanged = false;
                    }
                }
                onReloadModel(model) {
                }
            }
            Core.ElementModel = ElementModel;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            let CachedElementRefreshStatus;
            (function (CachedElementRefreshStatus) {
                CachedElementRefreshStatus[CachedElementRefreshStatus["None"] = 0] = "None";
                CachedElementRefreshStatus[CachedElementRefreshStatus["Pending"] = 2] = "Pending";
                CachedElementRefreshStatus[CachedElementRefreshStatus["Success"] = 3] = "Success";
                CachedElementRefreshStatus[CachedElementRefreshStatus["Failure"] = 4] = "Failure";
            })(CachedElementRefreshStatus = Core.CachedElementRefreshStatus || (Core.CachedElementRefreshStatus = {}));
            class CachedElement extends Core.ElementModel {
                constructor(options) {
                    super(options);
                }
                get cacheAgeMinutes() {
                    return this.state.get("cacheAgeMins");
                }
                set cacheAgeMinutes(value) {
                    this.state.set("cacheAgeMins", value);
                }
                get cacheExpiration() {
                    return this.state.get("cacheExpiration");
                }
                set cacheExpiration(value) {
                    this.state.set("cacheExpiration", value);
                }
                get cacheLastUpdated() {
                    return this.state.get("cacheLastUpdated");
                }
                set cacheLastUpdated(value) {
                    this.state.set("cacheLastUpdated", value);
                }
                get cacheDocumentId() {
                    return this.state.get("cacheDocumentId");
                }
                set cacheDocumentId(value) {
                    this.state.set("cacheDocumentId", value);
                }
                get cacheEntityId() {
                    return this.state.get("cacheEntityId");
                }
                set cacheEntityId(value) {
                    this.state.set("cacheEntityId", value);
                }
                get minutesElapsedSinceCached() {
                    return (((Date.now() - this.cacheLastUpdated) / 1000) / 60);
                }
                get hasCacheExpired() {
                    return this.isCachingEnabled && this.cacheAgeMinutes < this.minutesElapsedSinceCached;
                }
                get isCachingEnabled() {
                    return this.cacheAgeMinutes != null && this.cacheAgeMinutes > 0;
                }
                get cacheRefreshStatus() {
                    return this.state.get("cacheRefreshStatus", CachedElementRefreshStatus.None);
                }
                set cacheRefreshStatus(value) {
                    this.state.set("cacheRefreshStatus", value);
                }
                getCachedData(args) {
                    let shouldRefresh = (args === null || args === void 0 ? void 0 : args.force) == true ||
                        (this.cacheRefreshStatus == CachedElementRefreshStatus.None) ||
                        (this.isCachingEnabled && this.hasCacheExpired);
                    if (!shouldRefresh) {
                        return;
                    }
                    this.cacheRefreshStatus = CachedElementRefreshStatus.Pending;
                    let elementService = new PDJS.Services.Canvas.ElementService();
                    let success = (args === null || args === void 0 ? void 0 : args.success) || (() => { });
                    let error = (args === null || args === void 0 ? void 0 : args.error) || (() => { });
                    elementService.getCachedData({
                        entityId: this.cacheEntityId,
                        documentId: this.cacheDocumentId,
                        elementId: this.id,
                        refresh: shouldRefresh,
                        success: (e) => {
                            this.onCacheRefresh(e.data);
                            this.cacheRefreshStatus = CachedElementRefreshStatus.Success;
                            success(e.data);
                        },
                        error: (e) => {
                            this.cacheRefreshStatus = CachedElementRefreshStatus.Failure;
                            error();
                        }
                    });
                }
                onCacheRefresh(state) {
                    this.cacheAgeMinutes = state.cacheAgeMinutes;
                    this.cacheExpiration = state.cacheExpiration;
                    this.cacheLastUpdated = state.cacheLastUpdated;
                }
            }
            Core.CachedElement = CachedElement;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            let CanvasType;
            (function (CanvasType) {
                CanvasType[CanvasType["Explorer"] = 0] = "Explorer";
                CanvasType[CanvasType["Global"] = 1] = "Global";
                CanvasType[CanvasType["Create"] = 2] = "Create";
                CanvasType[CanvasType["Properties"] = 3] = "Properties";
                CanvasType[CanvasType["List"] = 4] = "List";
                CanvasType[CanvasType["DocumentType"] = 5] = "DocumentType";
            })(CanvasType = Core.CanvasType || (Core.CanvasType = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            class CssStates {
                constructor(options) {
                    this.m_model = options.model;
                }
                get activeBackColor() {
                    return this.getStateValue("active.backColor");
                }
                set activeBackColor(value) {
                    this.setStateValue("active.backColor", value);
                }
                get activeBackColorGradient() {
                    return this.getStateValue("active.backColorGradient");
                }
                set activeBackColorGradient(value) {
                    this.setStateValue("active.backColorGradient", value);
                }
                get activeBorderColor() {
                    return this.getStateValue("active.borderColor");
                }
                set activeBorderColor(value) {
                    this.setStateValue("active.borderColor", value);
                }
                get activeTextColor() {
                    return this.getStateValue("active.textColor");
                }
                set activeTextColor(value) {
                    this.setStateValue("active.textColor", value);
                }
                get defaultBackColor() {
                    return this.getStateValue("backColor");
                }
                set defaultBackColor(value) {
                    this.setStateValue("backColor", value);
                }
                get defaultBackColorGradient() {
                    return this.getStateValue("backColorGradient");
                }
                set defaultBackColorGradient(value) {
                    this.setStateValue("backColorGradient", value);
                }
                get defaultBorderColor() {
                    return this.getStateValue("borderColor");
                }
                set defaultBorderColor(value) {
                    this.setStateValue("borderColor", value);
                }
                get defaultTextColor() {
                    return this.getStateValue("textColor");
                }
                set defaultTextColor(value) {
                    this.setStateValue("textColor", value);
                }
                get focusBackColor() {
                    return this.getStateValue("focus.backColor");
                }
                set focusBackColor(value) {
                    this.setStateValue("focus.backColor", value);
                }
                get focusBackColorGradient() {
                    return this.getStateValue("focus.backColorGradient");
                }
                set focusBackColorGradient(value) {
                    this.setStateValue("focus.backColorGradient", value);
                }
                get focusBorderColor() {
                    return this.getStateValue("focus.borderColor");
                }
                set focusBorderColor(value) {
                    this.setStateValue("focus.borderColor", value);
                }
                get focusTextColor() {
                    return this.getStateValue("focus.textColor");
                }
                set focusTextColor(value) {
                    this.setStateValue("focus.textColor", value);
                }
                get hasActiveStates() {
                    return this.activeBackColor != null ||
                        this.activeBackColorGradient != null ||
                        this.activeBorderColor != null ||
                        this.activeTextColor != null;
                }
                get hasDefaultStates() {
                    return this.defaultBackColor != null ||
                        this.defaultBackColorGradient != null ||
                        this.defaultBorderColor != null ||
                        this.defaultTextColor != null;
                }
                get hasFocusStates() {
                    return this.focusBackColor != null ||
                        this.focusBackColorGradient != null ||
                        this.focusBorderColor != null ||
                        this.focusTextColor != null;
                }
                get hasHoverStates() {
                    return this.hoverBackColor != null ||
                        this.hoverBackColorGradient != null ||
                        this.hoverBorderColor != null ||
                        this.hoverTextColor != null;
                }
                get hasInactiveStates() {
                    return this.inactiveBackColor != null ||
                        this.inactiveBackColorGradient != null ||
                        this.inactiveBorderColor != null ||
                        this.inactiveTextColor != null;
                }
                get hoverBackColor() {
                    return this.getStateValue("hover.backColor");
                }
                set hoverBackColor(value) {
                    this.setStateValue("hover.backColor", value);
                }
                get hoverBackColorGradient() {
                    return this.getStateValue("hover.backColorGradient");
                }
                set hoverBackColorGradient(value) {
                    this.setStateValue("hover.backColorGradient", value);
                }
                get hoverBorderColor() {
                    return this.getStateValue("hover.borderColor");
                }
                set hoverBorderColor(value) {
                    this.setStateValue("hover.borderColor", value);
                }
                get hoverTextColor() {
                    return this.getStateValue("hover.textColor");
                }
                set hoverTextColor(value) {
                    this.setStateValue("hover.textColor", value);
                }
                get inactiveBackColor() {
                    return this.getStateValue("inactive.backColor");
                }
                set inactiveBackColor(value) {
                    this.setStateValue("inactive.backColor", value);
                }
                get inactiveBackColorGradient() {
                    return this.getStateValue("inactive.backColorGradient");
                }
                set inactiveBackColorGradient(value) {
                    this.setStateValue("inactive.backColorGradient", value);
                }
                get inactiveBorderColor() {
                    return this.getStateValue("inactive.borderColor");
                }
                set inactiveBorderColor(value) {
                    this.setStateValue("inactive.borderColor", value);
                }
                get inactiveTextColor() {
                    return this.getStateValue("inactive.textColor");
                }
                set inactiveTextColor(value) {
                    this.setStateValue("inactive.textColor", value);
                }
                get model() {
                    return this.m_model;
                }
                get state() {
                    return this.model.state;
                }
                getActiveStates() {
                    return {
                        background: this.backgroundReset([this.activeBackColor]),
                        backgroundColor: this.activeBackColor,
                        backgroundImage: this.formatBackgroundGradient(this.activeBackColor, this.activeBackColorGradient, true),
                        borderColor: this.activeBorderColor,
                        color: this.activeTextColor,
                    };
                }
                getDefaultStates() {
                    return {
                        background: this.backgroundReset([this.defaultBackColor, this.defaultBackColorGradient]),
                        backgroundColor: this.defaultBackColor,
                        backgroundImage: this.formatBackgroundGradient(this.defaultBackColor, this.defaultBackColorGradient, true),
                        borderColor: this.defaultBorderColor,
                        color: this.defaultTextColor,
                    };
                }
                getFocusStates() {
                    return {
                        background: this.backgroundReset([this.focusBackColor]),
                        backgroundColor: this.focusBackColor,
                        backgroundImage: this.formatBackgroundGradient(this.focusBackColor, this.focusBackColorGradient, true),
                        borderColor: this.focusBorderColor,
                        color: this.focusTextColor,
                    };
                }
                getHoverStates() {
                    return {
                        background: this.backgroundReset([this.hoverBackColor]),
                        backgroundColor: this.hoverBackColor,
                        backgroundImage: this.formatBackgroundGradient(this.hoverBackColor, this.hoverBackColorGradient, true),
                        borderColor: this.hoverBorderColor,
                        color: this.hoverTextColor
                    };
                }
                getInactiveStates() {
                    return {
                        background: this.backgroundReset([this.inactiveBackColor]),
                        backgroundColor: this.inactiveBackColor,
                        backgroundImage: this.formatBackgroundGradient(this.inactiveBackColor, this.inactiveBackColorGradient, true),
                        borderColor: this.inactiveBorderColor,
                        color: this.inactiveTextColor,
                    };
                }
                formatBackgroundGradient(backColor, gradientColor, supportsGradient) {
                    return ((backColor == null && gradientColor == null) || !supportsGradient) ? undefined :
                        `none, linear-gradient(to bottom, ${gradientColor || "var(--visiv-theme-button-back-color-gradient)"} 0%, ${backColor || "var(--visiv-theme-button-back-color)"} 100%)`;
                }
                getStateValue(name, defaultValue) {
                    return this.state.get(`styles.${name}`, defaultValue);
                }
                setStateValue(name, value) {
                    return this.state.set(`styles.${name}`, value);
                }
                backgroundReset(values) {
                    return values.find(value => value != null) != null ? "unset" : null;
                }
            }
            Core.CssStates = CssStates;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            class TabIndex {
                static calculate(tabIndex) {
                    let depth = Jade.Application
                        .instance.contexts.current.depth;
                    let index = tabIndex < 0 ?
                        0 : tabIndex + 1;
                    return index + (depth * 1000);
                }
            }
            Core.TabIndex = TabIndex;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            class IIndexableGuard extends Jade.InterfaceGuard {
                get signature() {
                    return {
                        id: "5721ed84-9eab-4a6c-bb7b-92c8c5d8ef11",
                        label: "IIndexableGuard"
                    };
                }
            }
            Core.IIndexableGuard = IIndexableGuard;
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Charts;
            (function (Charts) {
                let ChartSeriesType;
                (function (ChartSeriesType) {
                    ChartSeriesType["area"] = "area";
                    ChartSeriesType["bar"] = "bar";
                    ChartSeriesType["column"] = "column";
                    ChartSeriesType["line"] = "line";
                    ChartSeriesType["pie"] = "pie";
                })(ChartSeriesType = Charts.ChartSeriesType || (Charts.ChartSeriesType = {}));
                class Chart extends Core.CachedElement {
                    constructor(state) {
                        super(state);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Charts.Chart",
                            designScript: "PDJS.Canvas.Design.Charts.Chart",
                            element: this
                        });
                    }
                    get templateId() {
                        return this.state.get("templateId");
                    }
                    set templateId(value) {
                        this.state.set("templateId", value);
                    }
                    get seriesType() {
                        return this.state.get("seriesType");
                    }
                    set seriesType(value) {
                        this.state.set("seriesType", value);
                    }
                    get anchor() {
                        return this.state.get("anchor");
                    }
                    set anchor(value) {
                        this.state.set("anchor", value);
                    }
                    get condition() {
                        return this.state.get("condition");
                    }
                    set condition(value) {
                        this.state.set("condition", value);
                    }
                    get categoryFields() {
                        return this.state.get("categoryFields");
                    }
                    set categoryFields(value) {
                        this.state.set("categoryFields", value);
                    }
                    get legendFields() {
                        return this.state.get("legendFields");
                    }
                    set legendFields(value) {
                        this.state.set("legendFields", value);
                    }
                    get valueFields() {
                        return this.state.get("valueFields");
                    }
                    set valueFields(value) {
                        this.state.set("valueFields", value);
                    }
                    get enforceSecurity() {
                        return this.state.get("enforceSecurity");
                    }
                    set enforceSecurity(value) {
                        this.state.set("enforceSecurity", value);
                    }
                    get useEntityContext() {
                        return this.state.get("useEntityContext");
                    }
                    set useEntityContext(value) {
                        this.state.set("useEntityContext", value);
                    }
                    get style() {
                        return this.state.get("style");
                    }
                    set style(value) {
                        this.state.set("style", value);
                    }
                    get data() {
                        return this.state.get("data");
                    }
                    set data(value) {
                        this.state.set("data", value);
                    }
                    get context() {
                        return this.state.get("context");
                    }
                    set context(value) {
                        this.state.set("context", value);
                    }
                    get actionMenuVisible() {
                        return this.state.get("actionMenuVisible");
                    }
                    set actionMenuVisible(value) {
                        this.state.set("actionMenuVisible", value);
                    }
                    get actionMenuRefresh() {
                        return this.state.get("actionMenuRefresh");
                    }
                    set actionMenuRefresh(value) {
                        this.state.set("actionMenuRefresh", value);
                    }
                    get informationBarVisible() {
                        return this.state.get("informationBarVisible");
                    }
                    set informationBarVisible(value) {
                        this.state.set("informationBarVisible", value);
                    }
                    get informationBarRefresh() {
                        return this.state.get("informationBarRefresh");
                    }
                    set informationBarRefresh(value) {
                        this.state.set("informationBarRefresh", value);
                    }
                    onCacheRefresh(state) {
                        super.onCacheRefresh(state);
                        this.data = state.data;
                    }
                }
                Charts.Chart = Chart;
            })(Charts = Core.Charts || (Core.Charts = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                let Button = class Button extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Button",
                            designScript: "PDJS.Canvas.Design.Common.Button",
                            element: this
                        });
                        this.m_cssStates = new Core.CssStates({
                            model: this
                        });
                    }
                    get activeTabIndex() {
                        return Core.TabIndex.calculate(this.tabIndex);
                    }
                    get borderRadius() {
                        return this.state.get("styles.borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("styles.borderRadius", value);
                    }
                    get cssStates() {
                        return this.m_cssStates;
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get hasOnClickAction() {
                        return this.onClickAction != null
                            && this.onClickAction.id != null;
                    }
                    get hasImage() {
                        return !Jade.String.isNullOrWhiteSpace(this.image);
                    }
                    get hasLabel() {
                        return !Jade.String.isNullOrWhiteSpace(this.label);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                    get image() {
                        return this.state.get("image");
                    }
                    set image(value) {
                        this.state.set("image", value);
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get onClickAction() {
                        return this.state.get("onClick");
                    }
                    set onClickAction(value) {
                        this.state.set("onClick", value);
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                };
                Button = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], Button);
                Common.Button = Button;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                let Hyperlink = class Hyperlink extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Hyperlink",
                            designScript: "PDJS.Canvas.Design.Common.Hyperlink",
                            element: this
                        });
                    }
                    get onClickAction() {
                        return this.state.get("onClick");
                    }
                    set onClickAction(value) {
                        this.state.set("onClick", value);
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get foreColor() {
                        return this.state.get("foreColor", "var(--visiv-theme-link-text-color)");
                    }
                    set foreColor(value) {
                        this.state.set("foreColor", value);
                    }
                    get fontSize() {
                        return this.state.get("fontSize");
                    }
                    set fontSize(value) {
                        this.state.set("fontSize", value);
                    }
                    get fontName() {
                        return this.state.get("fontName");
                    }
                    set fontName(value) {
                        this.state.set("fontName", value);
                    }
                    get hoverForeColor() {
                        return this.state.get("hoverForeColor", "var(--visiv-theme-link-text-color)");
                    }
                    set hoverForeColor(value) {
                        this.state.set("hoverForeColor", value);
                    }
                    get textAlignment() {
                        return this.state.get("textAlignment");
                    }
                    set textAlignment(value) {
                        this.state.set("textAlignment", value);
                    }
                    get hasOnClickAction() {
                        return this.onClickAction != null
                            && this.onClickAction.id != null;
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get activeTabIndex() {
                        return Core.TabIndex.calculate(this.tabIndex);
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                };
                Hyperlink = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], Hyperlink);
                Common.Hyperlink = Hyperlink;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                class Image extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Image",
                            designScript: "PDJS.Canvas.Design.Common.Image",
                            element: this
                        });
                    }
                    get borderRadius() {
                        return this.state.get("borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("borderRadius", value);
                    }
                    get onClickAction() {
                        return this.state.get("onClick");
                    }
                    set onClickAction(value) {
                        this.state.set("onClick", value);
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get imageUrl() {
                        return this.state.get("imageUrl");
                    }
                    set imageUrl(value) {
                        this.state.set("imageUrl", value);
                    }
                    get hasOnClickAction() {
                        return this.onClickAction != null
                            && this.onClickAction.id != null;
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                }
                Common.Image = Image;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                class Markup extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Markup",
                            designScript: "PDJS.Canvas.Design.Common.Markup",
                            element: this
                        });
                    }
                    get markup() {
                        return this.state.get("markup");
                    }
                    set markup(value) {
                        this.state.set("markup", value);
                    }
                    get scrolling() {
                        return this.state.get("scrolling");
                    }
                    set scrolling(value) {
                        this.state.set("scrolling", value);
                    }
                    get padding() {
                        return this.state.get("padding");
                    }
                    set padding(value) {
                        this.state.set("padding", value);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-base-1-back-color)");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "var(--visiv-theme-base-1-border-color)");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderStyle() {
                        return this.state.get("borderStyle");
                    }
                    set borderStyle(value) {
                        this.state.set("borderStyle", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                }
                Common.Markup = Markup;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                class Report extends Core.CachedElement {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Report",
                            designScript: "PDJS.Canvas.Design.Common.Report",
                            element: this
                        });
                    }
                    get reportId() {
                        return this.state.get("reportId");
                    }
                    set reportId(value) {
                        this.state.set("reportId", value);
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    set entityId(value) {
                        this.state.set("entityId", value);
                    }
                    get reportName() {
                        return this.state.get("reportName");
                    }
                    set reportName(value) {
                        this.state.set("reportName", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "var(--visiv-theme-base-1-border-color)");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderStyle() {
                        return this.state.get("borderStyle");
                    }
                    set borderStyle(value) {
                        this.state.set("borderStyle", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                    get data() {
                        return this.state.get("data");
                    }
                    set data(value) {
                        this.state.set("data", value);
                    }
                    get actionMenuVisible() {
                        return this.state.get("actionMenuVisible");
                    }
                    set actionMenuVisible(value) {
                        this.state.set("actionMenuVisible", value);
                    }
                    get actionMenuRefresh() {
                        return this.state.get("actionMenuRefresh");
                    }
                    set actionMenuRefresh(value) {
                        this.state.set("actionMenuRefresh", value);
                    }
                    get actionMenuPrint() {
                        return this.state.get("actionMenuPrint");
                    }
                    set actionMenuPrint(value) {
                        this.state.set("actionMenuPrint", value);
                    }
                    get actionMenuOpen() {
                        return this.state.get("actionMenuOpen");
                    }
                    set actionMenuOpen(value) {
                        this.state.set("actionMenuOpen", value);
                    }
                    get informationBarVisible() {
                        return this.state.get("informationBarVisible");
                    }
                    set informationBarVisible(value) {
                        this.state.set("informationBarVisible", value);
                    }
                    get informationBarRefresh() {
                        return this.state.get("informationBarRefresh");
                    }
                    set informationBarRefresh(value) {
                        this.state.set("informationBarRefresh", value);
                    }
                    onCacheRefresh(state) {
                        super.onCacheRefresh(state);
                        this.data = state.data;
                    }
                }
                Common.Report = Report;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Common;
            (function (Common) {
                let VerticalAlign;
                (function (VerticalAlign) {
                    VerticalAlign["top"] = "flex-start";
                    VerticalAlign["middle"] = "center";
                    VerticalAlign["bottom"] = "flex-end";
                })(VerticalAlign || (VerticalAlign = {}));
                let HorizontalAlign;
                (function (HorizontalAlign) {
                    HorizontalAlign["left"] = "left";
                    HorizontalAlign["center"] = "center";
                    HorizontalAlign["right"] = "right";
                })(HorizontalAlign || (HorizontalAlign = {}));
                class Text extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.Text",
                            designScript: "PDJS.Canvas.Design.Common.Text",
                            element: this
                        });
                    }
                    get text() {
                        return this.state.get("text");
                    }
                    set text(value) {
                        this.state.set("text", value);
                    }
                    get verticalAlignment() {
                        return this.state.get("verticalAlignment");
                    }
                    set verticalAlignment(value) {
                        this.state.set("verticalAlignment", value);
                    }
                    get horizontalAlignment() {
                        return this.state.get("horizontalAlignment");
                    }
                    set horizontalAlignment(value) {
                        this.state.set("horizontalAlignment", value);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderStyle() {
                        return this.state.get("borderStyle");
                    }
                    set borderStyle(value) {
                        this.state.set("borderStyle", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                    get paddingTop() {
                        return this.state.get("paddingTop");
                    }
                    set paddingTop(value) {
                        this.state.set("paddingTop", value);
                    }
                    get paddingRight() {
                        return this.state.get("paddingRight");
                    }
                    set paddingRight(value) {
                        this.state.set("paddingRight", value);
                    }
                    get paddingBottom() {
                        return this.state.get("paddingBottom");
                    }
                    set paddingBottom(value) {
                        this.state.set("paddingBottom", value);
                    }
                    get paddingLeft() {
                        return this.state.get("paddingLeft");
                    }
                    set paddingLeft(value) {
                        this.state.set("paddingLeft", value);
                    }
                }
                Common.Text = Text;
            })(Common = Core.Common || (Core.Common = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Documents;
            (function (Documents) {
                class DocumentModel extends CanvasJS.DocumentModel {
                    constructor(options) {
                        super(options);
                        if (_.isArray(options.tabIndexes)) {
                            this.m_tabIndexes = new Jade.Collection(options.tabIndexes);
                        }
                        else {
                            this.m_tabIndexes = new Jade.Collection();
                        }
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-base-1-back-color)");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor");
                    }
                    get canvasType() {
                        return this.state.get("canvasType");
                    }
                    set canvasType(value) {
                        this.state.set("canvasType");
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get externalFiles() {
                        return this.state.get("externalFiles", "");
                    }
                    set externalFiles(value) {
                        this.state.set("externalFiles", value);
                    }
                    get internalScript() {
                        return this.state.get("internalScript", "");
                    }
                    set internalScript(value) {
                        this.state.set("internalScript", value);
                    }
                    get internalStyles() {
                        return this.state.get("internalStyles", "");
                    }
                    set internalStyles(value) {
                        this.state.set("internalStyles", value);
                    }
                    get tabIndexes() {
                        return this.m_tabIndexes;
                    }
                    toJSON() {
                        let result = super.toJSON();
                        _.each(this.tabIndexes.toArray(), (id) => {
                            if (this.elements.get(id) == null) {
                                this.tabIndexes.remove(id);
                            }
                        });
                        result.tabIndexes = this.tabIndexes.toArray();
                        return result;
                    }
                }
                Documents.DocumentModel = DocumentModel;
            })(Documents = Core.Documents || (Core.Documents = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Documents;
            (function (Documents) {
                class ActualDocument extends Documents.DocumentModel {
                    constructor(options) {
                        super(options);
                        this.m_variables = new PDJS.Canvas.Core.Dynamics.VariableCollection(options.variables);
                        this.loadVariableData();
                    }
                    get variables() {
                        return this.m_variables;
                    }
                    saveForm(options) {
                        let formService = new PDJS.Services.Canvas.Forms.FormService();
                        formService.submit({
                            document: this.toJSON(),
                            entityId: options.entityId,
                            formButtonId: options.formButtonId,
                            success: (e) => {
                                setTimeout(() => {
                                    switch (true) {
                                        case e.data.hasValidationErrors:
                                            if (_.isFunction(options.onValidationError)) {
                                                options.onValidationError(e.data);
                                            }
                                            break;
                                        case e.data.hasScriptErrors:
                                            if (_.isFunction(options.onScriptError)) {
                                                options.onScriptError(e.data);
                                            }
                                            break;
                                        default:
                                            if (_.isFunction(options.onSuccess)) {
                                                this.fill(e.data.document);
                                                options.onSuccess(e.data);
                                            }
                                            break;
                                    }
                                    if (e.data.hasEntityChanges) {
                                        PDJS.Hub.Explorer.EventsHub.entityChangedPublish(e.data.entityChanges);
                                        PDJS.Hub.Explorer.EventsHub.reloadExplorerPublish();
                                    }
                                }, 750);
                            },
                            error: (e) => {
                                if (_.isFunction(options.onError)) {
                                    options.onError(e);
                                }
                            }
                        });
                    }
                    loadVariableData() {
                        let variables = {};
                        this.variables.items.forEach(item => {
                            variables[item.id] = item.value;
                        });
                        let elements = this.elements.toArray();
                        elements.forEach((element => {
                            if (element.dynamics) {
                                let updates = {};
                                element.dynamics.find(item => {
                                    if (item.clientPath != null) {
                                        if (variables[item.variableId] != null) {
                                            updates[item.clientPath] = variables[item.variableId];
                                        }
                                    }
                                });
                                element.state.set(updates);
                            }
                        }));
                    }
                }
                Documents.ActualDocument = ActualDocument;
            })(Documents = Core.Documents || (Core.Documents = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Documents;
            (function (Documents) {
                class DesignDocument extends Documents.DocumentModel {
                    constructor(options) {
                        super(options);
                        this.m_variables = new PDJS.Canvas.Core.Dynamics.VariableCollection(options.variables);
                    }
                    get sessionId() {
                        return this.state.get("sessionId");
                    }
                    get script() {
                        return this.state.get("script");
                    }
                    get width() {
                        return this.state.get("width", this.getDefaultWidth());
                    }
                    get height() {
                        return this.state.get("height", "10000px");
                    }
                    get variables() {
                        return this.m_variables;
                    }
                    toJSON() {
                        let result = super.toJSON();
                        result.variables = this.variables.toArray();
                        return result;
                    }
                    getDefaultWidth() {
                        let result = "10000px";
                        switch (this.canvasType) {
                            case PDJS.Canvas.Core.CanvasType.Create:
                                result = "680px";
                                break;
                            case PDJS.Canvas.Core.CanvasType.Properties:
                                result = "680px";
                                break;
                            case PDJS.Canvas.Core.CanvasType.List:
                                result = "680px";
                                break;
                            case PDJS.Canvas.Core.CanvasType.DocumentType:
                                result = "680px";
                                break;
                        }
                        return result;
                    }
                }
                Documents.DesignDocument = DesignDocument;
            })(Documents = Core.Documents || (Core.Documents = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Documents;
            (function (Documents) {
                class ExplorerDocument extends Document {
                    static load() {
                    }
                    save(options) {
                    }
                }
                Documents.ExplorerDocument = ExplorerDocument;
            })(Documents = Core.Documents || (Core.Documents = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Dynamics;
            (function (Dynamics) {
                let CanvasVariableType;
                (function (CanvasVariableType) {
                    CanvasVariableType[CanvasVariableType["Boolean"] = 1] = "Boolean";
                    CanvasVariableType[CanvasVariableType["Date"] = 2] = "Date";
                    CanvasVariableType[CanvasVariableType["Number"] = 3] = "Number";
                    CanvasVariableType[CanvasVariableType["String"] = 4] = "String";
                })(CanvasVariableType = Dynamics.CanvasVariableType || (Dynamics.CanvasVariableType = {}));
                let CanvasVariableSource;
                (function (CanvasVariableSource) {
                    CanvasVariableSource[CanvasVariableSource["Local"] = 1] = "Local";
                    CanvasVariableSource[CanvasVariableSource["System"] = 2] = "System";
                    CanvasVariableSource[CanvasVariableSource["Context"] = 3] = "Context";
                })(CanvasVariableSource = Dynamics.CanvasVariableSource || (Dynamics.CanvasVariableSource = {}));
            })(Dynamics = Core.Dynamics || (Core.Dynamics = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Dynamics;
            (function (Dynamics) {
                class VariableCollection {
                    constructor(data) {
                        this.m_items = [];
                        if (data != null) {
                            this.m_items = JSON.parse(JSON.stringify(data));
                        }
                    }
                    get ids() {
                        let result = [];
                        this.items.map(item => {
                            result[result.length] = item.id;
                        });
                        return result;
                    }
                    get items() {
                        return this.m_items;
                    }
                    add(variable) {
                        if (variable.id == null || variable.name == null) {
                            return;
                        }
                        let index = this.getIndex(variable.id);
                        if (index > -1) {
                            this.items[index] = variable;
                        }
                        else {
                            this.items.push(variable);
                        }
                    }
                    remove(id) {
                        let index = this.getIndex(id);
                        if (index > -1) {
                            this.items.splice(index, 1);
                        }
                    }
                    get(id) {
                        let result = null;
                        if (this.contains(id)) {
                            result = this.items.find(item => item.id === id);
                        }
                        return result;
                    }
                    getIndex(id) {
                        let result = -1;
                        if (this.contains(id)) {
                            this.items.forEach((item, index) => {
                                result = (item.id === id) ? index : result;
                            });
                        }
                        return result;
                    }
                    contains(id) {
                        return this.ids.filter(key => { key === id; }) != null;
                    }
                    clear() {
                        this.m_items = [];
                    }
                    toArray() {
                        return this.items.slice(0);
                    }
                }
                Dynamics.VariableCollection = VariableCollection;
            })(Dynamics = Core.Dynamics || (Core.Dynamics = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                let FormElement = class FormElement extends Core.ElementModel {
                    get activeEnabledState() {
                        return !this.isDisabled;
                    }
                    get activeTabIndex() {
                        return Core.TabIndex.calculate(this.tabIndex);
                    }
                    get formId() {
                        return this.state.get("formId");
                    }
                    set formId(value) {
                        this.state.set("formId", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                    get isDisabled() {
                        return this.state.get("isDisabled");
                    }
                    set isDisabled(value) {
                        this.state.set("isDisabled", value);
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                };
                FormElement = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], FormElement);
                Forms.FormElement = FormElement;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class FormButton extends Forms.FormElement {
                    constructor(state) {
                        super(state);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.FormButton",
                            designScript: "PDJS.Canvas.Design.Forms.FormButton",
                            element: this
                        });
                        this.m_cssStates = new Core.CssStates({
                            model: this
                        });
                    }
                    get activeEnabledState() {
                        return !this.isDisabled && this.enabled;
                    }
                    get borderRadius() {
                        return this.state.get("styles.borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("styles.borderRadius", value);
                    }
                    get cssStates() {
                        return this.m_cssStates;
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get enforceSecurity() {
                        return this.state.get("enforceSecurity");
                    }
                    set enforceSecurity(value) {
                        this.state.set("enforceSecurity", value);
                    }
                    get hasImage() {
                        return !Jade.String.isNullOrWhiteSpace(this.image);
                    }
                    get hasLabel() {
                        return !Jade.String.isNullOrWhiteSpace(this.label);
                    }
                    get image() {
                        return this.state.get("image");
                    }
                    set image(value) {
                        this.state.set("image", value);
                    }
                    get ruleScript() {
                        return this.state.get("script");
                    }
                    set ruleScript(value) {
                        this.state.set("script", value);
                    }
                }
                Forms.FormButton = FormButton;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class FormField extends Forms.FormElement {
                    constructor(options) {
                        super(options);
                    }
                    get defaultLabel() {
                        return this.state.get("defaultLabel");
                    }
                    set defaultLabel(value) {
                        this.state.set("defaultLabel", value);
                    }
                    get isRequired() {
                        return this.state.get("isRequired");
                    }
                    set isRequired(value) {
                        this.state.set("isRequired", value);
                    }
                    get labelColor() {
                        return this.state.get("labelColor", "var(--visiv-theme-base-1-text-color)");
                    }
                    set labelColor(value) {
                        this.state.set("labelColor", value);
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get activeLabel() {
                        return this.label || this.defaultLabel;
                    }
                    get activeLabelColor() {
                        return this.isRequired ? "var(--visiv-required-text-color)" : this.labelColor;
                    }
                    get value() {
                        return null;
                    }
                    set value(value) {
                    }
                    get input() {
                        return this.state.get("input");
                    }
                    set input(value) {
                        this.state.set("input", value);
                    }
                    get valueChanged() {
                        return this.m_valueChanged;
                    }
                    set valueChanged(value) {
                        this.m_valueChanged = value;
                    }
                    copyInputTo(field) {
                    }
                    isEquivalentTo(field) {
                        return false;
                    }
                    hasValue() {
                        return (_.isString(this.value) && !Jade.String.isNullOrWhiteSpace(this.value)) ||
                            (_.isArray(this.value) && this.value.length > 0) ||
                            (!_.isString(this.value) && !_.isArray(this.value) && !_.isNull(this.value));
                    }
                    checkValueChanged(currentValue, newValue) {
                        if (newValue != null && _.isString(newValue) && Jade.String.isNullOrWhiteSpace(newValue)) {
                            newValue = null;
                        }
                        if (currentValue != null && _.isString(currentValue) && Jade.String.isNullOrWhiteSpace(currentValue)) {
                            currentValue = null;
                        }
                        if (currentValue != newValue) {
                            this.valueChanged = true;
                            Jade.Application
                                .instance
                                .contexts
                                .current
                                .events
                                .publish("canvas/form/changed", {
                                formId: this.formId
                            });
                        }
                    }
                }
                Forms.FormField = FormField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class BuiltInField extends Forms.FormField {
                    constructor(options) {
                        super(options);
                    }
                    get isReadOnly() {
                        return this.state.get("isReadOnly");
                    }
                    set isReadOnly(value) {
                        this.state.set("isReadOnly", value);
                    }
                    get activeEnabledState() {
                        return !this.isDisabled && !this.isReadOnly;
                    }
                }
                Forms.BuiltInField = BuiltInField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class ExtensionField extends Forms.FormField {
                    constructor(options) {
                        super(options);
                    }
                    get columnId() {
                        return this.state.get("columnId");
                    }
                    set columnId(value) {
                        this.state.set("columnId", value);
                    }
                    get columnIsReadOnly() {
                        return this.state.get("columnIsReadOnly");
                    }
                    set columnIsReadOnly(value) {
                        this.state.set("columnIsReadOnly", value);
                    }
                    get inBatch() {
                        return this.state.get("inBatch");
                    }
                    set inBatch(value) {
                        this.state.set("inBatch", value);
                    }
                    get isReadOnly() {
                        return this.state.get("isReadOnly");
                    }
                    set isReadOnly(value) {
                        this.state.set("isReadOnly", value);
                    }
                    get inBatchMode() {
                        return this.state.get("isBatchMode");
                    }
                    set inBatchMode(value) {
                        this.state.set("isBatchMode", value);
                    }
                    get activeEnabledState() {
                        return !this.isDisabled
                            && !this.isReadOnly && !this.columnIsReadOnly
                            && (!this.inBatchMode || (this.inBatchMode && this.inBatch));
                    }
                }
                Forms.ExtensionField = ExtensionField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class FormFields {
                    static getField(args) {
                        let result = null;
                        args.document.elements.getByType(Forms.FormField).each((field) => {
                            if (field instanceof args.type) {
                                let isEquivalentExtensionField = field instanceof Forms.ExtensionField &&
                                    field.columnId == args.columnId;
                                let isNotExtensionField = !(field instanceof Forms.ExtensionField);
                                switch (true) {
                                    case isEquivalentExtensionField:
                                        result = field;
                                        return false;
                                    case isNotExtensionField:
                                        result = field;
                                        return false;
                                }
                            }
                        });
                        return result;
                    }
                    static getFields(args) {
                        let result = new Jade.Collection();
                        args.document.elements.getByType(Forms.FormField).each((field) => {
                            if (field instanceof args.type) {
                                let isEquivalentExtensionField = field instanceof Forms.ExtensionField &&
                                    field.columnId == args.columnId;
                                let isNotExtensionField = !(field instanceof Forms.ExtensionField);
                                switch (true) {
                                    case isEquivalentExtensionField:
                                        result.add(field);
                                        return false;
                                    case isNotExtensionField:
                                        result.add(field);
                                        return false;
                                }
                            }
                        });
                        return result;
                    }
                    static getInput(args) {
                        let result = null;
                        let field = this.getField(args);
                        if (field != null) {
                            result = field.input;
                        }
                        return result;
                    }
                    static getRequiredFields(source) {
                        let result = new Jade.Collection();
                        this.getFormFields(source).each((field) => {
                            if (field.isRequired) {
                                result.add(field);
                            }
                        });
                        return result;
                    }
                    static getValue(args) {
                        let result = null;
                        let field = this.getField(args);
                        if (field != null) {
                            result = field.value;
                        }
                        return result;
                    }
                    static map(source, destination) {
                        let srcFields = source.elements.getByType(Forms.FormField);
                        let dstFields = destination.elements.getByType(Forms.FormField);
                        dstFields.each((dstField) => {
                            srcFields.each((srcField) => {
                                let shouldMap = !(srcField instanceof Forms.TextField)
                                    && dstField.isEquivalentTo(srcField);
                                if (shouldMap) {
                                    dstField.input = srcField.input;
                                }
                            });
                        });
                    }
                    static setEntityNameFieldValue(source, value) {
                        this.getFields({
                            document: source,
                            type: PDJS.Canvas.Core.Forms.EntityNameField
                        })
                            .each((field) => {
                            if (field.value == null) {
                                field.value = value;
                            }
                        });
                    }
                    static getEntityNameFieldValue(source) {
                        return PDJS.Canvas.Core.Forms.FormFields.getValue({
                            document: source,
                            type: PDJS.Canvas.Core.Forms.EntityNameField
                        });
                    }
                    static iterateRequiredFields(source, callback) {
                        FormFields
                            .getRequiredFields(source)
                            .each((field) => {
                            callback(field);
                        });
                    }
                    static getFormFields(source) {
                        return source.elements.getByType(Canvas.Core.Forms.FormField);
                    }
                }
                Forms.FormFields = FormFields;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityDescriptionField extends Forms.BuiltInField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityDescriptionField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityDescriptionField",
                            element: this
                        });
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof EntityDescriptionField;
                    }
                }
                Forms.EntityDescriptionField = EntityDescriptionField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityIconField extends Forms.BuiltInField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityIconField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityIconField",
                            element: this
                        });
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof EntityIconField;
                    }
                }
                Forms.EntityIconField = EntityIconField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityNameField extends Forms.BuiltInField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityNameField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityNameField",
                            element: this
                        });
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof EntityNameField;
                    }
                }
                Forms.EntityNameField = EntityNameField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityParentField extends Forms.BuiltInField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityParentField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityParentField",
                            element: this
                        });
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    set entityTypeId(value) {
                        this.state.set("entityTypeId", value);
                    }
                    get parentId() {
                        return this.state.get("parentId");
                    }
                    set parentId(value) {
                        this.checkValueChanged(this.parentId, value);
                        this.state.set("parentId", value);
                    }
                    get parentName() {
                        return this.state.get("parentName");
                    }
                    set parentName(value) {
                        this.state.set("parentName", value);
                    }
                    get parentTypeName() {
                        return this.state.get("parentTypeName");
                    }
                    set parentTypeName(value) {
                        this.state.set("parentTypeName", value);
                    }
                    get parentTypeIcon() {
                        return this.state.get("parentTypeIcon");
                    }
                    set parentTypeIcon(value) {
                        this.state.set("parentTypeIcon", value);
                    }
                    get isRequiredByType() {
                        return this.state.get("isRequiredByType");
                    }
                    set isRequiredByType(value) {
                        this.state.set("isRequiredByType", value);
                    }
                    get input() {
                        return {
                            parentId: this.parentId,
                            parentName: this.parentName,
                            parentTypeName: this.parentTypeName,
                            parentTypeIcon: this.parentTypeIcon
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof EntityParentField;
                    }
                }
                Forms.EntityParentField = EntityParentField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityProcessField extends Forms.BuiltInField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityProcessField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityProcessField",
                            element: this
                        });
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get keyIcon() {
                        return this.state.get("keyIcon");
                    }
                    set keyIcon(value) {
                        this.state.set("keyIcon", value);
                    }
                    get keyName() {
                        return this.state.get("keyName");
                    }
                    set keyName(value) {
                        this.state.set("keyName", value);
                    }
                    get processName() {
                        return this.state.get("processName");
                    }
                    set processName(value) {
                        this.state.set("processName", value);
                    }
                    get stageId() {
                        return this.state.get("stageId");
                    }
                    set stageId(value) {
                        this.checkValueChanged(this.stageId, value);
                        this.state.set("stageId", value);
                    }
                    get stageIcon() {
                        return this.state.get("stageIcon");
                    }
                    set stageIcon(value) {
                        this.state.set("stageIcon", value);
                    }
                    get stageName() {
                        return this.state.get("stageName");
                    }
                    set stageName(value) {
                        this.state.set("stageName", value);
                    }
                    get statusId() {
                        return this.state.get("statusId");
                    }
                    set statusId(value) {
                        this.state.set("statusId", value);
                    }
                    get statusIcon() {
                        return this.state.get("statusIcon");
                    }
                    set statusIcon(value) {
                        this.state.set("statusIcon", value);
                    }
                    get statusName() {
                        return this.state.get("statusName");
                    }
                    set statusName(value) {
                        this.state.set("statusName", value);
                    }
                    get showKey() {
                        return this.state.get("showKey");
                    }
                    get showProcess() {
                        return this.state.get("showProcess");
                    }
                    get showStage() {
                        return this.state.get("showStage");
                    }
                    get showStatus() {
                        return this.state.get("showStatus");
                    }
                }
                Forms.EntityProcessField = EntityProcessField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class BooleanField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.BooleanField",
                            designScript: "PDJS.Canvas.Design.Forms.BooleanField",
                            element: this
                        });
                    }
                    get itemIcon() {
                        return this.state.get("itemIcon");
                    }
                    set itemIcon(value) {
                        this.state.set("itemIcon", value);
                    }
                    get itemLabel() {
                        return this.state.get("itemLabel");
                    }
                    set itemLabel(value) {
                        this.state.set("itemLabel", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof BooleanField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.BooleanField = BooleanField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class DateField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.DateField",
                            designScript: "PDJS.Canvas.Design.Forms.DateField",
                            element: this
                        });
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    set format(value) {
                        this.state.set("format", value);
                    }
                    get columnFormat() {
                        return this.state.get("columnFormat");
                    }
                    set columnFormat(value) {
                        this.state.set("columnFormat", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeFormat() {
                        return this.format || this.columnFormat;
                    }
                    isEquivalentTo(field) {
                        return field instanceof DateField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.DateField = DateField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class DecimalField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.DecimalField",
                            designScript: "PDJS.Canvas.Design.Forms.DecimalField",
                            element: this
                        });
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    set format(value) {
                        this.state.set("format", value);
                    }
                    get columnFormat() {
                        return this.state.get("columnFormat");
                    }
                    set columnFormat(value) {
                        this.state.set("columnFormat", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeFormat() {
                        return this.format || this.columnFormat;
                    }
                    isEquivalentTo(field) {
                        return field instanceof DecimalField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.DecimalField = DecimalField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class EntityField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.EntityField",
                            designScript: "PDJS.Canvas.Design.Forms.EntityField",
                            element: this
                        });
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    set entityId(value) {
                        this.checkValueChanged(this.entityId, value);
                        this.state.set("entityId", value);
                    }
                    get entityName() {
                        return this.state.get("entityName");
                    }
                    set entityName(value) {
                        this.state.set("entityName", value);
                    }
                    get entityTypeName() {
                        return this.state.get("entityTypeName");
                    }
                    set entityTypeName(value) {
                        this.state.set("entityTypeName", value);
                    }
                    get entityTypeIcon() {
                        return this.state.get("entityTypeIcon");
                    }
                    set entityTypeIcon(value) {
                        this.state.set("entityTypeIcon", value);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    set viewId(value) {
                        this.state.set("viewId", value);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get input() {
                        return {
                            entityId: this.entityId,
                            entityName: this.entityName,
                            entityTypeName: this.entityTypeName,
                            entityTypeIcon: this.entityTypeIcon
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof EntityField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.EntityField = EntityField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class Int32Field extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.Int32Field",
                            designScript: "PDJS.Canvas.Design.Forms.Int32Field",
                            element: this
                        });
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    set format(value) {
                        this.state.set("format", value);
                    }
                    get columnFormat() {
                        return this.state.get("columnFormat");
                    }
                    set columnFormat(value) {
                        this.state.set("columnFormat", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeFormat() {
                        return this.format || this.columnFormat;
                    }
                    isEquivalentTo(field) {
                        return field instanceof Int32Field &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.Int32Field = Int32Field;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class Int64Field extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.Int64Field",
                            designScript: "PDJS.Canvas.Design.Forms.Int64Field",
                            element: this
                        });
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    set format(value) {
                        this.state.set("format", value);
                    }
                    get columnFormat() {
                        return this.state.get("columnFormat");
                    }
                    set columnFormat(value) {
                        this.state.set("columnFormat", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeFormat() {
                        return this.format || this.columnFormat;
                    }
                    isEquivalentTo(field) {
                        return field instanceof Int64Field &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.Int64Field = Int64Field;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class MultiSelectField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.MultiSelectField",
                            designScript: "PDJS.Canvas.Design.Forms.MultiSelectField",
                            element: this
                        });
                    }
                    get items() {
                        return this.state.get("items");
                    }
                    set items(value) {
                        this.state.set("items", value);
                    }
                    get value() {
                        return this.state.get("selectedIds");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("selectedIds", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof MultiSelectField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.MultiSelectField = MultiSelectField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class SingleSelectField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.SingleSelectField",
                            designScript: "PDJS.Canvas.Design.Forms.SingleSelectField",
                            element: this
                        });
                    }
                    get items() {
                        return this.state.get("items", []);
                    }
                    set items(value) {
                        this.state.set("items", value);
                    }
                    get selectedId() {
                        return this.state.get("selectedId");
                    }
                    set selectedId(value) {
                        this.checkValueChanged(this.selectedId, value);
                        this.state.set("selectedId", value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof SingleSelectField &&
                            field.columnId === this.columnId;
                    }
                    getSelectedItem() {
                        let result = null;
                        _.each(this.items, (item) => {
                            if (item.id == this.selectedId) {
                                result = item;
                                return false;
                            }
                        });
                        return result;
                    }
                }
                Forms.SingleSelectField = SingleSelectField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class StringField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.StringField",
                            designScript: "PDJS.Canvas.Design.Forms.StringField",
                            element: this
                        });
                    }
                    get multiLine() {
                        return this.height > 50;
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof StringField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.StringField = StringField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class UserField extends Forms.ExtensionField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.UserField",
                            designScript: "PDJS.Canvas.Design.Forms.UserField",
                            element: this
                        });
                    }
                    get userId() {
                        return this.state.get("userId");
                    }
                    set userId(value) {
                        this.checkValueChanged(this.userId, value);
                        this.state.set("userId", value);
                    }
                    get userName() {
                        return this.state.get("userName");
                    }
                    set userName(value) {
                        this.state.set("userName", value);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    set viewId(value) {
                        this.state.set("viewId", value);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get input() {
                        return {
                            userId: this.userId,
                            userName: this.userName
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    isEquivalentTo(field) {
                        return field instanceof UserField &&
                            field.columnId === this.columnId;
                    }
                }
                Forms.UserField = UserField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class BatchField extends Forms.FormField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.BatchField",
                            designScript: "PDJS.Canvas.Design.Forms.BatchField",
                            element: this
                        });
                        this.reloadModelAfterPost = true;
                        if (this.listItems == null) {
                            this.listItems = [];
                        }
                    }
                    get contextId() {
                        return this.state.get("contextId");
                    }
                    set contextId(value) {
                        this.state.set("contextId", value);
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    set entityId(value) {
                        this.state.set("entityId", value);
                    }
                    get enforceSecurity() {
                        return this.state.get("enforceSecurity");
                    }
                    set enforceSecurity(value) {
                        this.state.set("enforceSecurity", value);
                    }
                    get filterTerm() {
                        return this.state.get("filterTerm", "");
                    }
                    set filterTerm(value) {
                        this.state.set("filterTerm", value, { silent: true });
                    }
                    get isReadOnly() {
                        return this.state.get("isReadOnly");
                    }
                    set isReadOnly(value) {
                        this.state.set("isReadOnly", value);
                    }
                    get isRequired() {
                        return this.state.get("isRequired");
                    }
                    set isRequired(value) {
                        this.state.set("isRequired", value);
                    }
                    get selectIdentities() {
                        return this.state.get("selectIdentities");
                    }
                    set selectIdentities(value) {
                        this.state.set("selectIdentities", value);
                    }
                    get selectedIds() {
                        return this.state.get("selectedIds");
                    }
                    set selectedIds(value) {
                        this.state.set("selectedIds", value, { silent: true });
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    get contextFilters() {
                        return this.state.get("contextFilters", []);
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeEnabledState() {
                        return !this.isDisabled && !this.isReadOnly;
                    }
                    get listItems() {
                        return this.state.get("listItems");
                    }
                    set listItems(value) {
                        this.state.set("listItems", value, { silent: true });
                    }
                    get dialogTitle() {
                        return this.state.get("dialogTitle", "Batch Field Selection");
                    }
                    get dialogHeight() {
                        return this.state.get("dialogHeight", 400);
                    }
                    get dialogWidth() {
                        return this.state.get("dialogWidth", 600);
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", 600);
                    }
                    onReloadModel(model) {
                        super.onReloadModel(model);
                        if (model instanceof BatchField) {
                            this.listItems = model.listItems;
                            this.filterTerm = model.filterTerm;
                        }
                    }
                    toJSON() {
                        this.selectedIds = [];
                        _.each(this.listItems, (item) => {
                            if (item.active) {
                                this.selectedIds[this.selectedIds.length] = item.id;
                            }
                        });
                        return super.toJSON();
                    }
                    isEquivalentTo(field) {
                        return field instanceof BatchField;
                    }
                }
                Forms.BatchField = BatchField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Forms;
            (function (Forms) {
                class TextField extends Forms.FormField {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Forms.TextField",
                            designScript: "PDJS.Canvas.Design.Forms.TextField",
                            element: this
                        });
                    }
                    get contextId() {
                        return this.state.get("contextId");
                    }
                    set contextId(value) {
                        this.state.set("contextId", value);
                    }
                    get enforceSecurity() {
                        return this.state.get("enforceSecurity");
                    }
                    set enforceSecurity(value) {
                        this.state.set("enforceSecurity", value);
                    }
                    get isReadOnly() {
                        return this.state.get("isReadOnly");
                    }
                    set isReadOnly(value) {
                        this.state.set("isReadOnly", value);
                    }
                    get isRequired() {
                        return this.state.get("isRequired");
                    }
                    set isRequired(value) {
                        this.state.set("isRequired", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.checkValueChanged(this.value, value);
                        this.state.set("value", value);
                    }
                    get multiLine() {
                        return this.height > 50;
                    }
                    get input() {
                        return {
                            value: this.value
                        };
                    }
                    set input(value) {
                        this.state.set(value);
                    }
                    get activeEnabledState() {
                        return !this.isDisabled && !this.isReadOnly;
                    }
                    isEquivalentTo(field) {
                        return field instanceof TextField;
                    }
                }
                Forms.TextField = TextField;
            })(Forms = Core.Forms || (Core.Forms = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Process;
            (function (Process) {
                let DecisionButton = class DecisionButton extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Process.DecisionButton",
                            designScript: "PDJS.Canvas.Design.Process.DecisionButton",
                            element: this
                        });
                        this.m_cssStates = new Core.CssStates({
                            model: this
                        });
                    }
                    get borderRadius() {
                        return this.state.get("styles.borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("styles.borderRadius", value);
                    }
                    get cssStates() {
                        return this.m_cssStates;
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get activeLabel() {
                        return this.label || this.defaultLabel;
                    }
                    get defaultLabel() {
                        return this.state.get("defaultLabel");
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get activeTabIndex() {
                        return Core.TabIndex.calculate(this.tabIndex);
                    }
                    get entityId() {
                        return this.document.entityId;
                    }
                    get decisionId() {
                        return this.state.get("decisionId");
                    }
                    toJSON() {
                        return _.extend(super.toJSON(), {
                            entityId: this.entityId
                        });
                    }
                };
                DecisionButton = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], DecisionButton);
                Process.DecisionButton = DecisionButton;
            })(Process = Core.Process || (Core.Process = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Process;
            (function (Process) {
                let ProcessDecisions = class ProcessDecisions extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Process.ProcessDecisions",
                            designScript: "PDJS.Canvas.Design.Process.ProcessDecisions",
                            element: this
                        });
                    }
                    get entityId() {
                        return this.document.entityId;
                    }
                    get showKey() {
                        return this.state.get("showKeys");
                    }
                    get showStage() {
                        return this.state.get("showStages");
                    }
                    get showStatus() {
                        return this.state.get("showStatus");
                    }
                    get currentKey() {
                        return this.state.get("currentKey");
                    }
                    get currentStage() {
                        return this.state.get("currentStage");
                    }
                    get currentStatus() {
                        return this.state.get("currentStatus");
                    }
                    get decisions() {
                        return this.state.get("decisions", []);
                    }
                    toJSON() {
                        return _.extend(super.toJSON(), {
                            entityId: this.entityId
                        });
                    }
                };
                ProcessDecisions = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], ProcessDecisions);
                Process.ProcessDecisions = ProcessDecisions;
            })(Process = Core.Process || (Core.Process = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Process;
            (function (Process) {
                let ProcessStateOrientation;
                (function (ProcessStateOrientation) {
                    ProcessStateOrientation["Horizontal"] = "horizontal";
                    ProcessStateOrientation["Vertical"] = "vertical";
                })(ProcessStateOrientation = Process.ProcessStateOrientation || (Process.ProcessStateOrientation = {}));
                let ProcessState = class ProcessState extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Process.ProcessState",
                            designScript: "PDJS.Canvas.Design.Process.ProcessState",
                            element: this
                        });
                    }
                    get showProcess() {
                        return this.state.get("showProcess");
                    }
                    get showKey() {
                        return this.state.get("showKey");
                    }
                    get showStage() {
                        return this.state.get("showStage");
                    }
                    get showStatus() {
                        return this.state.get("showStatus");
                    }
                    get showLabels() {
                        return this.state.get("showLabels");
                    }
                    get currentKey() {
                        return this.state.get("currentKey");
                    }
                    get currentStage() {
                        return this.state.get("currentStage");
                    }
                    get currentStatus() {
                        return this.state.get("currentStatus");
                    }
                    get fontSize() {
                        return this.state.get("fontSize");
                    }
                    get itemHeight() {
                        return this.fontSize + 10 + (5 - (this.fontSize % 5));
                    }
                    get orientation() {
                        return this.state.get("orientation", ProcessStateOrientation.Horizontal);
                    }
                    get processName() {
                        return this.state.get("processName");
                    }
                    get displayedSectionCount() {
                        return (this.showProcess ? 1 : 0) +
                            (this.showKey ? 1 : 0) +
                            (this.showStage ? 1 : 0) +
                            (this.showStatus ? 1 : 0);
                    }
                    get absoluteHeight() {
                        let isHorizontal = this.orientation == ProcessStateOrientation.Horizontal;
                        let multiplier = isHorizontal ? 2 : this.displayedSectionCount * 2;
                        return this.itemHeight * multiplier;
                    }
                    toJSON() {
                        return _.extend(super.toJSON(), {
                            itemHeight: this.itemHeight,
                            displayedSectionCount: this.displayedSectionCount,
                            absoluteHeight: this.absoluteHeight
                        });
                    }
                };
                ProcessState = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], ProcessState);
                Process.ProcessState = ProcessState;
            })(Process = Core.Process || (Core.Process = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Process;
            (function (Process) {
                let ProcessView = class ProcessView extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Process.ProcessView",
                            designScript: "PDJS.Canvas.Design.Process.ProcessView",
                            element: this
                        });
                        this.calculateRowCount();
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get activeTabIndex() {
                        return Core.TabIndex.calculate(this.tabIndex);
                    }
                    get entityId() {
                        return this.document.attributes["entityId"];
                    }
                    get showKeys() {
                        return this.state.get("showKeys");
                    }
                    get showStages() {
                        return this.state.get("showStages");
                    }
                    get showState() {
                        return this.state.get("showState");
                    }
                    get showDecisions() {
                        return this.state.get("showDecisions");
                    }
                    get showDecisionDestinations() {
                        return this.state.get("showDecisionDestinations");
                    }
                    get showCurrentKey() {
                        return this.state.get("showCurrentKey");
                    }
                    get showVisitedKeys() {
                        return this.state.get("showVisitedKeys");
                    }
                    get showCurrentStage() {
                        return this.state.get("showCurrentStage");
                    }
                    get showVisitedStages() {
                        return this.state.get("showVisitedStages");
                    }
                    get currentKey() {
                        return this.state.get("currentKey");
                    }
                    get currentStage() {
                        return this.state.get("currentStage");
                    }
                    get currentStatus() {
                        return this.state.get("currentStatus");
                    }
                    get keys() {
                        return this.state.get("keys");
                    }
                    get stages() {
                        return this.state.get("stages");
                    }
                    get keyHeight() {
                        return this.state.get("keyHeight");
                    }
                    get keyFontSize() {
                        return this.state.get("keyFontSize");
                    }
                    get stageHeight() {
                        return this.state.get("stageHeight", 120);
                    }
                    get stageFontSize() {
                        return this.state.get("stageFontSize", 12);
                    }
                    get gridColumnWidth() {
                        return this.state.get("gridColumnWidth", 120);
                    }
                    get currentStageBackColor() {
                        return this.state.get("currentStageBackColor", "var(--visiv-theme-canvas-process-current-stage-back-color)");
                    }
                    get currentStageBorderColor() {
                        return this.state.get("currentStageBorderColor", "var(--visiv-theme-canvas-process-current-stage-border-color)");
                    }
                    get currentStageBorderWidth() {
                        return this.state.get("currentStageBorderWidth");
                    }
                    get currentStageForeColor() {
                        return this.state.get("currentStageForeColor", "var(--visiv-theme-canvas-process-current-stage-text-color)");
                    }
                    get selectedStageBackColor() {
                        return this.state.get("selectedStageBackColor", "var(--visiv-theme-canvas-process-selected-stage-back-color)");
                    }
                    get selectedStageBorderColor() {
                        return this.state.get("selectedStageBorderColor", "var(--visiv-theme-canvas-process-selected-stage-border-color)");
                    }
                    get selectedStageBorderWidth() {
                        return this.state.get("selectedStageBorderWidth");
                    }
                    get selectedStageForeColor() {
                        return this.state.get("selectedStageForeColor", "var(--visiv-theme-canvas-process-selected-stage-text-color)");
                    }
                    get visitedStageBackColor() {
                        return this.state.get("visitedStageBackColor", "var(--visiv-theme-canvas-process-visited-stage-back-color)");
                    }
                    get visitedStageBorderColor() {
                        return this.state.get("visitedStageBorderColor", "var(--visiv-theme-canvas-process-visited-stage-border-color)");
                    }
                    get visitedStageBorderWidth() {
                        return this.state.get("visitedStageBorderWidth");
                    }
                    get visitedStageForeColor() {
                        return this.state.get("visitedStageForeColor", "var(--visiv-theme-canvas-process-visited-stage-text-color)");
                    }
                    get currentKeyBackColor() {
                        return this.state.get("currentKeyBackColor", "var(--visiv-theme-canvas-process-current-key-back-color)");
                    }
                    get currentKeyBorderColor() {
                        return this.state.get("currentKeyBorderColor", "var(--visiv-theme-canvas-process-current-key-border-color)");
                    }
                    get currentKeyBorderWidth() {
                        return this.state.get("currentKeyBorderWidth");
                    }
                    get currentKeyForeColor() {
                        return this.state.get("currentKeyForeColor", "var(--visiv-theme-canvas-process-current-key-text-color)");
                    }
                    get visitedKeyBackColor() {
                        return this.state.get("visitedKeyBackColor", "var(--visiv-theme-canvas-process-visited-key-back-color)");
                    }
                    get visitedKeyBorderColor() {
                        return this.state.get("visitedKeyBorderColor", "var(--visiv-theme-canvas-process-visited-key-border-color)");
                    }
                    get visitedKeyBorderWidth() {
                        return this.state.get("visitedKeyBorderWidth");
                    }
                    get visitedKeyForeColor() {
                        return this.state.get("visitedKeyForeColor", "var(--visiv-theme-canvas-process-visited-key-text-color)");
                    }
                    get rowCount() {
                        return this.m_rowCount;
                    }
                    calculateRowCount() {
                        let count = 0;
                        this.keys.forEach(key => {
                            let stageCount = this.stages.filter(stage => {
                                return stage.keyId == key.id;
                            }).length;
                            count = stageCount > count ? stageCount : count;
                        });
                        this.m_rowCount = count;
                    }
                };
                ProcessView = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], ProcessView);
                Process.ProcessView = ProcessView;
            })(Process = Core.Process || (Core.Process = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                class Shape extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-canvas-shape-back-color)");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "var(--visiv-theme-canvas-shape-border-color)");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderStyle() {
                        return this.state.get("borderStyle");
                    }
                    set borderStyle(value) {
                        this.state.set("borderStyle", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                }
                Shapes.Shape = Shape;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                class Ellipse extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Shapes.Ellipse",
                            designScript: "PDJS.Canvas.Design.Shapes.Ellipse",
                            element: this
                        });
                    }
                }
                Shapes.Ellipse = Ellipse;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                let LineCapShape;
                (function (LineCapShape) {
                    LineCapShape[LineCapShape["none"] = 0] = "none";
                    LineCapShape[LineCapShape["circle"] = 1] = "circle";
                    LineCapShape[LineCapShape["square"] = 2] = "square";
                    LineCapShape[LineCapShape["triangle"] = 3] = "triangle";
                })(LineCapShape = Shapes.LineCapShape || (Shapes.LineCapShape = {}));
                class Line extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Shapes.Line",
                            designScript: "PDJS.Canvas.Design.Shapes.Line",
                            element: this
                        });
                    }
                    get backgroundColor() {
                        return this.lineColor;
                    }
                    set backgroundColor(value) {
                        this.endCapColor = value;
                        this.startCapColor = value;
                        this.lineColor = value;
                    }
                    get lineColor() {
                        return this.state.get("lineColor", "var(--visiv-theme-base-3-border-color)");
                    }
                    set lineColor(value) {
                        this.state.set("lineColor", value);
                    }
                    get lineWeight() {
                        return this.state.get("lineWeight");
                    }
                    set lineWeight(value) {
                        this.state.set("lineWeight", value);
                    }
                    get startCapShape() {
                        return this.state.get("startCapShape");
                    }
                    set startCapShape(value) {
                        this.state.set("startCapShape", value);
                    }
                    get startCapHeight() {
                        return this.state.get("startCapHeight");
                    }
                    set startCapHeight(value) {
                        this.state.set("startCapHeight", value);
                    }
                    get startCapWidth() {
                        return this.state.get("startCapWidth");
                    }
                    set startCapWidth(value) {
                        this.state.set("startCapWidth", value);
                    }
                    get startCapColor() {
                        return this.state.get("startCapColor", "var(--visiv-theme-base-3-border-color)");
                    }
                    set startCapColor(value) {
                        this.state.set("startCapColor", value);
                    }
                    get endCapShape() {
                        return this.state.get("endCapShape");
                    }
                    set endCapShape(value) {
                        this.state.set("endCapShape", value);
                    }
                    get endCapHeight() {
                        return this.state.get("endCapHeight");
                    }
                    set endCapHeight(value) {
                        this.state.set("endCapHeight", value);
                    }
                    get endCapWidth() {
                        return this.state.get("endCapWidth");
                    }
                    set endCapWidth(value) {
                        this.state.set("endCapWidth", value);
                    }
                    get endCapColor() {
                        return this.state.get("endCapColor", "var(--visiv-theme-base-3-border-color)");
                    }
                    set endCapColor(value) {
                        this.state.set("endCapColor", value);
                    }
                    get currentMaxHeight() {
                        let result = 0;
                        if (this.startCapHeight > result)
                            result = this.startCapHeight;
                        if (this.endCapHeight > result)
                            result = this.endCapHeight;
                        if (this.lineWeight > result)
                            result = this.lineWeight;
                        return result;
                    }
                }
                Shapes.Line = Line;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                class Rectangle extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Shapes.Rectangle",
                            designScript: "PDJS.Canvas.Design.Shapes.Rectangle",
                            element: this
                        });
                    }
                    get borderRadius() {
                        return this.state.get("borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("borderRadius", value);
                    }
                }
                Shapes.Rectangle = Rectangle;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                let TriangleRotation;
                (function (TriangleRotation) {
                    TriangleRotation[TriangleRotation["rotate0"] = 0] = "rotate0";
                    TriangleRotation[TriangleRotation["rotate90"] = 1] = "rotate90";
                    TriangleRotation[TriangleRotation["rotate180"] = 2] = "rotate180";
                    TriangleRotation[TriangleRotation["rotate270"] = 3] = "rotate270";
                })(TriangleRotation = Shapes.TriangleRotation || (Shapes.TriangleRotation = {}));
                class Triangle extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                    }
                    get rotation() {
                        return this.state.get("rotation", TriangleRotation.rotate0);
                    }
                    set rotation(value) {
                        this.state.set("rotation", value);
                    }
                }
                Shapes.Triangle = Triangle;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                class IsoscelesTriangle extends Shapes.Triangle {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Shapes.IsoscelesTriangle",
                            designScript: "PDJS.Canvas.Design.Shapes.IsoscelesTriangle",
                            element: this
                        });
                    }
                }
                Shapes.IsoscelesTriangle = IsoscelesTriangle;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Shapes;
            (function (Shapes) {
                class RightTriangle extends Shapes.Triangle {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Shapes.RightTriangle",
                            designScript: "PDJS.Canvas.Design.Shapes.RightTriangle",
                            element: this
                        });
                    }
                }
                Shapes.RightTriangle = RightTriangle;
            })(Shapes = Core.Shapes || (Core.Shapes = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Core;
        (function (Core) {
            var Views;
            (function (Views) {
                let EventHistoryView = class EventHistoryView extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Views.EventHistoryView",
                            designScript: "PDJS.Canvas.Design.Views.EventHistoryView",
                            element: this
                        });
                    }
                    get isDestroyable() {
                        return this.state.get("isDestroyable");
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    get contextFilters() {
                        return this.state.get("contextFilters", []);
                    }
                };
                EventHistoryView = __decorate([
                    Jade.InterfaceGuard.implement(Core.IIndexableGuard)
                ], EventHistoryView);
                Views.EventHistoryView = EventHistoryView;
            })(Views = Core.Views || (Core.Views = {}));
        })(Core = Canvas.Core || (Canvas.Core = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            Jade.Data.Database.onCreate((e) => {
                e.db.createObjectStore("settings", {
                    keyPath: "id",
                    autoIncrement: false
                });
            });
            Jade.Application.onStart(() => {
                CanvasJS.Design.ClipboardPasteEvent.handler = (e) => {
                    let svc = new PDJS.Services.Canvas.ElementService();
                    let doc = CanvasJS.Design.Environment.document.source;
                    svc.createDesignElements({
                        documentId: doc.id,
                        sessionId: doc.sessionId,
                        elements: e.states,
                        reset: e.reset,
                        success: (response) => {
                            e.commit(response.data);
                        },
                        error: () => {
                            e.cancel();
                        }
                    });
                };
                CanvasJS.Design.DeleteElementEvent.handler = (e) => {
                    let svc = new PDJS.Services.Canvas.ElementService();
                    let doc = CanvasJS.Design.Environment.document.source;
                    svc.deleteDesignElements({
                        documentId: doc.id,
                        sessionId: doc.sessionId,
                        elements: e.states,
                        success: (response) => {
                            e.commit();
                        },
                        error: () => {
                            e.cancel();
                        }
                    });
                };
            });
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                Jade.Application.onStart(() => {
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.ColorPaletteContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.ShapeBorderContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.BorderStyleContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.BorderWeightContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.AlignmentContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.LineStartCapShapeMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.LineEndCapShapeMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.ElementContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.TabIndexContextMenuGroup());
                    Jade.UI.Controls.ContextMenuGroups.add(new ContextMenu.ViewContextMenuGroup());
                });
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                Jade.Application.onStart(() => {
                    Jade.UI.Controls.RibbonBarSections.add(new RibbonBar.HomeRibbonSection());
                    Jade.UI.Controls.RibbonBarSections.add(new RibbonBar.CodeAndStylesRibbonSection());
                    Jade.UI.Controls.RibbonBarSections.add(new RibbonBar.ShapeRibbonSection());
                    Jade.UI.Controls.RibbonBarSections.add(new RibbonBar.FormFieldRibbonSection());
                    Jade.UI.Controls.RibbonBarSections.add(new RibbonBar.ViewRibbonSection());
                });
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let CssClass;
            (function (CssClass) {
                CssClass["ElementError"] = "-pdjs-element-design-error";
            })(CssClass = Design.CssClass || (Design.CssClass = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DesignerDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get documentId() {
                    return this.state.get("documentId");
                }
                get canvasType() {
                    return this.state.get("canvasType");
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId");
                }
                get extensionId() {
                    return this.state.get("extensionId");
                }
                get isListBased() {
                    return this.state.get("isListBased");
                }
                get isFileBased() {
                    return this.state.get("isFileBased");
                }
                template() {
                    return `<div class="${CanvasJS.Design.CanvasCss.Design}"></div>`;
                }
                onInit(e) {
                    this.m_documentService = new PDJS.Services.Canvas.DocumentService();
                    CanvasJS.Design.Environment.store.set("dialog", this);
                    this.controls.add(new CanvasJS.Design.Workspace({}));
                }
                onActivate(e) {
                    CanvasJS.Design.Environment.statusBar.controls.add(new Design.StatusBar.Theme());
                    CanvasJS.Design.Environment.statusBar.controls.add(new Design.StatusBar.Errors({}));
                    this.loadDocument();
                    this.loadToolBox();
                    this.loadHotKeys();
                }
                getWindowOptions() {
                    return {
                        title: false,
                        maximized: true,
                        height: 500,
                        width: 700
                    };
                }
                loadToolBox() {
                    let service = new PDJS.Services.Canvas.ToolBoxService();
                    let loadingMessage = new PDJS.Shared.UI.Controls.Message({
                        message: `<span style="font-size: 20px;">Loading Items...</span>`
                    });
                    CanvasJS.Design.Environment.toolBox.controls.add(loadingMessage);
                    service.load({
                        canvasType: this.canvasType,
                        success: (e) => {
                            CanvasJS.Design.Environment.toolBox.loadToolBoxItems(e.data);
                            CanvasJS.Design.Environment.toolBox.controls.remove(loadingMessage);
                        }
                    });
                }
                loadDocument() {
                    let loadingMessage = new PDJS.Shared.UI.Controls.Message({
                        message: `<span style="font-size: 20px;">Loading Document...</span>`
                    });
                    CanvasJS.Design.Environment.surface.controls.add(loadingMessage);
                    this.m_documentService.loadDesignDocument({
                        documentId: this.documentId,
                        success: (e) => {
                            let model = new Canvas.Core.Documents.DesignDocument(e.data.document);
                            CanvasJS.Design.Environment.surface.loadDocument(new Design.DocumentView({
                                $source: model,
                                canvasType: this.canvasType,
                                entityTypeId: this.entityTypeId,
                                extensionId: this.extensionId,
                                documentTypeId: this.documentTypeId,
                                isFileBased: this.isFileBased,
                                isListBased: this.isListBased
                            }));
                            if (loadingMessage != null) {
                                CanvasJS.Design.Environment.surface.controls.remove(loadingMessage);
                            }
                        }
                    });
                }
                loadHotKeys() {
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "ctrl e",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/close", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "ctrl s",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/save", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "alt f s",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/save", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                }
                static open(options) {
                    let result = new DesignerDialog(options);
                    return result;
                }
            }
            Design.DesignerDialog = DesignerDialog;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentView extends CanvasJS.Design.DocumentDesignViewBase {
                constructor(options) {
                    super(options);
                    CanvasJS.Design.Environment.store.set("document", this);
                }
                get documentId() {
                    return this.state.get("documentId");
                }
                get canvasType() {
                    return this.state.get("canvasType");
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId");
                }
                get extensionId() {
                    return this.state.get("extensionId");
                }
                get isListBased() {
                    return this.state.get("isListBased", false);
                }
                get isFileBased() {
                    return this.state.get("isFileBased", false);
                }
                load() {
                    this.source.elements.each((item) => {
                        let element = item.resolver.getViewOf(CanvasJS.CanvasType.Design);
                        if (element != null) {
                            this.controls.add(element);
                        }
                    });
                    CanvasJS.Design.Environment
                        .events
                        .publish(CanvasJS.Design.CanvasEvent.DOCUMENT_LOAD);
                }
                setHeader(content) {
                    let headerNode = this.node.parent().find("div[role=canvas-header]");
                    if (headerNode.length > 0) {
                        headerNode.empty();
                        headerNode.html(content);
                    }
                    else {
                        headerNode = $(`<div role="canvas-header">${content}</div>`);
                        this.node.before(headerNode);
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass("-pdjs-canvas-document-design");
                    this.node.attr("document-id", this.source.id);
                    this.addInternalStyles();
                    this.load();
                }
                addSelectionBox() {
                    this.controls.add(new Design.SelectionBox({}));
                }
                onStateChanged() {
                    this.node.css({
                        backgroundColor: this.source.backgroundColor,
                        width: this.source.width,
                        height: this.source.height
                    });
                }
                addInternalStyles() {
                    let internalStyles = new Canvas.InternalStyles({
                        documentId: this.source.id,
                        styles: this.source.internalStyles
                    });
                    internalStyles.addStyles();
                }
            }
            Design.DocumentView = DocumentView;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let ElementEditorLayoutType;
            (function (ElementEditorLayoutType) {
                ElementEditorLayoutType["Panels"] = "FeatureBlendJS.Views.FeatureBlendLayoutType.Panels";
                ElementEditorLayoutType["Tabbed"] = "FeatureBlendJS.Views.FeatureBlendLayoutType.Tabbed";
                ElementEditorLayoutType["Simple"] = "FeatureBlendJS.Views.FeatureBlendLayoutType.Simple";
            })(ElementEditorLayoutType = Design.ElementEditorLayoutType || (Design.ElementEditorLayoutType = {}));
            class ElementEditorAttribute {
                static convertEnumToType(type) {
                    let result = null;
                    let typeName = type;
                    if (typeName == null) {
                        result = ElementEditorLayoutType.Tabbed;
                    }
                    result = Jade.Type.getType(typeName);
                    return result;
                }
                static read(element) {
                    let result = _.extend({
                        layout: ElementEditorLayoutType.Tabbed,
                        height: 500,
                        width: 500
                    }, element[ElementEditorAttribute.ATTRIBUTE_KEY] || {});
                    return _.extend(result, {
                        layoutType: ElementEditorAttribute.convertEnumToType(result.layout)
                    });
                }
            }
            ElementEditorAttribute.ATTRIBUTE_KEY = "___elementEditor___";
            Design.ElementEditorAttribute = ElementEditorAttribute;
            function elementEditor(layout, height = 500, width = 400) {
                return function attribute(constr) {
                    return class extends constr {
                        constructor(...args) {
                            super(...args);
                            this[ElementEditorAttribute.ATTRIBUTE_KEY] = {
                                layout: layout,
                                height: height,
                                width: width
                            };
                        }
                    };
                };
            }
            Design.elementEditor = elementEditor;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            class FeatureDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get okButton() {
                    return this.node.find("button[command=ok]");
                }
                get featureButtons() {
                    return this.state.get("featureButtons");
                }
                get cancelButton() {
                    return this.node.find("button[command=cancel]");
                }
                get editor() {
                    return this.m_editor;
                }
                get targetId() {
                    return this.state.get("args.targetId");
                }
                get targetData() {
                    return this.state.get("args.targetData");
                }
                get targetType() {
                    return this.state.get("args.targetType");
                }
                get arbiterType() {
                    return this.state.get("args.arbiterType");
                }
                get attributes() {
                    return this.state.get("args.attributes");
                }
                get properties() {
                    return this.state.get("args.properties");
                }
                get layoutType() {
                    return this.state.get("args.layoutType");
                }
                template() {
                    return super.template(`<div class="feature-blend-dialog">
                                    <div role="feature" data-controls></div>
                                    <div role="buttons" class="-pdjs-dialog-button-deck">
                                        <button command="ok" class="-pdjs-dialog-button -pdjs-feature-dialog-button">OK</button>
                                        <button command="cancel" class="-pdjs-dialog-button -pdjs-feature-dialog-button">Cancel</button>
                                    </div>
                                </div>`);
                }
                onActivate(e) {
                    var _a, _b, _c, _d, _e, _f, _g, _h;
                    super.onActivate(e);
                    this.editor_init();
                    this.editor.load(this.getRequestData());
                    this.okButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.save();
                    });
                    this.cancelButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.close();
                    });
                    this.cancelButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.close();
                    });
                    if (((_b = (_a = this.featureButtons) === null || _a === void 0 ? void 0 : _a.ok) === null || _b === void 0 ? void 0 : _b.visible) === false) {
                        this.okButton.hide();
                    }
                    this.okButton.text(((_d = (_c = this.featureButtons) === null || _c === void 0 ? void 0 : _c.ok) === null || _d === void 0 ? void 0 : _d.label) || "OK");
                    if (((_f = (_e = this.featureButtons) === null || _e === void 0 ? void 0 : _e.cancel) === null || _f === void 0 ? void 0 : _f.visible) === false) {
                        this.cancelButton.hide();
                    }
                    this.cancelButton.text(((_h = (_g = this.featureButtons) === null || _g === void 0 ? void 0 : _g.ok) === null || _h === void 0 ? void 0 : _h.label) || "Cancel");
                }
                getRequestData() {
                    return null;
                }
                getDefaultOptions() {
                    return {
                        args: {},
                        padding: 0,
                        height: 550,
                        width: 500,
                        resizable: true
                    };
                }
                onInputReturnKeystroke() {
                    this.okButton.focus();
                    this.okButton.click();
                }
                getEditor() {
                    return new Features.FeatureEditor({
                        layoutType: this.layoutType,
                        onLoadError: (e) => {
                            this.close();
                        },
                        onLoadSuccess: (e) => {
                            let dialogTitle = e.output.dialogTitle;
                            if (dialogTitle) {
                                this.setWindowOptions({
                                    title: dialogTitle
                                });
                            }
                            let dialogHeight = e.output.dialogHeight;
                            if (dialogHeight) {
                                this.setWindowOptions({
                                    height: dialogHeight
                                });
                            }
                            let dialogWidth = e.output.dialogWidth;
                            if (dialogWidth) {
                                this.setWindowOptions({
                                    width: dialogWidth
                                });
                            }
                            if (dialogHeight != null || dialogWidth != null) {
                                this.center();
                            }
                        }
                    });
                }
                editor_init() {
                    this.m_editor = this.getEditor();
                    this.controls.add(this.m_editor);
                }
                save() {
                    this.editor.commit({
                        success: (e) => {
                            this.close({
                                name: "ok",
                                data: e
                            });
                        }
                    });
                }
            }
            Features.FeatureDialog = FeatureDialog;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ElementEditorDialog extends PDJS.Shared.Features.FeatureDialog {
                getRequestData() {
                    return {
                        "initialized": false,
                        "arbiter": {
                            type: "ProspectDirector.Web.UI.Canvas.ElementArbiter",
                            targetType: this.targetType,
                            json: JSON.stringify(this.targetData),
                            attributes: this.attributes
                        }
                    };
                }
                getEditor() {
                    return new PDJS.Shared.Features.FeatureEditor({
                        loadMethod: PDJS.Shared.Features.LoadMethod.LoadWithValidaton,
                        layoutType: this.layoutType,
                        onCommitSuccess: (e) => {
                            this.close({
                                name: "ok",
                                data: e
                            });
                        }
                    });
                    ;
                }
                static open(options) {
                    return new ElementEditorDialog(options);
                }
            }
            Design.ElementEditorDialog = ElementEditorDialog;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ElementLayoutSettings extends CanvasJS.ElementModel {
                static get columnCount() {
                    this.ensurelocalStorage();
                    return this.m_data.columnCount || 1;
                }
                static set columnCount(value) {
                    this.ensurelocalStorage();
                    this.m_data.columnCount = value;
                }
                static get columnWidth() {
                    this.ensurelocalStorage();
                    return this.m_data.columnWidth || 300;
                }
                static set columnWidth(value) {
                    this.ensurelocalStorage();
                    this.m_data.columnWidth = value;
                }
                static get columnSpacing() {
                    this.ensurelocalStorage();
                    return this.m_data.columnSpacing || 20;
                }
                static set columnSpacing(value) {
                    this.ensurelocalStorage();
                    this.m_data.columnSpacing = value;
                }
                static get rowSpacing() {
                    this.ensurelocalStorage();
                    return this.m_data.rowSpacing || 5;
                }
                static set rowSpacing(value) {
                    this.ensurelocalStorage();
                    this.m_data.rowSpacing = value;
                }
                static get data() {
                    this.ensurelocalStorage();
                    return this.m_data;
                }
                static save() {
                    localStorage.setItem(this.LOCAL_STORAGE_KEY, JSON.stringify(this.m_data));
                }
                static applyLayout(args) {
                    let colIndex = 0;
                    let rowHeight = 0;
                    let currentX = args.xOrigin;
                    let currentY = args.yOrigin;
                    _.each(args.elements, (element) => {
                        if (element.height > rowHeight) {
                            rowHeight = element.height;
                        }
                        element.width = this.columnWidth;
                        element.x = currentX;
                        element.y = currentY;
                        if (colIndex < (this.columnCount - 1)) {
                            currentX += element.width + this.columnSpacing;
                            colIndex += 1;
                        }
                        else {
                            currentX = args.xOrigin;
                            currentY += rowHeight + this.rowSpacing;
                            colIndex = 0;
                            rowHeight = 0;
                        }
                    });
                }
                static ensurelocalStorage() {
                    if (this.m_data != null) {
                        return;
                    }
                    let data = localStorage.getItem(this.LOCAL_STORAGE_KEY);
                    try {
                        this.m_data = JSON.parse(data);
                    }
                    catch (_a) {
                        data = null;
                    }
                    if (data == null) {
                        this.m_data = {
                            columnCount: 1,
                            columnSpacing: 20,
                            columnWidth: 300,
                            rowSpacing: 5
                        };
                    }
                }
            }
            ElementLayoutSettings.LOCAL_STORAGE_KEY = "ElementLayoutSettings";
            Design.ElementLayoutSettings = ElementLayoutSettings;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ElementView extends CanvasJS.Design.ElementDesignViewBase {
                onComplete(e) {
                    super.onComplete(e);
                    this.handleErrors();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.handleErrors();
                }
                handleErrors() {
                    let currentError = this.controls.getByType(Design.ElementViewError).first();
                    if (currentError != null) {
                        this.controls.remove(currentError);
                    }
                    if (this.source.hasErrors) {
                        this.controls.add(new Design.ElementViewError({
                            insertAt: `.-canvasjs-overlay`,
                            element: this
                        }));
                        let highlight = this.node.find(".-canvasjs-highlight").detach();
                        let overlay = this.node.find(".-canvasjs-overlay");
                        overlay.append(highlight);
                    }
                }
            }
            Design.ElementView = ElementView;
            class ElementViewBase extends ElementView {
                get source() {
                    return this.m_source;
                }
            }
            Design.ElementViewBase = ElementViewBase;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ElementViewError extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get element() {
                    return this.state.get("element");
                }
                template() {
                    let result = $(`<div class="${Design.CssClass.ElementError}"></div>`);
                    if (this.element.source.hasNonRecoverableErrors) {
                        result.append(this.getOverlay());
                        result.append(this.getIcon("error.png"));
                    }
                    else {
                        result.append(this.getIcon());
                        result.css({
                            backgroundImage: "none"
                        });
                    }
                    return result;
                }
                getIcon(icon) {
                    let result = $(`<div role="icon"></div>`);
                    result.css({
                        backgroundImage: `url(${this.getIconPath(icon)})`,
                        backgroundPosition: "center center",
                        height: "32px",
                        width: "32px",
                        position: "absolute",
                        top: -8,
                        right: -8,
                        borderRadius: "32px",
                        backgroundColor: "var(--visiv-system-white)"
                    });
                    return result;
                }
                getOverlay() {
                    return $(`<table>
                    <tr>
                        <td>
                            <div style="padding-left: 37px;background-image:url(${this.getIconPath()})">
                                ${this.element.source.componentName}
                            </div>
                        </td>
                    </tr>
                </table>`);
                }
                getIconPath(icon) {
                    let iconName = this.element.source.hasNonRecoverableErrors ? "skull.png" : "error.png";
                    if (icon != null) {
                        iconName = icon;
                    }
                    return Jade.IconSet.get("pdjs")
                        .resolve(iconName, Jade.IconSetSizeSpecificDirectory.x32);
                }
            }
            Design.ElementViewError = ElementViewError;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class FeatureEditor {
                static showForDocument(document) {
                    PDJS.Shared.Features.FeatureDialogForJson.open({
                        title: `Edit | Document`,
                        height: 450,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.UI.Canvas.Document",
                            targetData: document.source.toJSON(),
                            layoutType: Design.ElementEditorAttribute.convertEnumToType(Design.ElementEditorLayoutType.Tabbed)
                        },
                        select: {
                            ok: (sender, e) => {
                                document.source.state.update(e.target);
                                CanvasJS.Design.Environment.selection.box.hide();
                                CanvasJS.Design.Environment.selection.box.show();
                                CanvasJS.Design.Environment.events.publish(CanvasJS.Design.CanvasEvent.ELEMENT_EDIT);
                            }
                        }
                    });
                }
                static showForElement(element) {
                    let editorSettings = Design.ElementEditorAttribute.read(element);
                    Design.ElementEditorDialog.open({
                        title: `Edit | ${element.source.componentName}`,
                        height: editorSettings.height,
                        width: editorSettings.width,
                        args: {
                            targetType: element.source.componentType,
                            targetData: element.source.toJSON(),
                            layoutType: editorSettings.layoutType
                        },
                        select: {
                            ok: (sender, e) => {
                                element.source.state.update(e.target);
                                CanvasJS.Design.Environment.selection.box.hide();
                                CanvasJS.Design.Environment.selection.box.show();
                                CanvasJS.Design.Environment.events.publish(CanvasJS.Design.CanvasEvent.ELEMENT_EDIT);
                            }
                        }
                    });
                }
            }
            Design.FeatureEditor = FeatureEditor;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class SelectionBox extends CanvasJS.Design.SelectionBox {
                onElementInspect(e) {
                    Design.FeatureEditor.showForElement(e.element);
                }
            }
            Design.SelectionBox = SelectionBox;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class AutoArrangeCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "elements/auto-arrange",
                        icon: "layout_vertical.png",
                        label: "Auto Arrange",
                        tooltip: "Automatically arrange the selected elements into columns.",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Canvas.Design.Dialogs.AutoArrangeDialog.open({
                        select: {
                            ok: (sender, e) => {
                                Design.ElementLayoutSettings.applyLayout({
                                    xOrigin: CanvasJS.Design.Environment.selectionBox.dimensions.left,
                                    yOrigin: CanvasJS.Design.Environment.selectionBox.dimensions.top,
                                    elements: CanvasJS.Design.Environment.selection.toArray()
                                });
                                CanvasJS.Design.Environment.selectionBox.draw();
                            }
                        }
                    });
                }
                onStateChanged(e) {
                    this.enabled = CanvasJS.Design.Environment.selection.count > 0;
                }
            }
            Design.AutoArrangeCommand = AutoArrangeCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class AutoTabIndexCommand extends Jade.Command {
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "form-field/auto-tab-indexes",
                        label: "Auto Tab Indexes",
                        icon: "rubber_stamp.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    let models = new Jade.Collection();
                    CanvasJS.Design.Environment.selection.each((item) => {
                        if (item.source instanceof PDJS.Canvas.Core.ElementModel) {
                            models.add(item.source);
                        }
                    });
                    this.enabled = Jade.InterfaceGuard.anyImplement(models.toArray(), Canvas.Core.IIndexableGuard);
                }
                onExecute(e) {
                    let inColumns = e === "columns";
                    if (this.document.tabIndexes.count > 0) {
                        this.continuePreviousPrompt(inColumns);
                    }
                    else {
                        this.autoTabIndex(false, inColumns);
                    }
                }
                continuePreviousPrompt(inColumns) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNoCancel,
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        title: "Auto Tab Indexes",
                        message: "A previous tab order has been detected.<br/>Do you want to add to the existing tab order?",
                        select: (e) => {
                            e.close();
                            switch (e.name) {
                                case Jade.UI.Dialogs.MessageDialogButton.yes:
                                    this.autoTabIndex(true, inColumns);
                                    break;
                                case Jade.UI.Dialogs.MessageDialogButton.no:
                                    this.autoTabIndex(false, inColumns);
                                    break;
                            }
                        }
                    });
                }
                autoTabIndex(append = false, columns = false) {
                    let map = this.createMap(columns);
                    let keys = this.sortKeys(map);
                    if (!append) {
                        this.document.tabIndexes.clear();
                    }
                    _.each(keys, (key) => {
                        let id = map[key];
                        if (append) {
                            if (this.document.tabIndexes.contains(id)) {
                                this.document.tabIndexes.remove(id);
                            }
                        }
                        this.document.tabIndexes.add(id);
                    });
                    this.updateTabIndexLabels();
                }
                createMap(columns) {
                    let minX = Number.MAX_VALUE;
                    let minY = Number.MAX_VALUE;
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (Jade.InterfaceGuard.is(element.source, Canvas.Core.IIndexableGuard)) {
                            if (element.x < minX)
                                minX = element.x;
                            if (element.y < minY)
                                minY = element.y;
                        }
                    });
                    let map = {};
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (Jade.InterfaceGuard.is(element.source, Canvas.Core.IIndexableGuard)) {
                            let x = this.round(element.x - minX, 100) + minX;
                            let y = this.round(element.y - minY, 25) + minY;
                            if (columns) {
                                map[this.formatKey(x, y)] = element.ID;
                            }
                            else {
                                map[this.formatKey(y, x)] = element.ID;
                            }
                        }
                    });
                    return map;
                }
                formatKey(val1, val2) {
                    return this.pad(val1) + this.pad(val2);
                }
                pad(value) {
                    return ("000000" + value.toString()).slice(-5);
                }
                round(value, factor) {
                    return Math.round(value / factor) * factor;
                }
                sortKeys(map) {
                    let keys = [];
                    _.each(map, (value, key) => {
                        keys[keys.length] = key;
                    });
                    keys.sort();
                    return keys;
                }
                updateTabIndexLabels() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/canvas/standard": {}
                    }, {
                        force: true,
                        overwrite: false
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .execute("pdjs/canvas/standard:form-field/tab-index-toggle", {
                        preventToggle: true
                    });
                }
            }
            Design.AutoTabIndexCommand = AutoTabIndexCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let ICustomColorCommandTarget;
            (function (ICustomColorCommandTarget) {
                ICustomColorCommandTarget["backgroundColor"] = "backgroundColor";
                ICustomColorCommandTarget["borderColor"] = "borderColor";
            })(ICustomColorCommandTarget = Design.ICustomColorCommandTarget || (Design.ICustomColorCommandTarget = {}));
            class CustomColorCommand extends Jade.Command {
                onExecute(target) {
                    PDJS.Shared.UI.Controls.ColorsDialog.open({
                        title: target === ICustomColorCommandTarget.backgroundColor ? "Background Color" : "Border Color",
                        select: {
                            ok: (e, data) => {
                                this.setColor(target, data.color);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "element/custom-color",
                        label: "More colors...",
                        icon: "painters_palette.png",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                setColor(target, color) {
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (element.source.has(target)) {
                            element.source[target] = color;
                        }
                    });
                }
            }
            Design.CustomColorCommand = CustomColorCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class Commands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/canvas/standard");
                }
                registerCommands(e) {
                    e.commands.add(new Design.DocumentSaveCommand());
                    e.commands.add(new Design.DocumentCloseCommand());
                    e.commands.add(new Design.DocumentSettingsCommand());
                    e.commands.add(new Design.DocumentRulesCommand());
                    e.commands.add(new Design.ExternalCodeAndStylesCommand());
                    e.commands.add(new Design.DocumentVariablesCommand());
                    e.commands.add(new Design.FormFieldRequiredCommand({
                        id: "form-field/required/enable",
                        label: "Required",
                        tooltip: "Sets the selected form field elements to be required.",
                        icon: "breakpoint.png",
                        isRequired: true
                    }));
                    e.commands.add(new Design.FormFieldRequiredCommand({
                        id: "form-field/required/disable",
                        label: "Not Required",
                        tooltip: "Sets the selected form field elements to no longer be required.",
                        icon: "not-required.png",
                        isRequired: false
                    }));
                    e.commands.add(new Design.InternalCodeCommand());
                    e.commands.add(new Design.InternalStylesCommand());
                    e.commands.add(new Design.AutoArrangeCommand());
                    e.commands.add(new Design.AutoTabIndexCommand());
                    e.commands.add(new Design.TabIndexCommand());
                    e.commands.add(new Design.TabIndexToggleCommand());
                    e.commands.add(new Design.LineScaleCommand({
                        id: "line/shape/scale-up",
                        label: "Scale Up",
                        tooltip: "Increase the weight of the selected line elements and the size of the start/end caps.",
                        icon: "navigate_plus.png",
                        scaling: Design.LineScaleType.increase,
                        target: Design.LineScaleTarget.shape
                    }));
                    e.commands.add(new Design.LineScaleCommand({
                        id: "line/shape/scale-down",
                        label: "Scale Down",
                        tooltip: "Decrease the weight of the selected line elements and the size of the start/end caps",
                        icon: "navigate_minus.png",
                        scaling: Design.LineScaleType.decrease,
                        target: Design.LineScaleTarget.shape
                    }));
                    e.commands.add(new Design.LineCapShapeCommand({
                        id: "line/start/shape",
                        label: "Shape",
                        tooltip: "Change the shape of the start cap of the selected line elements.",
                        target: Design.LineCapShapeTarget.startCap
                    }));
                    e.commands.add(new Design.LineCapShapeCommand({
                        id: "line/end/shape",
                        label: "Shape",
                        tooltip: "Change the shape of the end cap of the selected line elements.",
                        target: Design.LineCapShapeTarget.endCap
                    }));
                    e.commands.add(new Design.RotateShapeCommand());
                    e.commands.add(new Design.ElementPropertiesCommand());
                    e.commands.add(new Design.CustomColorCommand());
                    e.commands.add(new Design.GridlinesToggleCommand());
                    e.commands.add(new Canvas.Shared.Views.ViewDesignerCommand());
                }
            }
            Design.Commands = Commands;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
Jade.Application.onStart(function () {
    Jade.CommandGroups.add(PDJS.Canvas.Design.Commands);
});
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentCloseCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "document/close",
                        label: "Close",
                        icon: "close.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    if (CanvasJS.Design.Environment.document.source.hasChanges) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Close",
                            message: `Close without saving changes?`,
                            select: {
                                ok: (sender, e2) => {
                                    sender.close();
                                    this.closeDocument(e);
                                }
                            }
                        });
                    }
                    else {
                        this.closeDocument(e);
                    }
                }
                closeDocument(e) {
                    let service = new PDJS.Services.Canvas.DocumentService();
                    let document = CanvasJS.Design.Environment.document.source;
                    service.closeDesignDocument({
                        sessionId: document.sessionId,
                        success: () => {
                            _.isFunction(e.success) ?
                                e.success() : null;
                        },
                        error: () => {
                            _.isFunction(e.error) ?
                                e.error() : null;
                        }
                    });
                }
            }
            Design.DocumentCloseCommand = DocumentCloseCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentRulesCommand extends Jade.Command {
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                onExecute(e) {
                    var _a;
                    super.onExecute(e);
                    ((_a = this.document.script) === null || _a === void 0 ? void 0 : _a.scriptId) != null ?
                        PDJS.Manage.Rules.RuleEditing.editScript(this.document.script.scriptId) :
                        this.assignRuleScript();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document/rules",
                        label: "Rules",
                        icon: "arrows_fork_three.png",
                        enabled: true,
                        tooltip: "Edit the rules script associated with this canvas.",
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                assignRuleScript() {
                    PDJS.Manage.Rules.RuleScriptSelectionDialog.open({
                        title: "Assign | Rule Script",
                        select: {
                            ok: (sender, e) => {
                                this.document.script.scriptId = e.id;
                                this.document.script.scriptName = e.name;
                                sender.close();
                                this.promptToOpenRuleScript();
                            }
                        }
                    });
                }
                promptToOpenRuleScript() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Prompt | Open Script",
                        message: "Open the script for editing?",
                        select: {
                            ok: (e) => {
                                e.close();
                                PDJS.Manage.Rules.RuleEditing.editScript(this.document.script.scriptId);
                            }
                        }
                    });
                }
            }
            Design.DocumentRulesCommand = DocumentRulesCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentSaveCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "document/save",
                        icon: "floppy_disk.png",
                        label: "Save",
                        tooltip: "Save the changes made to this canvas.",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e = {}) {
                    let countOfErroredElements = 0;
                    let elements = CanvasJS.Design.Environment.document.controls.getByType(Design.ElementView);
                    elements.each((element) => {
                        countOfErroredElements += element.source.hasErrors ? 1 : 0;
                    });
                    if (countOfErroredElements > 0) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                            title: "Save With Errors?",
                            message: `This document contains ${countOfErroredElements} element(s) with errors,
                                these elements may not display correctly while in an errored state. <br/><br/>
                                Continue with save despite these errors?`,
                            select: {
                                yes: (sender, e) => {
                                    sender.close();
                                    this.commitSave();
                                }
                            }
                        });
                    }
                    else {
                        this.commitSave();
                    }
                }
                commitSave() {
                    CanvasJS.Design.Environment.document.saveSource();
                    let documentService = new PDJS.Services.Canvas.DocumentService();
                    documentService.saveDesignDocument({
                        document: CanvasJS.Design.Environment.document.source.toJSON(),
                        success: (e) => {
                            if (e.data.hasSaveErrors) {
                                Jade.UI.Dialogs.MultiMessageDialog.open({
                                    header: "The following errors prevents the document from being saved:",
                                    messages: e.data.saveErrors,
                                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK
                                });
                                return;
                            }
                            let module = PDJS.Manage.Modules.instance.current;
                            module.settings.hasChanges = false;
                            PDJS.Shared.MessageStack.instance.success(`"${module.settings.label}" has been saved.`);
                        }
                    });
                }
            }
            Design.DocumentSaveCommand = DocumentSaveCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentSettingsCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "document/settings",
                        icon: "clipboard_checks.png",
                        label: "Settings",
                        tooltip: "Edit the settings of this canvas.",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    Design.FeatureEditor.showForDocument(CanvasJS.Design.Environment.document);
                }
            }
            Design.DocumentSettingsCommand = DocumentSettingsCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class DocumentVariablesCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "document/variables",
                        label: "Variables",
                        tooltip: "Manage the variables associated with this canvas.",
                        icon: "function.png",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Canvas.Design.Dynamics.VariablesDialog.open({
                        callbacks: {
                            ok: (sender, e) => {
                            }
                        }
                    });
                }
            }
            Design.DocumentVariablesCommand = DocumentVariablesCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ElementPropertiesCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "element/properties",
                        label: "Edit",
                        tooltip: "Edit the properties of the selected element.",
                        icon: "edit.png",
                        enabled: false,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(e) {
                    this.enabled = CanvasJS.Design.Environment.selection.count == 1
                        && !(CanvasJS.Design.Environment.selection.first() instanceof CanvasJS.Design.GroupDesignView);
                }
                onExecute() {
                    let element = CanvasJS.Design.Environment.selection.first();
                    Design.FeatureEditor.showForElement(element);
                }
            }
            Design.ElementPropertiesCommand = ElementPropertiesCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ExternalCodeAndStylesCommand extends Jade.Command {
                onExecute(e) {
                    PDJS.Canvas.Design.Dialogs.ExternalFilesDialog.open({
                        value: this.document.externalFiles,
                        select: {
                            ok: (sender, e) => {
                                this.document.externalFiles = e.value;
                            }
                        }
                    });
                }
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document/external-code-and-styles",
                        label: "External Files",
                        tooltip: "Edit the list of external stylesheets and JavaScript files associated with this canvas.",
                        enabled: true,
                        display: "label icon",
                        icon: "graph_fork.png",
                        iconSetId: "pdjs"
                    };
                }
            }
            Design.ExternalCodeAndStylesCommand = ExternalCodeAndStylesCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class FormFieldRequiredCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                }
                get isRequired() {
                    return this.props.get("isRequired", false);
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (element instanceof Design.Forms.FormField) {
                            element.source.isRequired = this.isRequired;
                        }
                    });
                }
            }
            Design.FormFieldRequiredCommand = FormFieldRequiredCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class GridlinesToggleCommand extends Jade.Command {
                get isVisible() {
                    return this.state.get("isVisible", false);
                }
                set isVisible(value) {
                    this.state.set("isVisible", value);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "gridlines/toggle",
                        icon: "layout.png",
                        label: "Show Gridlines",
                        tooltip: "Toggle the visibility of grid lines.",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    this.isVisible = !this.isVisible;
                    this.label = this.isVisible ? "Hide Gridlines" : "Show Gridlines";
                    if (this.isVisible) {
                        CanvasJS.Design.Environment.document.node.addClass("-canvasjs-gridlines");
                    }
                    else {
                        CanvasJS.Design.Environment.document.node.removeClass("-canvasjs-gridlines");
                    }
                }
            }
            Design.GridlinesToggleCommand = GridlinesToggleCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class InternalCodeCommand extends Jade.Command {
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document/internal-code",
                        label: "Script",
                        tooltip: "Edit the custom JavaScript code associated with this canvas.",
                        enabled: true,
                        display: "label icon",
                        icon: "file-type-js.png",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Shared.Coding.CodeEditorDialog.open({
                        mimeType: "text/javascript",
                        codeContent: this.document.internalScript,
                        select: {
                            ok: (sender, e) => {
                                this.document.internalScript = e.codeContent;
                            }
                        }
                    });
                }
            }
            Design.InternalCodeCommand = InternalCodeCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class InternalStylesCommand extends Jade.Command {
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document/internal-styles",
                        label: "Styles",
                        tooltip: "Edit the custom CSS styles associated with this canvas.",
                        enabled: true,
                        display: "label icon",
                        icon: "file-type-css.png",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Shared.Coding.CodeEditorDialog.open({
                        mimeType: "text/css",
                        codeContent: this.document.internalStyles,
                        select: {
                            ok: (sender, e) => {
                                this.document.internalStyles = e.codeContent;
                                this.addInternalStyles();
                            }
                        }
                    });
                }
                addInternalStyles() {
                    let internalStyles = new Canvas.InternalStyles({
                        documentId: this.document.id,
                        styles: this.document.internalStyles
                    });
                    if (internalStyles.stylesNode.length > 0) {
                        internalStyles.updateStyles();
                        return;
                    }
                    internalStyles.addStyles();
                }
            }
            Design.InternalStylesCommand = InternalStylesCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let LineCapShapeTarget;
            (function (LineCapShapeTarget) {
                LineCapShapeTarget[LineCapShapeTarget["shape"] = 1] = "shape";
                LineCapShapeTarget[LineCapShapeTarget["startCap"] = 2] = "startCap";
                LineCapShapeTarget[LineCapShapeTarget["endCap"] = 3] = "endCap";
            })(LineCapShapeTarget = Design.LineCapShapeTarget || (Design.LineCapShapeTarget = {}));
            class LineCapShapeCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                }
                get target() {
                    return this.props.get("target");
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: false,
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    this.enabled = CanvasJS.Design.Environment.selection.count > 0;
                }
                onExecute(e) {
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (element instanceof Design.Shapes.Line) {
                            switch (this.target) {
                                case LineCapShapeTarget.startCap:
                                    element.source.startCapShape = e.shape;
                                    break;
                                case LineCapShapeTarget.endCap:
                                    element.source.endCapShape = e.shape;
                                    break;
                            }
                        }
                    });
                }
            }
            Design.LineCapShapeCommand = LineCapShapeCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let LineScaleType;
            (function (LineScaleType) {
                LineScaleType[LineScaleType["increase"] = 1] = "increase";
                LineScaleType[LineScaleType["decrease"] = 2] = "decrease";
            })(LineScaleType = Design.LineScaleType || (Design.LineScaleType = {}));
            let LineScaleTarget;
            (function (LineScaleTarget) {
                LineScaleTarget[LineScaleTarget["shape"] = 1] = "shape";
                LineScaleTarget[LineScaleTarget["line"] = 2] = "line";
                LineScaleTarget[LineScaleTarget["startCap"] = 3] = "startCap";
                LineScaleTarget[LineScaleTarget["endCap"] = 4] = "endCap";
            })(LineScaleTarget = Design.LineScaleTarget || (Design.LineScaleTarget = {}));
            class LineScaleCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                }
                get scaling() {
                    return this.props.get("scaling");
                }
                getDefaultValuesForProps() {
                    return {
                        id: "line/line-scale",
                        enabled: false,
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    this.enabled = CanvasJS.Design.Environment.selection.count > 0;
                }
                onExecute(e) {
                    CanvasJS.Design.Environment.selection.each((element) => {
                        if (element instanceof Design.Shapes.Line) {
                            let unit = this.scaling == LineScaleType.decrease ? -1 : 1;
                            this.scaleStartCap(element, unit);
                            this.scaleLine(element, unit);
                            this.scaleEndCap(element, unit);
                        }
                    });
                    CanvasJS.Design.Environment.selectionBox.draw();
                }
                scaleShape(element, unit) {
                    let stop = (element.source.lineWeight <= unit
                        || element.source.startCapHeight <= unit
                        || element.source.startCapWidth <= unit
                        || element.source.endCapHeight <= unit
                        || element.source.endCapWidth <= unit)
                        && this.scaling == LineScaleType.decrease;
                    if (!stop) {
                        element.source.state.set({
                            lineWeight: element.source.lineWeight + unit,
                            startCapHeight: element.source.startCapHeight + unit,
                            startCapWidth: element.source.startCapWidth + unit,
                            endCapHeight: element.source.endCapHeight + unit,
                            endCapWidth: element.source.endCapWidth + unit
                        });
                    }
                }
                scaleLine(element, unit) {
                    if (this.scaling == LineScaleType.decrease && (element.source.lineWeight <= 1)) {
                        element.source.state.set({
                            lineWeight: 1
                        });
                    }
                    else {
                        element.source.state.set({
                            lineWeight: element.source.lineWeight + unit
                        });
                    }
                }
                scaleStartCap(element, unit) {
                    let stop = (element.source.startCapHeight <= unit
                        || element.source.startCapWidth <= unit)
                        && this.scaling == LineScaleType.decrease;
                    if (!stop) {
                        element.source.state.set({
                            startCapHeight: element.source.startCapHeight + unit,
                            startCapWidth: element.source.startCapWidth + unit
                        });
                    }
                }
                scaleEndCap(element, unit) {
                    let stop = (element.source.endCapHeight <= unit
                        || element.source.endCapWidth <= unit)
                        && this.scaling == LineScaleType.decrease;
                    if (!stop) {
                        element.source.state.set({
                            endCapHeight: element.source.endCapHeight + unit,
                            endCapWidth: element.source.endCapWidth + unit
                        });
                    }
                }
            }
            Design.LineScaleCommand = LineScaleCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class RotateShapeCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "shape/rotate",
                        tooltip: "Rotate the selected shapes.",
                        label: "Rotate Shape",
                        enabled: false,
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    this.enabled = CanvasJS.Design.Environment.selection.count > 0;
                }
                onExecute(e) {
                    CanvasJS.Design.Environment
                        .selection
                        .each((element) => {
                        if (element instanceof Design.Shapes.Triangle) {
                            if (e == 0) {
                                this.rotateLeft(element);
                            }
                            else {
                                this.rotateRight(element);
                            }
                        }
                    });
                }
                rotateLeft(triangle) {
                    let rotation = triangle.source.rotation;
                    if (triangle.source.rotation < 1) {
                        rotation = 3;
                    }
                    else {
                        rotation -= 1;
                    }
                    triangle.source.rotation = rotation;
                }
                rotateRight(triangle) {
                    let rotation = triangle.source.rotation;
                    if (triangle.source.rotation > 2) {
                        rotation = 0;
                    }
                    else {
                        rotation += 1;
                    }
                    triangle.source.rotation = rotation;
                }
            }
            Design.RotateShapeCommand = RotateShapeCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class TabIndexCommand extends Jade.Command {
                get document() {
                    return CanvasJS.Design.Environment.document.source;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "form-field/tab-indexes",
                        label: "Set Tab Indexes",
                        icon: "rubber_stamp.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    let models = new Jade.Collection();
                    CanvasJS.Design.Environment.selection.each((item) => {
                        if (item.source instanceof PDJS.Canvas.Core.ElementModel) {
                            models.add(item.source);
                        }
                    });
                    this.enabled = Jade.InterfaceGuard.anyImplement(models.toArray(), Canvas.Core.IIndexableGuard);
                }
                onExecute(e) {
                    if (this.document.tabIndexes.count > 0) {
                        this.continuePreviousOrderMessage();
                    }
                    else {
                        this.startNewTabOrder();
                    }
                }
                continuePreviousOrderMessage() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNoCancel,
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        title: "Set Tab Indexes",
                        message: `A previous tab order has been detected. Do you want to add to the existing tab order?`,
                        select: (e) => {
                            e.close();
                            switch (e.name) {
                                case Jade.UI.Dialogs.MessageDialogButton.yes:
                                    this.addToExistingTabOrder();
                                    break;
                                case Jade.UI.Dialogs.MessageDialogButton.no:
                                    this.startNewTabOrder();
                                    break;
                            }
                        }
                    });
                }
                addToExistingTabOrder() {
                    CanvasJS.Design.Environment.selection.each((element, index) => {
                        if (Jade.InterfaceGuard.is(element.source, Canvas.Core.IIndexableGuard)) {
                            if (this.document.tabIndexes.contains(element.ID)) {
                                this.document.tabIndexes.remove(element.ID);
                            }
                            this.document.tabIndexes.add(element.ID);
                        }
                    });
                    this.updateTabIndexLabels();
                }
                startNewTabOrder() {
                    this.document.tabIndexes.clear();
                    CanvasJS.Design.Environment.selection.each((element, index) => {
                        if (Jade.InterfaceGuard.is(element.source, Canvas.Core.IIndexableGuard)) {
                            this.document.tabIndexes.add(element.ID);
                        }
                    });
                    this.updateTabIndexLabels();
                }
                updateTabIndexLabels() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/canvas/standard": {}
                    }, {
                        force: true,
                        overwrite: false
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .execute("pdjs/canvas/standard:form-field/tab-index-toggle", {
                        preventToggle: true
                    });
                }
            }
            Design.TabIndexCommand = TabIndexCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class TabIndexToggleCommand extends Jade.Command {
                get tabOrderVisible() {
                    return this.state.get("tabOrderVisible", false);
                }
                set tabOrderVisible(value) {
                    this.state.set("tabOrderVisible", value);
                }
                get document() {
                    return CanvasJS.Design.Environment.document;
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.document.source.tabIndexes.count > 0;
                    this.updateLabelAndIcon();
                }
                onExecute(e) {
                    if (e == null || e.preventToggle == false) {
                        this.tabOrderVisible = !this.tabOrderVisible;
                    }
                    this.updateLabelAndIcon();
                    this.document.controls.each((element) => {
                        if (Jade.InterfaceGuard.is(element.source, Canvas.Core.IIndexableGuard)) {
                            let indexable = element.source;
                            let index = indexable.tabIndex;
                            if (this.tabOrderVisible && index != -1) {
                                this.addTabIndexMarker(element, index);
                            }
                            else {
                                this.removeTabIndexMarker(element);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "form-field/tab-index-toggle",
                        label: "Show Tab Order",
                        icon: "tags.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdjs"
                    };
                }
                addTabIndexMarker(element, index) {
                    let label = element.node.find("[role=tab-index]");
                    if (label.length == 0) {
                        element.node.children(":first").append(`<div role="tab-index">${index + 1}</div>`);
                    }
                    else {
                        label.text(index + 1);
                    }
                }
                removeTabIndexMarker(element) {
                    element.node.find("[role=tab-index]").remove();
                }
                updateLabelAndIcon() {
                    this.label = this.tabOrderVisible ? "Hide Tab Order" : "Show Tab Order";
                    this.icon = this.tabOrderVisible ? "tags_delete.png" : "tags.png";
                }
            }
            Design.TabIndexToggleCommand = TabIndexToggleCommand;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                let Chart = class Chart extends Design.ElementViewBase {
                    get kendo() {
                        return this.m_kendo;
                    }
                    set kendo(value) {
                        this.m_kendo = value;
                    }
                    get chartNode() {
                        return this.node.find("[role=chart]");
                        ;
                    }
                    get status() {
                        return this.m_status;
                    }
                    template() {
                        return `<div data-controls>
                <div role="chart"></div>
            </div>`;
                    }
                    refresh() {
                        var _a;
                        let chartOptions = null;
                        if (this.kendo != null && this.nodeWidth > 0 && this.nodeHeight > 0) {
                            chartOptions = this.getChartOptions();
                            this.kendo.setOptions(chartOptions);
                            this.kendo.refresh();
                            let style = this.getChartState().style;
                            this.chartNode.css({
                                position: "absolute",
                                top: 0,
                                right: 0,
                                bottom: 0,
                                left: 0,
                                boxSizing: "border-box",
                                padding: 0,
                                margin: 0,
                                borderWidth: style.chartArea.borderWidth,
                                borderStyle: "solid",
                                borderColor: (_a = style.chartArea.borderColor) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-area-border-color)"
                            });
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.isBrowserResizeAware = true;
                        this.m_kendo = this.chartNode.kendoChart(this.getChartOptions()).data("kendoChart");
                        this.m_status = new Canvas.Shared.ElementBar({
                            source: this.source,
                            showRefresh: this.source.informationBarRefresh,
                            visible: this.source.informationBarVisible,
                            onRefresh: () => {
                                this.source.getCachedData();
                            }
                        });
                        this.controls.add(this.m_status);
                    }
                    onBrowserResize() {
                        if (this.anchorRight != null || this.anchorBottom != null) {
                            this.refresh();
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.addActionMenu();
                        this.status.visible = this.source.informationBarVisible;
                        this.status.showRefresh = this.source.informationBarRefresh;
                        this.refresh();
                    }
                    getChartHeight() {
                        return this.nodeHeight - (this.source.informationBarVisible ? 25 : 0);
                    }
                    getChartOptions() {
                        let result = null;
                        let chartState = this.getChartState();
                        result = Canvas.Shared.Charts.ChartOptionsFactory.create(chartState).getOptions();
                        result = $.extend(true, result, {
                            seriesDefaults: {
                                type: this.source.seriesType
                            },
                            chartArea: {
                                height: this.getChartHeight(),
                                width: this.nodeWidth
                            }
                        });
                        return result;
                    }
                    addActionMenu() {
                        if (this.m_menu != null) {
                            this.controls.remove(this.m_menu);
                        }
                        if (!this.source.actionMenuVisible) {
                            return;
                        }
                        this.m_menu = new Canvas.Shared.ElementMenu({
                            position: Canvas.Shared.ElementMenuPosition.topRight,
                            visible: this.source.actionMenuVisible
                        });
                        this.controls.add(this.m_menu);
                    }
                    getChartData(data) {
                        let series = [
                            { name: "Series 1", data: [3, 7, 8, 2] },
                            { name: "Series 2", data: [-2, 4, 7, 5] },
                            { name: "Series 3", data: [2, 12, -5, 9] },
                            { name: "Series 4", data: [8, -4, 15, 7] }
                        ];
                        let categories = [
                            { data: [] },
                            { data: ["Cat 1", "Cat 2", "Cat 3", "Cat 4"] }
                        ];
                        if (data.seriesType == "pie") {
                            series = [{ name: "Series 1", data: [3, 7, 8, 2] }];
                            categories = [{ data: ["Cat 1", "Cat 2", "Cat 3", "Cat 4"] }];
                        }
                        return {
                            data: {
                                series: series,
                                categories: categories
                            }
                        };
                    }
                    getChartState() {
                        let source = this.source.toJSON();
                        return $.extend(true, this.source.toJSON(), this.getChartData(source));
                    }
                };
                Chart = __decorate([
                    Design.elementEditor(Design.ElementEditorLayoutType.Panels, 600, 850)
                ], Chart);
                Charts.Chart = Chart;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartCommandBase extends Jade.Command {
                    constructor(options) {
                        super(options);
                        this.state.set("$feature", null);
                    }
                    get feature() {
                        return this.state.get("$feature");
                    }
                    get isDocumentBased() {
                        return this.feature.getRemoteValue("templateIsDocumentBased", false);
                    }
                    get templateId() {
                        return this.feature.getRemoteValue("templateId");
                    }
                }
                Charts.ChartCommandBase = ChartCommandBase;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartConstraintCommand extends Charts.ChartCommandBase {
                    constructor(options) {
                        super(options);
                        this.state.set("$tree", null);
                        this.state.set("$constraints", null);
                    }
                    get list() {
                        return this.state.get("$tree");
                    }
                    get constraints() {
                        return this.state.get("$constraints");
                    }
                    get selectedConstraint() {
                        return this.list.selectedConstraint;
                    }
                    get selectedNode() {
                        return this.list.selectedNode;
                    }
                    get anchors() {
                        return {
                            documentTypes: this.feature.getRemoteValue("documentTypes", { types: [] }),
                            entityTypes: this.feature.getRemoteValue("entityTypes", { groups: [] })
                        };
                    }
                    setCommandState() {
                        PDJS.Application.instance.contexts.current.commands.setState({
                            "canvas/design/chart/constraints": {
                                $tree: this.list,
                                $constraints: this.constraints,
                                $feature: this.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                }
                Charts.ChartConstraintCommand = ChartConstraintCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartDocumentCommand extends Charts.ChartCommandBase {
                    constructor(options) {
                        super(options);
                        this.state.set("$list", null);
                        this.state.set("$documentTypes", null);
                    }
                    get list() {
                        return this.state.get("$list");
                    }
                    get documentTypes() {
                        return this.state.get("$documentTypes");
                    }
                    get selectedDocumentTypes() {
                        return this.list.grid
                            .getSelections()
                            .toArray();
                    }
                    commit(silent = false) {
                        this.feature.setValue("documentTypes.types", this.documentTypes.toArray(), {
                            silent: silent
                        });
                    }
                    updateGrid(clear = false, selections = []) {
                        this.list.grid.get_dataSource().data([]);
                        this.list.grid.get_dataSource().data(this.documentTypes.toArray());
                        this.list.grid.refresh({
                            clear: clear,
                            selections: selections
                        });
                    }
                    setCommandState() {
                        PDJS.Application.instance.contexts.current.commands.setState({
                            "canvas/design/chart/documents": {
                                $documentTypes: this.documentTypes,
                                $list: this.list,
                                $feature: this.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                }
                Charts.ChartDocumentCommand = ChartDocumentCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartEditorBase extends FeatureBlendJS.Views.MacroEditorBase {
                    onChartAnchorCleared() {
                    }
                    onChartTemplateChanged() {
                    }
                    onCreated() {
                        this.source.controller.onValueChanged(["templateId"], (e) => {
                            this.onChartTemplateChanged();
                            this.onChartAnchorCleared();
                        });
                        this.source.controller.onValueChanged(["entityTypes.groups"], (e) => {
                            if (_.isArray(e.newValue) && e.newValue.length == 0) {
                                this.onChartAnchorCleared();
                            }
                        });
                    }
                    setCommandState(state, options) {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState(state, options);
                    }
                }
                Charts.ChartEditorBase = ChartEditorBase;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartFieldCommand extends Charts.ChartCommandBase {
                    constructor(options) {
                        super(options);
                        this.state.set("$list", null);
                        this.state.set("$feature", null);
                        this.state.set("fieldType", null);
                        this.state.set("sourceValue", null);
                    }
                    get list() {
                        return this.state.get("$list");
                    }
                    get fields() {
                        return this.list.fields;
                    }
                    get fieldType() {
                        return this.getFieldType();
                    }
                    get sourceValue() {
                        return this.state.get("sourceValue");
                    }
                    get selectedFields() {
                        let result = [];
                        this.list.grid.getSelections()
                            .toArray()
                            .forEach(item => {
                            let found = this.fields.getById(item.id);
                            if (found) {
                                result.push(found);
                            }
                        });
                        return result;
                    }
                    get anchors() {
                        return {
                            documentTypes: this.feature.getRemoteValue("documentTypes", { types: [] }),
                            entityTypes: this.feature.getRemoteValue("entityTypes", { groups: [] })
                        };
                    }
                    commit() {
                        this.feature.setValue(this.sourceValue, this.fields.toArray());
                    }
                    updateGrid(clear = false, selections = []) {
                        this.list.grid.get_dataSource().data([]);
                        this.list.grid.get_dataSource().data(this.fields.toArray());
                        this.list.grid.refresh({
                            clear: clear,
                            selections: selections
                        });
                    }
                    getFieldType() {
                        let result;
                        switch (this.sourceValue) {
                            case "valueFields":
                                result = "ValueField";
                                break;
                            case "legendFields":
                                result = "LegendField";
                                break;
                            case "categoryFields":
                                result = "CategoryField";
                                break;
                        }
                        return result;
                    }
                }
                Charts.ChartFieldCommand = ChartFieldCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartFilterCommand extends Charts.ChartCommandBase {
                    constructor(options) {
                        super(options);
                    }
                    get constraints() {
                        return this.feature.getRemoteValue("constraints");
                    }
                }
                Charts.ChartFilterCommand = ChartFilterCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ChartUtilities {
                    static formatFieldName(data) {
                        let result = "";
                        let hasFunction = false;
                        let hasScalarFunction = false;
                        let hasAggregateFunction = false;
                        hasScalarFunction =
                            data.scalarFunctionName !== undefined &&
                                data.scalarFunctionName !== null;
                        hasAggregateFunction =
                            data.aggregateFunctionName !== undefined &&
                                data.aggregateFunctionName !== null;
                        hasFunction = hasScalarFunction || hasAggregateFunction;
                        if (data.columnName !== undefined && data.columnName !== null) {
                            result = data.columnName;
                            if (hasFunction) {
                                result = `<span style="color:var(--visiv-theme-base-1-text-color);">${result}</span>`;
                            }
                            if (hasScalarFunction) {
                                result = `<span style="color:var(--visiv-system-blue);">${data.scalarFunctionName} of ${result} </span>`;
                            }
                            if (hasAggregateFunction) {
                                result = `<span style="color:var(--visiv-system-red);">${data.aggregateFunctionName.toUpperCase()} (${result})</span>`;
                            }
                        }
                        else {
                            result = "#error#";
                        }
                        return result;
                    }
                    static getQuerySettings(feature) {
                        return {
                            anchor: {
                                entityTypes: feature.getRemoteValue("entityTypes", {
                                    groups: []
                                }),
                                documentTypes: feature.getRemoteValue("documentTypes", {
                                    types: []
                                }),
                            },
                            templateId: feature.getRemoteValue("templateId"),
                            templateIsDocumentBased: feature.getRemoteValue("templateIsDocumentBased")
                        };
                    }
                }
                Charts.ChartUtilities = ChartUtilities;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorSelectionGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get searchTerm() {
                        return this.state.get("searchTerm");
                    }
                    set searchTerm(value) {
                        this.state.set("searchTerm", value);
                        this.grid.refresh();
                    }
                    get selections() {
                        return this.grid.getSelections().toArray();
                    }
                    get dblClickCallback() {
                        return this.state.get("dblClick", () => { });
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-field-selection-grid"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.node,
                            selectionMode: "multiple",
                            pk: "id",
                            sortable: {
                                mode: "multiple",
                                allowUnsort: true
                            },
                            selection: {
                                mapping: (e) => {
                                    return e.toJSON();
                                }
                            },
                            footer: {
                                visible: false
                            },
                            dataSource: {
                                schema: {
                                    data: "paths",
                                    total: "totalCount"
                                },
                                transport: {
                                    read: {
                                        url: Jade.Path.resolve("~/query/findanchor")
                                    },
                                    parameterMap: (data) => {
                                        return {
                                            request: JSON.stringify({
                                                keywords: this.searchTerm,
                                                orders: this.getGridSortOrder(data.sort),
                                                pageIndex: data.page ? data.page - 1 : 0,
                                                pageSize: data.pageSize
                                            })
                                        };
                                    }
                                },
                                sort: {
                                    field: "target",
                                    dir: "asc"
                                }
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Target",
                                    field: "name",
                                    width: 150,
                                    template: (e) => {
                                        return e.types[0].name;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Path",
                                    field: "path",
                                    width: 300
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ],
                            dblclick: () => {
                                this.dblClickCallback();
                            }
                        });
                    }
                    getGridSortOrder(sorts) {
                        let result = [];
                        if (_.isArray(sorts)) {
                            sorts.forEach((sort) => {
                                result.push({
                                    ascending: sort.dir === "asc",
                                    column: sort.field === "name" ? 0 : 1
                                });
                            });
                        }
                        return result;
                    }
                }
                Charts.AnchorSelectionGrid = AnchorSelectionGrid;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get okButton() {
                        return this.node.find("button[command=ok]");
                    }
                    get cancelButton() {
                        return this.node.find("button[command=cancel]");
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    template() {
                        return super.template(`
            <div class="-pdjs-canvas-chart-anchor-selection-dialog">
                <div role="content">
                    <div role="row-1">
                        <div role="search-box"></div>
                    </div>
                    <div role="row-2">
                        <div role="grid"></div>
                    </div>
                </div>
                <div role="buttons">
                    <button command="ok" class="-pdjs-dialog-button">OK</button>
                    <button command="cancel" class="-pdjs-dialog-button">Cancel</button>
                </div>
            </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.searchBox_init();
                        this.okButton.on(Jade.BrowserEvent.CLICK, () => {
                            this.closeAndReturn();
                        });
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, () => {
                            this.close();
                        });
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select Anchors",
                            maximized: false,
                            height: 400,
                            width: 550
                        };
                    }
                    grid_init() {
                        this.m_grid = new Charts.AnchorSelectionGrid({
                            insertAt: "div[role=grid]",
                            dblClick: () => {
                                this.closeAndReturn();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    searchBox_init() {
                        this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                            insertAt: "div[role=search-box]",
                            onSearch: (e) => {
                                this.grid.searchTerm = e.term;
                            }
                        });
                        this.controls.add(this.m_searchBox);
                        this.m_searchBox.node.css({
                            position: "relative",
                            width: "200px"
                        });
                    }
                    closeAndReturn() {
                        if (this.grid.selections.length == 0) {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Anchors Selected",
                                message: `No anchors have been selected. Select at least one anchor and try again.`
                            });
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: {
                                selections: this.grid.selections
                            }
                        });
                    }
                    static open(options) {
                        return new AnchorSelectionDialog(options);
                        ;
                    }
                }
                Charts.AnchorSelectionDialog = AnchorSelectionDialog;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorCommand extends Charts.ChartCommandBase {
                    constructor(options) {
                        super(options);
                        this.state.set("$list", null);
                        this.state.set("$anchors", null);
                    }
                    get list() {
                        return this.state.get("$list");
                    }
                    get anchors() {
                        return this.state.get("$anchors");
                    }
                    commit(silent = false) {
                        this.feature.setValue("entityTypes.groups", this.anchors.toJSON(), {
                            silent: silent
                        });
                    }
                    updateGrid(clear = false, selections = []) {
                        this.list.grid.get_dataSource().data([]);
                        this.list.grid.get_dataSource().data(this.anchors.toJSON());
                        this.list.refresh(clear, selections);
                    }
                    setCommandState() {
                        PDJS.Application.instance.contexts.current.commands.setState({
                            "canvas/design/chart/anchors": {
                                $anchors: this.anchors,
                                $list: this.list,
                                $feature: this.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                }
                Charts.AnchorCommand = AnchorCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AddAnchorCommand extends Charts.AnchorCommand {
                    constructor() {
                        super({});
                    }
                    onExecute(e) {
                        Charts.AnchorSelectionDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    this.addAnchors(e.selections);
                                    this.commit();
                                    this.updateGrid(true);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "anchor/add",
                            tooltip: "Add",
                            label: "Add",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    addAnchors(items) {
                        items.forEach(item => {
                            item.types.forEach((type, index) => {
                                let group = this.anchors.item(index);
                                if (!group) {
                                    group = new Charts.AnchorGroup();
                                    this.anchors.add(group);
                                }
                                if (group) {
                                    group.types.add(new Charts.AnchorType(type));
                                }
                            });
                        });
                    }
                }
                Charts.AddAnchorCommand = AddAnchorCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ClearAnchorsCommand extends Charts.AnchorCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.anchors.count > 0;
                    }
                    onExecute(silent = false) {
                        silent ? this.executeClear(silent) : this.confirmClear();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "anchors/clear-all",
                            tooltip: "Clear All",
                            label: "Clear All",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    confirmClear() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Clear Anchors?",
                            message: "Remove all the anchors? This will clear all constraints, value fields, legend fields and category fields.",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.executeClear();
                                }
                            }
                        });
                    }
                    executeClear(silent = false) {
                        this.anchors.clear();
                        this.commit();
                        this.updateGrid(true, []);
                    }
                }
                Charts.ClearAnchorsCommand = ClearAnchorsCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AddConditionCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.constraints.condition.hasConditionsOrFilters
                            && this.selectedConstraint !== null
                            && this.selectedConstraint.role == "condition";
                    }
                    onExecute(e) {
                        let depth = this.selectedConstraint.getDepth();
                        if (depth < 10) {
                            this.list.addCondition({
                                operatorName: "AND"
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtonStyle: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "Condtional Depth Exceeded",
                                message: "No more than ten levels of conditional depth may added.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "condition/add",
                            tooltip: "Add Condition",
                            label: "Add Condition",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.AddConditionCommand = AddConditionCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AddFilterCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selectedConstraint !== null;
                    }
                    onExecute(e) {
                        Charts.FieldSelectionDialog.open({
                            isDocumentBased: this.isDocumentBased,
                            anchors: this.anchors,
                            templateId: this.templateId,
                            filterable: true,
                            select: {
                                ok: (sender, e) => {
                                    let list = [];
                                    e.selections.forEach(item => {
                                        list.push({
                                            columnId: item.id,
                                            columnName: item.name,
                                            isEnabled: true
                                        });
                                    });
                                    this.list.addFilter(list);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "filter/add",
                            tooltip: "Add Filter",
                            label: "Add Filter",
                            icon: "funnel_add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.AddFilterCommand = AddFilterCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ClearConstraintsCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.constraints.condition.conditions.count > 0 ||
                            this.constraints.condition.filters.count > 0;
                    }
                    onExecute(silent = false) {
                        silent ? this.executeClear() : this.confirmClear();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "constraints/clear",
                            tooltip: "Clear All",
                            label: "Clear All",
                            icon: "eraser.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                    confirmClear() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Remove Constraints",
                            message: "Remove all constraints?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.executeClear();
                                }
                            }
                        });
                    }
                    executeClear() {
                        this.list.clear();
                        this.setCommandState();
                    }
                }
                Charts.ClearConstraintsCommand = ClearConstraintsCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DuplicateFilterCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    get filter() {
                        return this.selectedConstraint;
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selectedConstraint !== null &&
                            this.selectedConstraint.role == "filter";
                    }
                    onExecute(e) {
                        this.list.addFilter(_.extend(this.filter.toKendoData(), {
                            id: Jade.Guid.new()
                        }));
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "filter/duplicate",
                            tooltip: "Duplicate",
                            label: "Duplicate",
                            icon: "copy.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.DuplicateFilterCommand = DuplicateFilterCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class EditFilterCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    get filter() {
                        return this.selectedConstraint;
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selectedConstraint !== null &&
                            this.selectedConstraint.role == "filter";
                        this.visible = this.enabled;
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: `Filter | ${this.filter.columnName}`,
                            height: 170,
                            width: 350,
                            args: {
                                layoutType: FeatureBlendJS.Views.FeatureBlendLayoutType.Simple,
                                targetType: "ProspectDirector.Web.UI.Queries.FilterUIO",
                                targetData: this.filter.toJSON(),
                                attributes: {
                                    querySettings: {
                                        valueType: "ProspectDirector.Web.UI.Queries.QuerySettings",
                                        value: Charts.ChartUtilities.getQuerySettings(this.feature)
                                    }
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.selectedConstraint.state.set(e.target);
                                    this.list.applyNodeTemplateToAllAdjacent(this.selectedConstraint.id);
                                    this.constraints.commit();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "filter/edit",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.EditFilterCommand = EditFilterCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class RemoveConstraintCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selectedConstraint !== null &&
                            this.selectedConstraint.parent != null;
                    }
                    onExecute(e) {
                        this.list.remove(this.selectedConstraint.id);
                        this.setCommandState();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "constraint/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.RemoveConstraintCommand = RemoveConstraintCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ToggleConditionCommand extends Charts.ChartConstraintCommand {
                    constructor() {
                        super({});
                    }
                    get condition() {
                        return this.selectedConstraint;
                    }
                    get isCondition() {
                        return this.selectedConstraint !== null &&
                            this.selectedConstraint.role == "condition";
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.constraints.condition.hasConditionsOrFilters
                            && this.isCondition;
                        this.icon = this.isCondition && this.condition.operatorName == "OR" ?
                            "logic_and.png" : "logic_or.png";
                        this.label = this.isCondition && this.condition.operatorName == "OR" ?
                            "Change to ALL" : "Change to ANY";
                        this.tooltip = this.label;
                    }
                    onExecute(e) {
                        this.list.setConditionOperator(this.condition.id, this.condition.operatorName == "AND" ? "OR" : "AND");
                        this.setCommandState();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "condition/toggle-operator",
                            tooltip: "Convert to OR",
                            label: "Convert to OR",
                            icon: "logic_and.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.ToggleConditionCommand = ToggleConditionCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AddDocumentTypeCommand extends Charts.ChartDocumentCommand {
                    constructor() {
                        super({});
                    }
                    onExecute(e) {
                        PDJS.Shared.DocumentTypes.DocumentTypeBrowserDialog.open({
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                            select: {
                                ok: (sender, e) => {
                                    this.addDocumentTypes(e);
                                    this.commit();
                                    this.updateGrid(true, e.map(item => item.id));
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "document-type/add",
                            tooltip: "Add",
                            label: "Add",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    addDocumentTypes(items) {
                        let currentIds = this.documentTypes.toArray().map(item => {
                            return item.id;
                        });
                        items.forEach(item => {
                            let recordExists = currentIds.indexOf(item.id) > -1;
                            if (!recordExists) {
                                this.documentTypes.add(item);
                            }
                        });
                    }
                }
                Charts.AddDocumentTypeCommand = AddDocumentTypeCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ClearDocumentTypesCommand extends Charts.ChartDocumentCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.documentTypes.count > 0;
                    }
                    onExecute(silent = false) {
                        super.onExecute(silent);
                        silent ? this.executeClear(silent) : this.confirmClear();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "document-type/clear-all",
                            tooltip: "Clear All",
                            label: "Clear All",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    confirmClear() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Clear Document Types",
                            message: "Remove all document types?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.executeClear();
                                }
                            }
                        });
                    }
                    executeClear(silent = false) {
                        this.documentTypes.clear();
                        this.commit(silent);
                        this.updateGrid(true, []);
                    }
                }
                Charts.ClearDocumentTypesCommand = ClearDocumentTypesCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DeleteDocumentTypeCommand extends Charts.ChartDocumentCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.documentTypes.count > 0;
                    }
                    onExecute(e) {
                        let ids = this.selectedDocumentTypes.map(item => {
                            return item.id;
                        });
                        let fallback = this.getFallback(ids);
                        let toRemove = this.documentTypes
                            .toArray()
                            .filter(item => {
                            return ids.indexOf(item.id) > -1;
                        });
                        toRemove.forEach(item => {
                            this.documentTypes.remove(item);
                        });
                        if (fallback) {
                            this.updateGrid(true, [fallback.id]);
                        }
                        else {
                            this.updateGrid(true);
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "document-type/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    getFallback(ids) {
                        let fallback = null;
                        let passedFirstSelection = false;
                        this.documentTypes.each((item, index) => {
                            let isItemInSelections = ids.indexOf(item.id) > -1;
                            let isFallback = (!isItemInSelections && !passedFirstSelection)
                                || ((!isItemInSelections && passedFirstSelection && fallback == null));
                            if (isFallback) {
                                fallback = item;
                            }
                            if (isItemInSelections && !passedFirstSelection) {
                                passedFirstSelection = true;
                            }
                        });
                        return fallback;
                    }
                }
                Charts.DeleteDocumentTypeCommand = DeleteDocumentTypeCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AddFieldCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    onExecute(e) {
                        Charts.FieldSelectionDialog.open({
                            isDocumentBased: this.isDocumentBased,
                            anchors: this.anchors,
                            templateId: this.templateId,
                            filterable: false,
                            select: {
                                ok: (sender, e) => {
                                    let selections = e.selections;
                                    let fields = [];
                                    selections.forEach(item => {
                                        let field = this.buildField(item);
                                        fields.push(field);
                                        this.fields.add(field);
                                    });
                                    this.commit();
                                    this.updateGrid(true, fields.map(item => item.id));
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/add",
                            tooltip: "Add",
                            label: "Add",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    buildField(field) {
                        let result = {
                            id: Jade.Guid.new(),
                            columnId: field.id,
                            columnName: field.name,
                            scalarFunctionId: null,
                            scalarFunctionName: null
                        };
                        switch (this.fieldType) {
                            case "ValueField":
                                result.aggregateFunctionId = "count";
                                result.aggregateFunctionName = "Count";
                                break;
                        }
                        return result;
                    }
                }
                Charts.AddFieldCommand = AddFieldCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ClearFieldsCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length > 0;
                    }
                    onExecute(silent = false) {
                        silent ? this.executeClear() : this.confirmClear();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/clear-all",
                            tooltip: "Clear All",
                            label: "Clear All",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    confirmClear() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Remove Fields",
                            message: "Remove all fields?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.executeClear();
                                }
                            }
                        });
                    }
                    executeClear() {
                        this.fields.clear();
                        this.commit();
                        this.updateGrid(true, []);
                    }
                }
                Charts.ClearFieldsCommand = ClearFieldsCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DeleteFieldCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length > 0;
                    }
                    onExecute(e) {
                        let ids = this.selectedFields.map(item => {
                            return item.id;
                        });
                        let fallback = this.getFallback(ids);
                        this.fields.remove(ids);
                        this.commit();
                        if (fallback) {
                            this.updateGrid(true, [fallback.id]);
                        }
                        else {
                            this.updateGrid(true);
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/delete",
                            tooltip: "Delete Field",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    getFallback(ids) {
                        let fallback = null;
                        let passedFirstSelection = false;
                        this.fields.toArray().forEach((item, index) => {
                            let isItemInSelections = ids.indexOf(item.id) > -1;
                            let isFallback = (!isItemInSelections && !passedFirstSelection)
                                || ((!isItemInSelections && passedFirstSelection && fallback == null));
                            if (isFallback) {
                                fallback = this.fields.getAtIndex(index);
                            }
                            if (isItemInSelections && !passedFirstSelection) {
                                passedFirstSelection = true;
                            }
                        });
                        return fallback;
                    }
                }
                Charts.DeleteFieldCommand = DeleteFieldCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DuplicateFieldCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    get selectedField() {
                        return _.first(this.selectedFields);
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length == 1;
                    }
                    onExecute(e) {
                        let newField = _.extend(JSON.parse(JSON.stringify(this.selectedField)), {
                            id: Jade.Guid.new()
                        });
                        this.fields.add(newField);
                        this.commit();
                        this.updateGrid(true, [newField.id]);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/duplicate",
                            tooltip: "Duplicate Field",
                            label: "Duplicate",
                            icon: "copy.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.DuplicateFieldCommand = DuplicateFieldCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class EditFieldCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    get field() {
                        return _.first(this.selectedFields);
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length === 1;
                    }
                    onExecute(e) {
                        this.showEditorDialog(this.fieldType, (sender, e) => {
                            this.fields.update(e);
                            this.updateGrid();
                            this.commit();
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/edit",
                            tooltip: "Edit Field",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    showEditorDialog(fieldType, okCallback) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: `Edit Field | ${this.field.columnName}`,
                            height: 450,
                            width: 500,
                            args: {
                                targetType: `ProspectDirector.Web.UI.Canvas.Elements.Charts.${fieldType}`,
                                targetData: this.field,
                                attributes: {
                                    chart: {
                                        value: this.feature.root.context.toJSON(),
                                        valueType: "ProspectDirector.Web.UI.FeatureSets.TargetContext"
                                    }
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    okCallback(sender, e.target);
                                }
                            }
                        });
                    }
                }
                Charts.EditFieldCommand = EditFieldCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class MoveFieldsDownCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length > 0;
                    }
                    onExecute(e) {
                        let movingIds = this.selectedFields.map((item) => {
                            return item.id;
                        });
                        this.fields.shift(Charts.FieldListShiftType.Down, movingIds);
                        this.updateGrid(true, movingIds);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/move-down",
                            tooltip: "Move Down",
                            label: "Move Down",
                            icon: "arrow2_down_green.png",
                            enabled: false,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.MoveFieldsDownCommand = MoveFieldsDownCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class MoveFieldsUpCommand extends Charts.ChartFieldCommand {
                    constructor() {
                        super({});
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedFields.length > 0;
                    }
                    onExecute(e) {
                        let movingIds = this.selectedFields.map((item) => {
                            return item.id;
                        });
                        this.fields.shift(Charts.FieldListShiftType.Up, movingIds);
                        this.updateGrid(true, movingIds);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "field/move-up",
                            tooltip: "Move Up",
                            label: "Move Up",
                            icon: "arrow2_up_green.png",
                            enabled: false,
                            display: "icon",
                            iconSetId: "pd"
                        };
                    }
                }
                Charts.MoveFieldsUpCommand = MoveFieldsUpCommand;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsCollection extends Jade.Collection {
                    constructor(data) {
                        super([]);
                        data.forEach(item => {
                            this.add(new AnchorGroup(item));
                        });
                    }
                    toJSON() {
                        return this.transform(group => {
                            return group.toJSON();
                        });
                    }
                }
                Charts.AnchorsCollection = AnchorsCollection;
                class AnchorGroup {
                    constructor(options) {
                        this.m_types = new AnchorTypeCollection((options === null || options === void 0 ? void 0 : options.types) || []);
                    }
                    get types() {
                        return this.m_types;
                    }
                    toJSON() {
                        return {
                            types: this.types.toJSON()
                        };
                    }
                }
                Charts.AnchorGroup = AnchorGroup;
                class AnchorTypeCollection extends Jade.Collection {
                    constructor(data) {
                        super([]);
                        data.forEach(item => {
                            this.add(new AnchorType(item));
                        });
                    }
                    add(item) {
                        let result = false;
                        if (!this.exists(item)) {
                            result = super.add(item);
                        }
                        return result;
                    }
                    exists(item) {
                        let result = false;
                        this.each(current => {
                            !result && item.id == current.id ?
                                result = true : null;
                        });
                        return result;
                    }
                    toJSON() {
                        return this.transform((item) => {
                            return item.toJSON();
                        });
                    }
                }
                Charts.AnchorTypeCollection = AnchorTypeCollection;
                class AnchorType {
                    constructor(options) {
                        this.m_id = options.id;
                        this.m_name = options.name;
                    }
                    get id() {
                        return this.m_id;
                    }
                    set id(value) {
                        this.m_id = value;
                    }
                    get name() {
                        return this.m_name;
                    }
                    set name(value) {
                        this.m_name = value;
                    }
                    toJSON() {
                        return {
                            id: this.id,
                            name: this.name
                        };
                    }
                }
                Charts.AnchorType = AnchorType;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsEditor extends Charts.ChartEditorBase {
                    get anchors() {
                        return this.m_anchors;
                    }
                    set anchors(value) {
                        this.m_anchors = value;
                    }
                    get sourceAnchors() {
                        return this.source.getFeatureValue("entityTypes.groups", []);
                    }
                    set sourceAnchors(value) {
                        this.source.setFeatureValue("entityTypes.groups", value);
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-anchors-editor">
                        <div role="text">
                            Select the entity types on which you wish to anchor the chart. All data for the entity types you select will be available for inclusion within your results.
                        </div>
                        <div role="toolbar"></div>
                        <div role="list" data-controls></div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.m_list) {
                            this.m_list.redraw();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.toolbar_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                        this.showMessage();
                    }
                    onCreated() {
                        super.onCreated();
                        let sourceData = this.sourceAnchors.slice(0);
                        this.anchors =
                            new Charts.AnchorsCollection(sourceData);
                    }
                    onChartTemplateChanged() {
                        if (this.m_list) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/anchors:anchors/clear-all", true);
                        }
                        else {
                            this.anchors.clear();
                            this.source.setFeatureValue("entityTypes.groups", [], { silent: true });
                        }
                    }
                    setCommandState() {
                        if (this.m_list == null || this.m_toolbar == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/anchors": {
                                $list: this.m_list,
                                $anchors: this.anchors,
                                $feature: this.source.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                    list_init() {
                        this.m_list = new Charts.AnchorsList({
                            insertAt: "[role=list]",
                            anchors: this.anchors,
                            change: (e) => {
                                this.setCommandState();
                                this.showMessage();
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.AnchorsEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    showMessage() {
                        let message = this.controls.getByType(Charts.AnchorsMessage).first();
                        if (!message) {
                            message = new Charts.AnchorsMessage({
                                clickFieldLink: (e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/anchors:anchor/add");
                                }
                            });
                            this.controls.add(message);
                        }
                        this.anchors.count === 0 ?
                            message.node.show() :
                            message.node.hide();
                    }
                }
                Charts.AnchorsEditor = AnchorsEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.AnchorsEditor", AnchorsEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/anchors");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddAnchorCommand());
                        e.commands.add(new Charts.ClearAnchorsCommand());
                    }
                }
                Charts.AnchorsEditorCommands = AnchorsEditorCommands;
                Jade.CommandGroups.add(AnchorsEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarSegment {
                    onAddItems(e) {
                    }
                    meetsLoadConditions(e) {
                        return true;
                    }
                }
                Controls.ToolbarSegment = ToolbarSegment;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/anchors:anchor/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/anchors:anchors/clear-all"
                        }));
                    }
                }
                Charts.AnchorsEditorToolbar = AnchorsEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.state.unset("anchors");
                        this.m_anchors = options.anchors;
                    }
                    get anchors() {
                        return this.m_anchors;
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get gridNode() {
                        return this.node.children("div[role=grid]");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;">
                        <div role="grid" style="position:absolute;inset:0;"></div>
                    <div>`;
                    }
                    redraw() {
                        if (this.grid) {
                            this.grid.redraw();
                        }
                    }
                    getSelected() {
                        let result = [];
                        this.m_grid
                            .getSelections()
                            .toArray()
                            .forEach(item => {
                            result.push(item);
                        });
                        return result;
                    }
                    refresh(clear = false, selections = []) {
                        this.grid.refresh({
                            clear: clear,
                            selections: selections
                        });
                        if (this.m_completeEventFired) {
                            this.changeCallback(this.grid.getSelections());
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_completeEventFired = true;
                        this.m_grid.get_dataSource().data(this.anchors.toJSON());
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.gridNode,
                            pk: "id",
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            selectionMode: "none",
                            height: "100%",
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "&nbsp;",
                                    field: "icon",
                                    width: 25,
                                    template: (e) => {
                                        let index = this.getDataItemIndex(e);
                                        return `<img src="${Jade.Path.resolve(`~/application/icons/16x16/${index == 0 ? "target" : "arrow_up_blue"}`)}.png"/>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Target",
                                    field: "target",
                                    width: 100,
                                    template: (e) => {
                                        let index = this.getDataItemIndex(e);
                                        return index == 0 ? "Target" : `Ancestor ${index}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Group",
                                    field: "group",
                                    template: (e) => {
                                        return e.types.map(anchor => {
                                            return anchor.name;
                                        }).join("<br/>");
                                    }
                                }),
                            ],
                            messaging: {
                                noRecordsMessage: "No anchors have been added."
                            },
                            change: (e) => {
                                if (this.m_completeEventFired) {
                                    this.changeCallback(e.selections);
                                }
                            }
                        });
                    }
                    getDataItemIndex(dataItem) {
                        return this.grid.get_dataSource().get_instance().indexOf(dataItem);
                    }
                }
                Charts.AnchorsList = AnchorsList;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class Message extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-input-back-color)");
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "var(--visiv-theme-input-border-color)");
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth", 0);
                    }
                    get fill() {
                        return this.state.get("fill", false);
                    }
                    get fontSize() {
                        return this.state.get("fontSize", "13px");
                    }
                    get message() {
                        return this.state.get("message", "");
                    }
                    set message(value) {
                        this.state.set("message", value);
                    }
                    get messageNode() {
                        return this.node.find("div[role=message]");
                    }
                    get textColor() {
                        return this.state.get("textColor", "var(--visiv-theme-input-text-color)");
                    }
                    template() {
                        return `
                <div class="-pdjs-shared-ui-control-message">
	                <div role="message" data-controls>
				        ${this.message}
	                </div>
                </div>
            `;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.messageNode.html(this.message);
                        this.node.css({
                            backgroundColor: `${this.backgroundColor}`,
                            borderColor: `${this.borderColor}`,
                            borderWidth: `${this.borderWidth}px`
                        });
                        this.messageNode.css({
                            fontSize: `${this.fontSize}`,
                            color: `${this.textColor}`
                        });
                        if (this.fill) {
                            this.node.css({
                                position: "absolute",
                                inset: 0
                            });
                        }
                    }
                }
                Controls.Message = Message;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsMessage extends PDJS.Shared.UI.Controls.Message {
                    constructor(options) {
                        super(options || {});
                    }
                    get clickFieldLinkCallback() {
                        return this.state.get("clickFieldLink", () => { });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.message_init();
                        this.node.addClass("-pdjs-canavas-design-charts-anchors-message");
                    }
                    message_init() {
                        if (Jade.String.isNullOrWhiteSpace(this.message)) {
                            this.message = `No anchors have been added.<br/>Add an <a href="#" role="anchor">anchor</a>.`;
                        }
                        this.messageNode.on(Jade.BrowserEvent.CLICK, "a[role]", (e) => {
                            this.clickFieldLinkCallback({
                                type: $(e.target).attr("role")
                            });
                            return false;
                        });
                    }
                }
                Charts.AnchorsMessage = AnchorsMessage;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class CategoriesEditor extends Charts.ChartEditorBase {
                    get fields() {
                        return this.m_fields;
                    }
                    get list() {
                        return this.m_list;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-categories-editor">
                    <div role="text">
                        Category fields control how data will be grouped in your chart and which values will be shown along the category axis.
                    </div>
                    <div role="toolbar"></div>
                    <div role="list" data-controls></div>
                </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.toolbar_init();
                        this.showMessage();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    onChartAnchorCleared() {
                        super.onChartAnchorCleared();
                        if (this.list) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/categories:field/clear-all", true);
                        }
                        else {
                            this.source.setFeatureValue("categoryFields", []);
                        }
                    }
                    focus() {
                        if (this.list) {
                            this.list.redraw();
                        }
                    }
                    list_init() {
                        this.m_fields = new Charts.FieldListCollection({
                            data: this.source.getFeatureValue("categoryFields")
                        });
                        this.m_list = new Charts.FieldList({
                            insertAt: "div[role=list]",
                            fields: this.fields,
                            change: () => {
                                this.setCommandState();
                                this.showMessage();
                                this.source.setFeatureValue("categoryFields", this.fields.toJSON());
                            },
                            dblClick: () => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("canvas/design/chart/categories:field/edit");
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.CategoriesEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    setCommandState() {
                        if (this.list == null || this.list.grid == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/categories": {
                                $list: this.list,
                                $feature: this.source.feature,
                                sourceValue: "categoryFields"
                            }
                        }, { force: true, overwrite: true });
                    }
                    showMessage() {
                        let message = this.controls.getByType(Charts.FieldMessage).first();
                        if (!message) {
                            message = new Charts.FieldMessage({
                                clickFieldLink: (e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/categories:field/add");
                                }
                            });
                            this.controls.add(message);
                        }
                        this.fields.list.length === 0 ?
                            message.node.show() :
                            message.node.hide();
                    }
                }
                Charts.CategoriesEditor = CategoriesEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.CategoriesEditor", CategoriesEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class CategoriesEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/categories");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddFieldCommand());
                        e.commands.add(new Charts.DeleteFieldCommand());
                        e.commands.add(new Charts.DuplicateFieldCommand());
                        e.commands.add(new Charts.EditFieldCommand());
                        e.commands.add(new Charts.ClearFieldsCommand());
                        e.commands.add(new Charts.MoveFieldsUpCommand());
                        e.commands.add(new Charts.MoveFieldsDownCommand());
                    }
                }
                Charts.CategoriesEditorCommands = CategoriesEditorCommands;
                Jade.CommandGroups.add(CategoriesEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class CategoriesEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/duplicate"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/clear-all"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/move-up"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/categories:field/move-down"
                        }));
                    }
                }
                Charts.CategoriesEditorToolbar = CategoriesEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ConstraintsEditor extends Charts.ChartEditorBase {
                    template() {
                        return `<div class="-pdjs-canvas-chart-filters-editor">
                        <div role="text">
                            Constraints allow you to retrieve the appropriate records for populating this chart via the addition of conditions and filters.
                        </div>
                        <div role="toolbar"></div>
                        <div role="tree"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.tree_init();
                        this.toolbar_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    onCreated() {
                        super.onCreated();
                        this.m_constraints = new PDJS.Core.Views.Constraints({
                            condition: this.source.getFeatureValue("constraints"),
                            commit: (value) => {
                                this.source.setFeatureValue("constraints", null);
                                this.source.setFeatureValue("constraints", value);
                            }
                        });
                    }
                    onChartAnchorCleared() {
                        super.onChartAnchorCleared();
                        if (this.m_tree) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/constraints:constraints/clear", true);
                        }
                        else {
                            this.m_constraints.clear();
                            this.source.setFeatureValue("constraints", this.m_constraints.toJSON());
                        }
                    }
                    tree_init() {
                        this.m_tree = new PDJS.Shared.View.ConstraintsTree({
                            insertAt: "[role=tree]",
                            constraints: this.m_constraints,
                            contextMenu: "PDJS.Canvas.Design.Charts.ConstraintsEditorContextMenu",
                            onChange: (e) => {
                                this.setCommandState();
                            },
                            onConstraintDblClick: (e) => {
                                switch (e.constraint.role) {
                                    case "condition":
                                        break;
                                    case "filter":
                                        PDJS.Application
                                            .instance
                                            .contexts
                                            .current
                                            .commands
                                            .execute("canvas/design/chart/constraints:filter/edit");
                                        break;
                                }
                            },
                            onClickConstraintLink: (e) => {
                                if (e.type == "condition") {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/constraints:condition/add");
                                }
                                if (e.type == "filter") {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/constraints:filter/add");
                                }
                            }
                        });
                        this.controls.add(this.m_tree);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.ConstraintsEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    setCommandState() {
                        if (this.m_tree == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/constraints": {
                                $tree: this.m_tree,
                                $constraints: this.m_constraints,
                                $feature: this.source.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                }
                Charts.ConstraintsEditor = ConstraintsEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.FiltersEditor", ConstraintsEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ConstraintsEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/constraints");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddConditionCommand());
                        e.commands.add(new Charts.AddFilterCommand());
                        e.commands.add(new Charts.EditFilterCommand());
                        e.commands.add(new Charts.DuplicateFilterCommand());
                        e.commands.add(new Charts.RemoveConstraintCommand());
                        e.commands.add(new Charts.ToggleConditionCommand());
                        e.commands.add(new Charts.ClearConstraintsCommand());
                    }
                }
                Charts.ConstraintsEditorCommands = ConstraintsEditorCommands;
                Jade.CommandGroups.add(ConstraintsEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ConstraintsEditorContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:condition/add"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:condition/toggle-operator"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:filter/add"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:filter/edit"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:filter/duplicate"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:constraint/delete"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "canvas/design/chart/constraints:constraints/clear"
                        }));
                    }
                }
                Charts.ConstraintsEditorContextMenu = ConstraintsEditorContextMenu;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ConstraintsEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:condition/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:condition/toggle-operator"
                        }));
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:filter/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:filter/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:filter/duplicate"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:constraint/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/constraints:constraints/clear"
                        }));
                    }
                }
                Charts.ConstraintsEditorToolbar = ConstraintsEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsCollection extends Jade.Collection {
                }
                Charts.DocumentsCollection = DocumentsCollection;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsEditor extends Charts.ChartEditorBase {
                    get documentTypes() {
                        return this.m_documentTypes;
                    }
                    set documentTypes(value) {
                        this.m_documentTypes = value;
                    }
                    get sourceDocumentTypes() {
                        return this.source.getFeatureValue("documentTypes.types", []);
                    }
                    set sourceDocumentTypes(value) {
                        this.source.getFeatureValue("documentTypes.types", value);
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-documents-editor">
                        <div role="text">
                            Select the document types you are interested in visualizing. All data for the document types you select will be available for inclusion within your results.
                        </div>
                        <div role="toolbar"></div>
                        <div role="list" data-controls></div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.m_list) {
                            this.m_list.redraw();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.toolbar_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                        this.showMessage();
                    }
                    onCreated() {
                        super.onCreated();
                        let sourceData = this.sourceDocumentTypes.slice(0);
                        this.documentTypes =
                            new Charts.DocumentsCollection(sourceData);
                    }
                    onChartTemplateChanged() {
                        if (this.m_list) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/documents:document-type/clear-all", true);
                        }
                        else {
                            this.documentTypes.clear();
                            this.sourceDocumentTypes = [];
                        }
                    }
                    setCommandState() {
                        if (this.m_list == null || this.m_toolbar == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/documents": {
                                $list: this.m_list,
                                $documentTypes: this.documentTypes,
                                $feature: this.source.feature
                            }
                        }, { force: true, overwrite: true });
                    }
                    list_init() {
                        this.m_list = new Charts.DocumentsList({
                            insertAt: "[role=list]",
                            documentTypes: this.documentTypes,
                            change: (e) => {
                                this.setCommandState();
                                this.showMessage();
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.DocumentsEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    showMessage() {
                        let message = this.controls.getByType(Charts.DocumentsMessage).first();
                        if (!message) {
                            message = new Charts.DocumentsMessage({
                                clickFieldLink: (e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/documents:document-type/add");
                                }
                            });
                            this.controls.add(message);
                        }
                        this.documentTypes.count === 0 ?
                            message.node.show() :
                            message.node.hide();
                    }
                }
                Charts.DocumentsEditor = DocumentsEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.DocumentsEditor", DocumentsEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/documents");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddDocumentTypeCommand());
                        e.commands.add(new Charts.DeleteDocumentTypeCommand());
                        e.commands.add(new Charts.ClearDocumentTypesCommand());
                    }
                }
                Charts.DocumentsEditorCommands = DocumentsEditorCommands;
                Jade.CommandGroups.add(DocumentsEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/documents:document-type/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/documents:document-type/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/documents:document-type/clear-all"
                        }));
                    }
                }
                Charts.DocumentsEditorToolbar = DocumentsEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.state.unset("documentTypes");
                        this.m_documentTypes = options.documentTypes;
                    }
                    get documentTypes() {
                        return this.m_documentTypes;
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get gridNode() {
                        return this.node.children("div[role=grid]");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;">
                        <div role="grid" style="position:absolute;inset:0;"></div>
                    <div>`;
                    }
                    redraw() {
                        if (this.grid) {
                            this.grid.redraw();
                        }
                    }
                    getSelected() {
                        let result = [];
                        this.m_grid
                            .getSelections()
                            .toArray()
                            .forEach(item => {
                            result.push(item);
                        });
                        return result;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_completeEventFired = true;
                        this.m_grid.get_dataSource().data(this.documentTypes.toArray());
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.gridNode,
                            pk: "id",
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            selectionMode: "multiple",
                            height: "100%",
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Name",
                                    field: "name",
                                    width: 250
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Category",
                                    field: "category",
                                    width: 250
                                }),
                            ],
                            messaging: {
                                noRecordsMessage: "No document types have been added."
                            },
                            change: (e) => {
                                if (this.m_completeEventFired) {
                                    this.changeCallback(e.selections);
                                }
                            }
                        });
                    }
                }
                Charts.DocumentsList = DocumentsList;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class DocumentsMessage extends PDJS.Shared.UI.Controls.Message {
                    constructor(options) {
                        super(options || {});
                    }
                    get clickFieldLinkCallback() {
                        return this.state.get("clickFieldLink", () => { });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.message_init();
                        this.node.addClass("-pdjs-canavas-design-charts-documents-message");
                    }
                    message_init() {
                        if (Jade.String.isNullOrWhiteSpace(this.message)) {
                            this.message = `No document types have been added.<br/>Add a <a href="#" role="document-type">document type</a>.`;
                        }
                        this.messageNode.on(Jade.BrowserEvent.CLICK, "a[role]", (e) => {
                            this.clickFieldLinkCallback({
                                type: $(e.target).attr("role")
                            });
                            return false;
                        });
                    }
                }
                Charts.DocumentsMessage = DocumentsMessage;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class FoundInEditor extends FeatureBlendJS.Views.MacroEditorBase {
                    get grid() {
                        return this.m_grid;
                    }
                    set grid(value) {
                        this.m_grid = value;
                    }
                    get gridNode() {
                        return this.node.children("div[role=grid]");
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-field-found-in-editor">
                        <div role="text">
                            The list below contains the search groups within which this field may be found. 
                            This list helps you in identifying the source of the data contained within this field.
                        </div>
                        <div role="grid" data-controls></div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.grid) {
                            this.grid.redraw();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.grid = new PD.Web.UI.Controls.Grid({
                            container: this.gridNode,
                            pk: "id",
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            selectionMode: "none",
                            height: "100%",
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "&nbsp;",
                                    field: "icon",
                                    width: 25,
                                    attributes: {
                                        style: "vertical-align:top;"
                                    },
                                    template: (e) => {
                                        return `<img src="${Jade.IconSet.get("pd").resolve("form_blue.png", Jade.IconSetSizeSpecificDirectory.x16)}"/>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Found In",
                                    field: "form",
                                    attributes: {
                                        style: "vertical-align:top;"
                                    }
                                })
                            ],
                            messaging: {
                                noRecordsMessage: "This field is not found within any search groups."
                            },
                            footer: {
                                visible: false
                            }
                        });
                    }
                }
                Charts.FoundInEditor = FoundInEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.FoundInEditor", FoundInEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class LegendEditor extends Charts.ChartEditorBase {
                    get fields() {
                        return this.m_fields;
                    }
                    get list() {
                        return this.m_list;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-legend-editor">
                    <div role="text">
                        Legend fields control which data will be used to create the legend on your chart and may increase the number of chart series.
                    </div>
                    <div role="toolbar"></div>
                    <div role="list" data-controls></div>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.list) {
                            this.list.redraw();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.toolbar_init();
                        this.showMessage();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    onChartAnchorCleared() {
                        super.onChartAnchorCleared();
                        if (this.list) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/legend:field/clear-all", true);
                        }
                        else {
                            this.source.setFeatureValue("legendFields", []);
                        }
                    }
                    setCommandState() {
                        if (this.list == null || this.list.grid == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/legend": {
                                $list: this.list,
                                $feature: this.source.feature,
                                sourceValue: "legendFields"
                            }
                        }, { force: true, overwrite: true });
                    }
                    list_init() {
                        this.m_fields = new Charts.FieldListCollection({
                            data: this.source.getFeatureValue("legendFields")
                        });
                        this.m_list = new Charts.FieldList({
                            insertAt: "div[role=list]",
                            fields: this.fields,
                            change: () => {
                                this.setCommandState();
                                this.showMessage();
                                this.source.setFeatureValue("legendFields", this.fields.toJSON());
                            },
                            dblClick: () => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("canvas/design/chart/legend:field/edit");
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.LegendEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    showMessage() {
                        let message = this.controls.getByType(Charts.FieldMessage).first();
                        if (!message) {
                            message = new Charts.FieldMessage({
                                clickFieldLink: (e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/legend:field/add");
                                }
                            });
                            this.controls.add(message);
                        }
                        this.fields.list.length === 0 ?
                            message.node.show() :
                            message.node.hide();
                    }
                }
                Charts.LegendEditor = LegendEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.LegendEditor", LegendEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class LegendEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/legend");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddFieldCommand());
                        e.commands.add(new Charts.DeleteFieldCommand());
                        e.commands.add(new Charts.DuplicateFieldCommand());
                        e.commands.add(new Charts.EditFieldCommand());
                        e.commands.add(new Charts.ClearFieldsCommand());
                        e.commands.add(new Charts.MoveFieldsUpCommand());
                        e.commands.add(new Charts.MoveFieldsDownCommand());
                    }
                }
                Charts.LegendEditorCommands = LegendEditorCommands;
                Jade.CommandGroups.add(LegendEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class LegendEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/duplicate"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/clear-all"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/move-up"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/legend:field/move-down"
                        }));
                    }
                }
                Charts.LegendEditorToolbar = LegendEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class OverviewEditor extends Charts.ChartEditorBase {
                    get title() {
                        return this.source.getFeatureValue("titleText", "");
                    }
                    set title(value) {
                        this.source.setFeatureValue("titleText", value);
                    }
                    get dataSource() {
                        return this.source.getFeatureValue("templateId");
                    }
                    set dataSource(value) {
                        this.source.setFeatureValue("templateId", value, { postback: true });
                    }
                    get seriesType() {
                        return this.source.getFeatureValue("seriesType");
                    }
                    get stacked() {
                        return this.source.getFeatureValue("stacked");
                    }
                    set stacked(value) {
                        this.source.setFeatureValue("stacked", value);
                    }
                    get dataSourceList() {
                        return this.source.getFeatureValue("templateList");
                    }
                    get seriesTypeList() {
                        return this.source.getFeatureValue("seriesTypeList");
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-overview-editor">
                        <div role="content" data-controls>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.m_title) {
                            this.m_title.focus();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.title_init();
                        this.dataSource_init();
                        this.seriesType_init();
                        this.stacked_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_title.value = this.title;
                        this.m_dataSource.value = this.dataSource;
                        this.m_seriesType.value = this.seriesType;
                        this.m_stacked.value = this.stacked;
                    }
                    title_init() {
                        this.m_title =
                            new PDJS.Shared.UI.Controls.Fields.StringField({
                                label: "Chart Title",
                                maxLength: 250,
                                blur: () => {
                                    this.title = this.m_title.value;
                                }
                            });
                        this.controls.add(this.m_title);
                    }
                    dataSource_init() {
                        this.m_dataSource =
                            new PDJS.Shared.UI.Controls.Fields.SelectField({
                                label: "Data Source",
                                items: this.dataSourceList,
                                tooltip: "Sets what data source will be used to populate the chart.",
                                binding: { label: "name", value: "value" },
                                change: () => {
                                    Jade.UI.Dialogs.MessageDialog.open({
                                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                                        title: "Change the Data Source?",
                                        message: "Change the data source? This will clear all constraints, value fields, legend fields and category fields.",
                                        select: (e) => {
                                            e.close();
                                            e.name === Jade.UI.Dialogs.MessageDialogButton.ok ?
                                                this.dataSource = parseInt(this.m_dataSource.value) :
                                                this.m_dataSource.value = this.dataSource;
                                        }
                                    });
                                }
                            });
                        this.controls.add(this.m_dataSource);
                    }
                    seriesType_init() {
                        this.m_seriesType =
                            new PDJS.Shared.UI.Controls.Fields.TileField({
                                label: "Chart Type",
                                items: this.seriesTypeList,
                                binding: { label: "name", value: "value", image: "image" },
                                change: () => {
                                    this.setSeriesType(this.m_seriesType.value);
                                }
                            });
                        this.controls.add(this.m_seriesType);
                    }
                    stacked_init() {
                        this.m_stacked =
                            new PDJS.Shared.UI.Controls.Fields.SelectField({
                                label: "Stacked",
                                tooltip: "When true, series in the chart will be displayed as stacked.",
                                items: [
                                    { label: "Yes", value: "true" },
                                    { label: "No", value: "false" }
                                ],
                                change: () => {
                                    this.stacked = this.m_stacked.value == "true";
                                }
                            });
                        this.controls.add(this.m_stacked);
                        if (this.seriesType == "pie") {
                            this.m_stacked.node.hide();
                        }
                    }
                    setSeriesType(value) {
                        let postback = (this.seriesType == "pie" && value != "pie") ||
                            (this.seriesType != "pie" && value == "pie");
                        this.source.setFeatureValue("seriesType", value, { postback: postback });
                    }
                }
                Charts.OverviewEditor = OverviewEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.OverviewEditor", OverviewEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ValuesEditor extends Charts.ChartEditorBase {
                    get fields() {
                        return this.m_fields;
                    }
                    get list() {
                        return this.m_list;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-values-editor">
                    <div role="text">
                        Value fields control the data used to create the data points on your chart and which values will be shown along the value axis.
                    </div>
                    <div role="toolbar"></div>
                    <div role="list" data-controls></div>
                </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.toolbar_init();
                        this.showMessage();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    onChartAnchorCleared() {
                        super.onChartAnchorCleared();
                        if (this.list) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("canvas/design/chart/values:field/clear-all", true);
                        }
                        else {
                            this.source.setFeatureValue("valueFields", []);
                        }
                    }
                    focus() {
                        super.focus();
                        if (this.list) {
                            this.list.redraw();
                        }
                    }
                    list_init() {
                        this.m_fields = new Charts.FieldListCollection({
                            data: this.source.getFeatureValue("valueFields")
                        });
                        this.m_list = new Charts.FieldList({
                            insertAt: "div[role=list]",
                            fields: this.fields,
                            change: () => {
                                this.setCommandState();
                                this.showMessage();
                                this.source.setFeatureValue("valueFields", this.fields.toJSON());
                            },
                            dblClick: () => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("canvas/design/chart/values:field/edit");
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=toolbar]",
                            segments: [new Charts.ValuesEditorToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    setCommandState() {
                        if (this.list == null || this.list.grid == null) {
                            return;
                        }
                        super.setCommandState({
                            "canvas/design/chart/values": {
                                $list: this.list,
                                $feature: this.source.feature,
                                sourceValue: "valueFields"
                            }
                        }, { force: true, overwrite: true });
                    }
                    showMessage() {
                        let message = this.controls.getByType(Charts.FieldMessage).first();
                        if (!message) {
                            message = new Charts.FieldMessage({
                                clickFieldLink: (e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .current
                                        .commands
                                        .execute("canvas/design/chart/values:field/add");
                                }
                            });
                            this.controls.add(message);
                        }
                        this.fields.list.length === 0 ?
                            message.node.show() :
                            message.node.hide();
                    }
                }
                Charts.ValuesEditor = ValuesEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Canvas.Design.Charts.ValuesEditor", ValuesEditor);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ValuesEditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("canvas/design/chart/values");
                    }
                    registerCommands(e) {
                        e.commands.add(new Charts.AddFieldCommand());
                        e.commands.add(new Charts.DeleteFieldCommand());
                        e.commands.add(new Charts.DuplicateFieldCommand());
                        e.commands.add(new Charts.EditFieldCommand());
                        e.commands.add(new Charts.ClearFieldsCommand());
                        e.commands.add(new Charts.MoveFieldsUpCommand());
                        e.commands.add(new Charts.MoveFieldsDownCommand());
                    }
                }
                Charts.ValuesEditorCommands = ValuesEditorCommands;
                Jade.CommandGroups.add(ValuesEditorCommands);
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class ValuesEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/add"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/duplicate"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/clear-all"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/move-up"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "canvas/design/chart/values:field/move-down"
                        }));
                    }
                }
                Charts.ValuesEditorToolbar = ValuesEditorToolbar;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class FieldList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get fields() {
                        return this.state.get("fields");
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get gridNode() {
                        return this.node.children("div[role=grid]");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get dblClickCallback() {
                        return this.state.get("dblClick", () => { });
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;">
                        <div role="grid" style="position:absolute;inset:0;"></div>
                    <div>`;
                    }
                    redraw() {
                        if (this.grid) {
                            this.grid.redraw();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_grid.get_dataSource().data(this.fields.toArray());
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.gridNode,
                            pk: "id",
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            selectionMode: "multiple",
                            height: "100%",
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Name",
                                    field: "columnName",
                                    width: 250,
                                    template: (data) => {
                                        return Charts.ChartUtilities.formatFieldName(data);
                                    }
                                })
                            ],
                            messaging: {
                                noRecordsMessage: "No fields have been added."
                            },
                            dblclick: (e) => {
                                this.dblClickCallback(e.selections);
                            },
                            change: (e) => {
                                this.changeCallback(e.selections);
                            }
                        });
                    }
                }
                Charts.FieldList = FieldList;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                let FieldListShiftType;
                (function (FieldListShiftType) {
                    FieldListShiftType[FieldListShiftType["Up"] = 0] = "Up";
                    FieldListShiftType[FieldListShiftType["Down"] = 1] = "Down";
                })(FieldListShiftType = Charts.FieldListShiftType || (Charts.FieldListShiftType = {}));
                class FieldListCollection {
                    constructor(options) {
                        this.m_list = options.data || [];
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get count() {
                        return this.list.length;
                    }
                    add(item) {
                        this.list.push(item);
                    }
                    remove(ids) {
                        this.list = this.list.filter((item, index) => {
                            return ids.indexOf(item.id) == -1;
                        });
                    }
                    clear() {
                        this.list = [];
                    }
                    data() {
                        return this.list.slice(0);
                    }
                    shift(shiftType, movingIds) {
                        let localList = this.list.slice(0);
                        if (shiftType == FieldListShiftType.Down) {
                            localList = localList.reverse();
                        }
                        let movingFields = [];
                        localList.forEach((field, index, array) => {
                            this.executeShift({
                                index: index,
                                field: field,
                                movingFieldIds: movingIds,
                                movingFields: movingFields
                            });
                        });
                        this.list = (shiftType == FieldListShiftType.Down) ?
                            movingFields.reverse() : movingFields;
                    }
                    toArray() {
                        return this.list.slice(0);
                    }
                    toJSON() {
                        return JSON.parse(JSON.stringify(this.list.slice(0)));
                    }
                    getIndex(item) {
                        let result = -1;
                        if (item) {
                            this.list.forEach((current, index) => {
                                result === -1 && current.id === item.id ?
                                    result = index : null;
                            });
                        }
                        return result;
                    }
                    getAtIndex(index) {
                        let result = null;
                        if (this.list.length > index) {
                            result = this.list[index];
                        }
                        return result;
                    }
                    getById(id) {
                        let result = _.first(this.list.filter(item => {
                            return item.id === id;
                        }));
                        return result;
                    }
                    update(item) {
                        let index = this.getIndex(item);
                        if (index > -1) {
                            this.list[index] = item;
                        }
                    }
                    executeShift(e) {
                        let isFirstField = e.index == 0;
                        let lastField = null;
                        let currField = e.field;
                        if (!isFirstField) {
                            lastField = e.movingFields[e.movingFields.length - 1];
                        }
                        let isCurrMoving = e.movingFieldIds.indexOf(currField.id) > -1;
                        let isLastMoved = false;
                        if (lastField) {
                            isLastMoved = e.movingFieldIds.indexOf(lastField.id) > -1;
                        }
                        if (isLastMoved) {
                            e.movingFields.push(currField);
                        }
                        else {
                            if (isCurrMoving) {
                                e.movingFields.pop();
                                e.movingFields.push(currField);
                                if (lastField) {
                                    e.movingFields.push(lastField);
                                }
                            }
                            else {
                                e.movingFields.push(currField);
                            }
                        }
                    }
                }
                Charts.FieldListCollection = FieldListCollection;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class FieldMessage extends PDJS.Shared.UI.Controls.Message {
                    constructor(options) {
                        super(options || {});
                    }
                    get clickFieldLinkCallback() {
                        return this.state.get("clickFieldLink", () => { });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.message_init();
                        this.node.addClass("-pdjs-canavas-design-charts-field-message");
                    }
                    message_init() {
                        if (Jade.String.isNullOrWhiteSpace(this.message)) {
                            this.message = `No fields have been added.<br/>Add a <a href="#" role="field">field</a>.`;
                        }
                        this.messageNode.on(Jade.BrowserEvent.CLICK, "a[role]", (e) => {
                            this.clickFieldLinkCallback({
                                type: $(e.target).attr("role")
                            });
                            return false;
                        });
                    }
                }
                Charts.FieldMessage = FieldMessage;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class FieldSelectionDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get anchors() {
                        return this.state.get("anchors");
                    }
                    get isDocumentBased() {
                        return this.state.get("isDocumentBased", false);
                    }
                    get templateId() {
                        return this.state.get("templateId", false);
                    }
                    get okButton() {
                        return this.node.find("button[command=ok]");
                    }
                    get cancelButton() {
                        return this.node.find("button[command=cancel]");
                    }
                    get searchTerm() {
                        return this.state.get("searchTerm");
                    }
                    set searchTerm(value) {
                        this.state.set("searchTerm", value);
                    }
                    get maxDepth() {
                        return this.state.get("maxDepth", 0);
                    }
                    set maxDepth(value) {
                        this.state.set("maxDepth", value);
                    }
                    get gridLabelNode() {
                        return this.node.find("div[role=grid-label]");
                    }
                    get searchCategoryNode() {
                        return this.node.find("select[role=search-category]");
                    }
                    get searchDepthNode() {
                        return this.node.find("select[role=search-depth]");
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get filterable() {
                        return this.state.get("filterable", false);
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-canvas-chart-field-selection-dialog">
                    <div role="content">
                        <div role="row-1">
                            <div role="row-1-content">
                                <div>Anchor group:</div>
                                <div>Show fields from:</div>
                                <div>
                                    <select role="search-depth" style="width:100%;box-sizing:border-box;"></select>
                                </div>
                                <div>
                                    <select role="search-category" style="width:100%;box-sizing:border-box;"></select>
                                </div>
                            </div>
                        </div>
                        <div role="row-2">
                            <div role="row-2-content">
                                <div role="grid-label">
                                    Fields
                                </div>
                                <div>
                                    <div role="search-box"></div>
                                </div>
                            </div>
                        </div>
                        <div role="row-3">
                            <div role="grid"></div>
                        </div>
                    </div>
                    <div role="buttons">
                        <button command="ok" class="-pdjs-dialog-button">OK</button>
                        <button command="cancel" class="-pdjs-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.searchBox_init();
                        this.dialog_init();
                        this.okButton.on(Jade.BrowserEvent.CLICK, () => {
                            this.closeAndReturn();
                        });
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, () => {
                            this.close();
                        });
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Fields",
                            maximized: false,
                            height: 500,
                            width: 650
                        };
                    }
                    getDepth() {
                        var _a, _b, _c;
                        let result = [];
                        if (((_c = (_b = (_a = this.anchors) === null || _a === void 0 ? void 0 : _a.entityTypes) === null || _b === void 0 ? void 0 : _b.groups) === null || _c === void 0 ? void 0 : _c.length) === 0) {
                            result = this.getDepthWithNoAnchor();
                        }
                        else {
                            result = this.getDepthWithAnchor(this.anchors.entityTypes.groups);
                        }
                        if (this.isDocumentBased) {
                            result.splice(0, 0, {
                                name: "Document",
                                index: 0
                            });
                        }
                        result.forEach((item, index) => {
                            item.name = `${index + 1} - ${item.name}`;
                        });
                        return result;
                    }
                    getDepthWithNoAnchor() {
                        let result = [];
                        for (let index = 0; index <= this.maxDepth; index++) {
                            result.push({
                                name: this.getDepthNames(index),
                                index: this.isDocumentBased ? index + 1 : index
                            });
                        }
                        return result;
                    }
                    getDepthWithAnchor(anchorNodes) {
                        let result = [];
                        anchorNodes.forEach((node, index) => {
                            result.push({
                                name: this.getDepthNames(index, node.types),
                                index: this.isDocumentBased ? index + 1 : index
                            });
                        });
                        return result;
                    }
                    getDepthNames(depth, types) {
                        let result = depth === 0 ?
                            "Target" : `Ancestor ${depth}`;
                        if (types == null) {
                            return result;
                        }
                        let typeNames = "";
                        if (types) {
                            typeNames = types.map((item) => {
                                return item.name;
                            }).join(", ");
                        }
                        if (!Jade.String.isNullOrWhiteSpace(typeNames)) {
                            result = `${typeNames}`;
                        }
                        return result;
                    }
                    grid_init() {
                        this.m_grid = new Charts.FieldSelectionGrid({
                            insertAt: "div[role=grid]",
                            anchors: this.anchors,
                            category: parseInt(this.searchCategoryNode.val()),
                            isReferenceGroup: this.isCategoryGroup("reference"),
                            searchTerm: this.searchTerm,
                            templateId: this.templateId,
                            depth: parseInt(this.searchDepthNode.val()),
                            filterable: false,
                            dblClick: () => {
                                this.closeAndReturn();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    searchBox_init() {
                        this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                            insertAt: "div[role=search-box]",
                            onSearch: (e) => {
                                this.searchTerm = e.term;
                                this.refreshGrid();
                            }
                        });
                        this.controls.add(this.m_searchBox);
                        this.m_searchBox.node.css({
                            position: "relative",
                            width: "200px"
                        });
                    }
                    searchCategories_init() {
                        let items = [];
                        let trgt = $(`<optgroup data-group="target" label="Anchor Group"></optgroup>`);
                        let refs = $(`<optgroup  data-group="reference" label="Anchor Group References"></optgroup>`);
                        items.push({ name: "All", value: 0 });
                        items.push({ name: "Common", value: 1 });
                        items.push({ name: "Single Select Lists", value: 2 });
                        items.push({ name: "Multi-Select Lists", value: 3 });
                        items.forEach(item => {
                            trgt.append(`<option value="${item.value}" data-name="${item.name}">${item.name}</option>`);
                            refs.append(`<option value="${item.value}" data-name="${item.name}">${item.name}</option>`);
                        });
                        trgt.find(":eq(1)").attr("selected", "selected");
                        this.searchCategoryNode.append(trgt);
                        this.searchCategoryNode.append(refs);
                        this.searchCategoryNode.on(Jade.BrowserEvent.CHANGE, () => {
                            this.searchCategories_onChange();
                        });
                        this.updateGridLabel();
                    }
                    searchCategories_onChange() {
                        this.updateGridLabel();
                        this.refreshGrid();
                    }
                    searchDepth_init() {
                        let items = "";
                        this.getDepth().forEach(item => {
                            items += `<option value="${item.index}">${item.name}</option>`;
                        });
                        this.searchDepthNode.append(items);
                        this.searchDepthNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.refreshGrid();
                        });
                    }
                    updateGridLabel() {
                        let label = this.isCategoryGroup("reference") ?
                            "Anchor Group Reference" : "Anchor Group";
                        this.gridLabelNode.html(`Displaying ${label.toLowerCase()} fields:`);
                    }
                    isCategoryGroup(category) {
                        return this.searchCategoryNode.find(":selected").parent().data("group") === category;
                    }
                    refreshGrid() {
                        this.grid.setParameters({
                            anchors: this.anchors,
                            category: parseInt(this.searchCategoryNode.val()),
                            isReferenceGroup: this.isCategoryGroup("reference"),
                            searchTerm: this.searchTerm,
                            templateId: this.templateId,
                            depth: parseInt(this.searchDepthNode.val())
                        });
                    }
                    dialog_init() {
                        PDJS.Ajax.call({
                            url: Jade.Path.resolve("~/Query/FindColumnsDialog"),
                            success: (e) => {
                                this.maxDepth = e.maxDepth;
                                this.searchDepth_init();
                                this.searchCategories_init();
                                this.grid_init();
                            }
                        });
                    }
                    closeAndReturn() {
                        if (this.grid.selections.length == 0) {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Fields Selected",
                                message: `No fields have been selected. Select at least on field and try again.`
                            });
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: {
                                selections: this.grid.selections
                            }
                        });
                    }
                    static open(options) {
                        return new FieldSelectionDialog(options);
                        ;
                    }
                }
                Charts.FieldSelectionDialog = FieldSelectionDialog;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class FieldSelectionGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get anchors() {
                        return this.state.get("anchors");
                    }
                    get isReferenceGroup() {
                        return this.state.get("isReferenceGroup", false);
                    }
                    get searchTerm() {
                        return this.state.get("searchTerm");
                    }
                    get templateId() {
                        return this.state.get("templateId");
                    }
                    get category() {
                        return this.state.get("category");
                    }
                    get filterable() {
                        return this.state.get("filterable", false);
                    }
                    get depth() {
                        return this.state.get("depth");
                    }
                    get selections() {
                        return this.grid.getSelections().toArray();
                    }
                    get dblClickCallback() {
                        return this.state.get("dblClick", () => { });
                    }
                    template() {
                        return `<div class="-pdjs-canvas-chart-field-selection-grid"></div>`;
                    }
                    setParameters(args) {
                        this.state.set(args);
                        this.grid.refresh();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.node,
                            selectionMode: "multiple",
                            pk: "id",
                            sortable: {
                                allowUnsort: true
                            },
                            resizable: true,
                            selection: {
                                mapping: (e) => {
                                    return e.toJSON();
                                }
                            },
                            dataSource: {
                                schema: {
                                    data: "columns",
                                    total: "totalCount"
                                },
                                transport: {
                                    read: {
                                        url: Jade.Path.resolve(`~/query/${this.filterable ? "findfilterablecolumn" : "findcolumn"}`)
                                    },
                                    parameterMap: (data) => {
                                        return {
                                            request: JSON.stringify({
                                                anchor: this.anchors,
                                                category: this.category,
                                                references: this.isReferenceGroup,
                                                condense: true,
                                                depth: this.depth,
                                                exclude: [],
                                                include: [],
                                                names: {},
                                                keywords: this.searchTerm,
                                                orders: this.getGridSortOrder(data.sort),
                                                pageIndex: data.page ? data.page - 1 : 0,
                                                pageSize: data.pageSize,
                                                templateId: this.templateId
                                            })
                                        };
                                    }
                                },
                                sort: {
                                    field: "name",
                                    dir: "asc"
                                }
                            },
                            messaging: {
                                noRecordsMessage: "No fields found."
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Name",
                                    field: "name",
                                    width: 250
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Used By",
                                    field: "usedBy",
                                    width: 150
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Found In",
                                    field: "foundIn",
                                    width: 400
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ],
                            dblclick: () => {
                                this.dblClickCallback();
                            }
                        });
                    }
                    getGridSortOrder(sorts) {
                        sorts = sorts || [];
                        let result = [];
                        let sortColumnId = {
                            name: 0,
                            usedBy: 1,
                            foundIn: 2
                        };
                        sorts.forEach((sort) => {
                            result.push({
                                ascending: sort.dir === "asc",
                                column: sortColumnId[sort.field]
                            });
                        });
                        return result;
                    }
                }
                Charts.FieldSelectionGrid = FieldSelectionGrid;
            })(Charts = Design.Charts || (Design.Charts = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Button = class Button extends Design.ElementViewBase {
                    get buttonIconNode() {
                        return this.buttonNode.find("div:nth-child(2)");
                    }
                    get buttonImageNode() {
                        return this.buttonIconNode.find("img");
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get buttonTextNode() {
                        return this.buttonNode.find("div:nth-child(3)");
                    }
                    get imageUrl() {
                        return Jade.Path.resolve(`~/resources/${this.source.image}`);
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-button">
                        <button>
                            <div></div>
                            <div><img/></div>
                            <div></div>
                            <div></div>
                        </button>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.buttonNode.prop("disabled", !this.source.enabled);
                        this.buttonNode.css({
                            borderRadius: borderRadius
                        });
                        if (this.source.hasImage) {
                            this.buttonImageNode.show();
                            this.buttonImageNode.attr("src", this.imageUrl);
                        }
                        else {
                            this.buttonImageNode.hide();
                        }
                        if (this.source.hasLabel) {
                            this.buttonTextNode.show();
                            this.buttonTextNode.text(this.source.label);
                        }
                        else {
                            this.buttonTextNode.hide();
                        }
                        this.buttonImageNode.css({
                            maxWidth: this.buttonNode.width(),
                            maxHeight: this.buttonNode.height()
                        });
                        this.source.hasImage && this.source.hasLabel ?
                            this.buttonIconNode.css({ paddingRight: "5px" }) :
                            this.buttonIconNode.css({ paddingRight: "0" });
                        this.styleInjector.clear();
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-button button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                };
                Button = __decorate([
                    Jade.UI.Controls.toolingTags("button")
                ], Button);
                Common.Button = Button;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Hyperlink = class Hyperlink extends Design.ElementViewBase {
                    get linkNode() {
                        return this.node.find("A");
                    }
                    template() {
                        return `<div style="display:flex;align-items:center;position:absolute;top:0;left:0;right:0;bottom:0;">
                        <a href='#' style='width:100%;'></a>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .4
                        });
                        this.linkNode.text(this.source.label);
                        this.linkNode.css({
                            color: this.source.foreColor,
                            fontName: this.source.fontName,
                            fontSize: this.source.fontSize,
                            textAlign: this.source.textAlignment
                        });
                        this.node.css({
                            borderColor: "var(--visiv-theme-base-1-border-color)",
                            borderStyle: "dashed",
                            borderWidth: "1px"
                        });
                    }
                };
                Hyperlink = __decorate([
                    Jade.UI.Controls.toolingTags("hyperlink")
                ], Hyperlink);
                Common.Hyperlink = Hyperlink;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Image = class Image extends Design.ElementViewBase {
                    get imageNode() {
                        return this.node.find("img");
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;text-align:center;">
                        <img style="position:absolute;inset:0;"/>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.imageNode.prop("src", this.getImageUrl());
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .5
                        });
                        this.imageNode.css({
                            height: this.source.height,
                            width: this.source.width,
                            borderRadius: borderRadius
                        });
                        this.setArea({
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.setPosition({
                            top: this.source.y,
                            left: this.source.x
                        });
                    }
                    getImageUrl() {
                        let result = null;
                        let imageUrl = this.source.imageUrl;
                        if (imageUrl == null) {
                            result = Jade.Path.resolve("~/application/icons/misc/1024x1024/photo_portrait.png");
                        }
                        else {
                            if (imageUrl.indexOf("/") === 0) {
                                result = Jade.Path.resolve(`~/resources${imageUrl}`);
                            }
                            else if (imageUrl.indexOf("~") === 0) {
                                result = Jade.Path.resolve(imageUrl);
                            }
                            else {
                                result = Jade.Path.resolve(`~/resources/${imageUrl}`);
                            }
                        }
                        return result;
                    }
                };
                Image = __decorate([
                    Jade.UI.Controls.toolingTags("image-button")
                ], Image);
                Common.Image = Image;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Markup = class Markup extends Design.ElementViewBase {
                    get contentNode() {
                        return this.node.find("[role=content]");
                    }
                    template() {
                        return `<div>
                        <div role="content"></div>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let noBorder = this.source.borderStyle == "none";
                        let markup = "";
                        this.contentNode.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            color: "var(--visiv-theme-base-1-text-color)",
                            backgroundColor: this.source.backgroundColor,
                            borderColor: noBorder ? "var(--visiv-theme-base-1-border-color)" : this.source.borderColor,
                            borderStyle: noBorder ? "dashed" : this.source.borderStyle,
                            borderWidth: noBorder ? "1px" : `${this.source.borderWidth}px`,
                            padding: `${this.source.padding}px`,
                            overflow: this.source.scrolling == "none" ? "none" : "auto",
                            overflowX: this.source.scrolling == "horizontal" ? "scroll" : "hidden",
                            overflowY: this.source.scrolling == "vertical" ? "scroll" : "hidden"
                        });
                        if (this.source.markup == "" || this.source.markup == null) {
                            this.contentNode.html(this.noContentMessage());
                        }
                        else {
                            this.contentNode.html(this.source.markup.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ""));
                        }
                        this.setArea({
                            height: this.height,
                            width: this.width
                        });
                        this.setPosition({
                            top: this.y,
                            left: this.x
                        });
                    }
                    noContentMessage() {
                        return `<table style="box-sizing:border-box;height:100%;width:100%;color:var(--visiv-theme-base-1-text-color);">
                        <tr>
                            <td style="text-align:center;">
                                <div style="font-size:16px;font-weight:bold;font-family:arial;margin-bottom:5px;">Markup</div>
                                <div style="font-size:12px;font-family:arial;">Double click to add content.</div>
                            </td>
                        </tr>
                    </table>`;
                    }
                };
                Markup = __decorate([
                    Jade.UI.Controls.toolingTags("text", "style"),
                    Design.elementEditor(Design.ElementEditorLayoutType.Tabbed, 600, 800)
                ], Markup);
                Common.Markup = Markup;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Report = class Report extends Design.ElementViewBase {
                    get reportNode() {
                        return this.node.find("[role=report]");
                    }
                    get status() {
                        return this.m_status;
                    }
                    template() {
                        return `<div data-controls>
                        <div role="report">
                            ${this.getReportSummaryText()}
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_status = new Canvas.Shared.ElementBar({
                            source: this.source,
                            showRefresh: this.source.informationBarRefresh,
                            visible: this.source.informationBarVisible,
                            onRefresh: () => {
                                this.source.getCachedData();
                            }
                        });
                        this.controls.add(this.m_status);
                        this.m_menu = new Canvas.Shared.ElementMenu({
                            position: Canvas.Shared.ElementMenuPosition.topRight,
                            visible: this.source.actionMenuVisible
                        });
                        this.controls.add(this.m_menu);
                        this.onStateChanged();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let noBorder = this.source.borderStyle === "none" ||
                            this.source.borderStyle == null;
                        this.reportNode.html(this.getReportSummaryText());
                        this.reportNode.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: this.source.informationBarVisible ? "25px" : "0",
                            backgroundColor: "var(--visiv-theme-base-1-back-color)",
                            borderColor: noBorder ? "var(--visiv-theme-base-1-border-color)" : this.source.borderColor,
                            borderStyle: noBorder ? "dashed" : this.source.borderStyle,
                            borderWidth: noBorder ? "1px" : this.source.borderWidth
                        });
                        this.setArea({
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.setPosition({
                            top: this.source.y,
                            left: this.source.x
                        });
                        this.m_menu.visible = this.source.actionMenuVisible;
                        this.m_status.visible = this.source.informationBarVisible;
                        this.m_status.showRefresh = this.source.informationBarRefresh;
                    }
                    getReportSummaryText() {
                        let name = this.source.reportName == null ? "No Report Selected" : this.source.reportName;
                        let reportName = `<div style=font-size:16px;font-family:arial;color:${this.source.reportName ? "blue" : "red"};">${name}</div>`;
                        return `<table style="box-sizing:border-box;height:100%;width:100%;color:var(--visiv-theme-base-1-text-color)">
                        <tr>
                            <td style="text-align:center;">
                                <div style="font-size:20px;font-weight:bold;margin-bottom:5px;">${this.source.componentName}</div>
                                ${reportName}
                            </td>
                        </tr>
                    </table>`;
                    }
                };
                Report = __decorate([
                    Jade.UI.Controls.toolingTags("report")
                ], Report);
                Common.Report = Report;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Common;
            (function (Common) {
                let Text = class Text extends Design.ElementViewBase {
                    get contentNode() {
                        return this.node.find("DIV[role=content]");
                    }
                    get containerNode() {
                        return this.node.find("DIV[role=container]");
                    }
                    template() {
                        return `<div class="${Canvas.Shared.CanvasCss.TextElement}">
                        <div role="container">
                            <div role="content"></div>
                        </div>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let noBorder = this.source.borderStyle == "none";
                        if (this.source.text == "" || this.source.text == null) {
                            this.contentNode.html(this.noContentMessage());
                        }
                        else {
                            this.contentNode.html(this.source.text);
                        }
                        this.contentNode.css({
                            width: `100%`,
                            textAlign: this.source.horizontalAlignment
                        });
                        this.containerNode.css({
                            display: "flex",
                            flexWrap: "wrap",
                            alignItems: this.source.verticalAlignment,
                            position: "absolute",
                            boxSizing: "border-box",
                            maxWidth: "border-box",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            borderStyle: noBorder ? "dashed" : this.source.borderStyle,
                            borderWidth: noBorder ? "1px" : `${this.source.borderWidth}`,
                            paddingTop: this.source.paddingTop == 0 ? 0 : `${this.source.paddingTop}px`,
                            paddingRight: this.source.paddingRight == 0 ? 0 : `${this.source.paddingRight}px`,
                            paddingBottom: this.source.paddingBottom == 0 ? 0 : `${this.source.paddingBottom}px`,
                            paddingLeft: this.source.paddingLeft == 0 ? 0 : `${this.source.paddingLeft}px`,
                        });
                        let element = this.containerNode.get(0);
                        element.style.backgroundColor =
                            this.source.backgroundColor == null ? "transparent" : `${this.source.backgroundColor}`;
                        element.style.borderColor = noBorder ? "var(--visiv-theme-base-1-text-color)" :
                            this.source.borderColor == null ? "transparent" : `${this.source.borderColor}`;
                        this.setArea({
                            height: this.height,
                            width: this.width
                        });
                        this.setPosition({
                            top: this.y,
                            left: this.x
                        });
                    }
                    noContentMessage() {
                        return `<table style="box-sizing:border-box;height:100%;width:100%;color:var(--visiv-theme-base-1-text-color);">
                        <tr>
                            <td style="text-align:center;">
                                <div style="font-size:16px;font-weight:bold;font-family:arial;margin-bottom:5px;">Text</div>
                                <div style="font-size:12px;font-family:arial;">Double click to add content.</div>
                            </td>
                        </tr>
                    </table>`;
                    }
                };
                Text = __decorate([
                    Jade.UI.Controls.toolingTags("text", "style")
                ], Text);
                Common.Text = Text;
            })(Common = Design.Common || (Design.Common = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            let ContextMenuType;
            (function (ContextMenuType) {
                ContextMenuType["ColorPalette"] = "color-palette";
                ContextMenuType["View"] = "view";
            })(ContextMenuType = Design.ContextMenuType || (Design.ContextMenuType = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class AlignmentContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "element-alignment" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-left"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-center"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-right"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-top"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-middle"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/align-bottom"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/distribute-horizontally"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/distribute-vertically"
                        }));
                    }
                }
                ContextMenu.AlignmentContextMenuGroup = AlignmentContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class ColorPaletteContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: Design.ContextMenuType.ColorPalette });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItemHeader({
                            label: "Standard Colors"
                        }));
                        this.items.add(new PDJS.Canvas.Design.ContextMenu.ColorPaletteMenuItem({
                            commandId: "canvas/standard:element/background-color",
                            colors: PDJS.Shared.Colors.ColorPalettes.standardColors,
                            closeOnClick: true
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:element/custom-color",
                            value: Design.ICustomColorCommandTarget.backgroundColor
                        }));
                    }
                }
                ContextMenu.ColorPaletteContextMenuGroup = ColorPaletteContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class ElementContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "element" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/group"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/ungroup"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/send-back"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/bring-forward"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/clipboard:clipboard/copy"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/clipboard:clipboard/cut"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/clipboard:clipboard/duplicate"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:selection/delete"
                        }));
                    }
                }
                ContextMenu.ElementContextMenuGroup = ElementContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class LineEndCapShapeMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "end-cap-shape" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/end/shape",
                            label: "None",
                            value: { shape: PDJS.Canvas.Core.Shapes.LineCapShape.none }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/end/shape",
                            label: "Circle",
                            icon: "shape_circle.png",
                            value: { shape: PDJS.Canvas.Core.Shapes.LineCapShape.circle }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/end/shape",
                            label: "Square",
                            icon: "shape_square.png",
                            value: { shape: PDJS.Canvas.Core.Shapes.LineCapShape.square }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/end/shape",
                            label: "Triangle",
                            icon: "shape_triangle_2.png",
                            value: { shape: PDJS.Canvas.Core.Shapes.LineCapShape.triangle }
                        }));
                    }
                }
                ContextMenu.LineEndCapShapeMenuGroup = LineEndCapShapeMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class LineStartCapShapeMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "start-cap-shape" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/start/shape",
                            label: "None",
                            value: { shape: Canvas.Core.Shapes.LineCapShape.none }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/start/shape",
                            label: "Circle",
                            icon: "shape_circle.png",
                            value: { shape: Canvas.Core.Shapes.LineCapShape.circle }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/start/shape",
                            label: "Square",
                            icon: "shape_square.png",
                            value: { shape: Canvas.Core.Shapes.LineCapShape.square }
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:line/start/shape",
                            label: "Triangle",
                            icon: "shape_triangle_2.png",
                            value: { shape: Canvas.Core.Shapes.LineCapShape.triangle }
                        }));
                    }
                }
                ContextMenu.LineStartCapShapeMenuGroup = LineStartCapShapeMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class ShapeBorderContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "shape-border" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItemHeader({
                            label: "Standard Colors"
                        }));
                        this.items.add(new PDJS.Canvas.Design.ContextMenu.ColorPaletteMenuItem({
                            commandId: "canvas/standard:element/border-color",
                            colors: PDJS.Shared.Colors.ColorPalettes.standardColors,
                            closeOnClick: true
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:element/custom-color",
                            value: Design.ICustomColorCommandTarget.borderColor
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItemSubMenu({
                            label: "Border Style",
                            menu: ["border-style"]
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemSubMenu({
                            label: "Border Weight",
                            menu: ["border-weight"]
                        }));
                    }
                }
                ContextMenu.ShapeBorderContextMenuGroup = ShapeBorderContextMenuGroup;
                class BorderStyleContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "border-style" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-style",
                            label: "None",
                            value: "none"
                        }));
                        this.items.add(new Design.BorderStyleContextMenuItem({
                            commandId: "canvas/standard:element/border-style",
                            value: "solid"
                        }));
                        this.items.add(new Design.BorderStyleContextMenuItem({
                            commandId: "canvas/standard:element/border-style",
                            value: "dotted"
                        }));
                        this.items.add(new Design.BorderStyleContextMenuItem({
                            commandId: "canvas/standard:element/border-style",
                            value: "dashed"
                        }));
                        this.items.add(new Design.BorderStyleContextMenuItem({
                            commandId: "canvas/standard:element/border-style",
                            value: "double"
                        }));
                    }
                }
                ContextMenu.BorderStyleContextMenuGroup = BorderStyleContextMenuGroup;
                class BorderWeightContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "border-weight" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-width",
                            label: "1px",
                            value: 1
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-width",
                            label: "2px",
                            value: 2
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-width",
                            label: "3px",
                            value: 3
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-width",
                            label: "4px",
                            value: 4
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "canvas/standard:element/border-width",
                            label: "5px",
                            value: 5
                        }));
                    }
                }
                ContextMenu.BorderWeightContextMenuGroup = BorderWeightContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class TabIndexContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "tab-index" });
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            label: "In Order Selected",
                            commandId: "pdjs/canvas/standard:form-field/tab-indexes"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            label: "In Rows",
                            commandId: "pdjs/canvas/standard:form-field/auto-tab-indexes",
                            value: "rows"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            label: "In Columns",
                            commandId: "pdjs/canvas/standard:form-field/auto-tab-indexes",
                            value: "columns"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:form-field/tab-index-toggle"
                        }));
                    }
                }
                ContextMenu.TabIndexContextMenuGroup = TabIndexContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class ViewContextMenuGroup extends Jade.UI.Controls.ContextMenuGroup {
                    constructor() {
                        super({ id: "view" });
                    }
                    get view() {
                        return CanvasJS.Design.Environment.selection.first();
                    }
                    onPopulate() {
                        this.items.add(new Jade.UI.Controls.ContextMenuDivider());
                        this.items.add(new Jade.UI.Controls.ContextMenuItem({
                            commandId: "pdjs/canvas/standard:view/designer"
                        }));
                    }
                    meetsLoadConditions() {
                        return CanvasJS.Design.Environment.selection.count == 1
                            && Jade.InterfaceGuard.is(this.view, Canvas.Shared.Views.IViewComponentGuard);
                    }
                }
                ContextMenu.ViewContextMenuGroup = ViewContextMenuGroup;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class BorderStyleContextMenuItem extends Jade.UI.Controls.ContextMenuItemTemplate {
                template() {
                    return `<div class="-jadejs-contextmenu-item">
                        <div style="border-color:var(--visiv-theme-base-1-text-color);border-width:3px 0 0 0;border-style:${this.value};height:0;margin-top:5px;"></div>
                    </div>`;
                }
            }
            Design.BorderStyleContextMenuItem = BorderStyleContextMenuItem;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ContextMenu;
            (function (ContextMenu) {
                class ColorPaletteMenuItem extends Jade.UI.Controls.ContextMenuItemTemplate {
                    constructor(options) {
                        super(options);
                    }
                    get colors() {
                        return this.state.get("colors");
                    }
                    get palette() {
                        return this.m_palette;
                    }
                    set palette(value) {
                        this.m_palette = value;
                    }
                    template() {
                        return `<div class="-jadejs-contextmenu-item-color-palette-large">
                        <div role="palette"></div>
                    </div>`;
                    }
                    click(e) {
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.palette = new PDJS.Shared.Colors.ColorPalette({
                            colors: this.colors,
                            targetTheme: PDJS.Services.Themes.ThemeScope.Canvas,
                            select: (e) => {
                                this.onColorSelect(e.color);
                                if (this.closeOnClick) {
                                    this.parent.hide();
                                }
                            }
                        });
                        this.controls.add(this.palette);
                    }
                    onColorSelect(color) {
                        if (this.commandSubscriber != null) {
                            this.commandSubscriber.execute(color);
                        }
                    }
                }
                ContextMenu.ColorPaletteMenuItem = ColorPaletteMenuItem;
            })(ContextMenu = Design.ContextMenu || (Design.ContextMenu = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dialogs;
            (function (Dialogs) {
                class AutoArrangeDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    template() {
                        return super.template(`
                    <div style="position:absolute;inset:0;">
                        <div data-controls style="position:absolute;top:0;right:0;bottom:36px;left:0;overflow-y:auto;overflow-x:hidden;">
                        </div>
                        <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                            <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.columnCount_init();
                        this.columnWidth_init();
                        this.columnSpacing_init();
                        this.rowSpacing_init();
                        this.node.on(Jade.BrowserEvent.KEYPRESS, "input", (e) => {
                            if (e.which === Jade.KeyCode.Enter) {
                                this.okAndClose();
                            }
                        });
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_columnCount.value = Design.ElementLayoutSettings.columnCount;
                        this.m_columnWidth.value = Design.ElementLayoutSettings.columnWidth;
                        this.m_columnSpacing.value = Design.ElementLayoutSettings.columnSpacing;
                        this.m_rowSpacing.value = Design.ElementLayoutSettings.rowSpacing;
                        this.m_columnCount.focus();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Auto Arrange",
                            height: 260,
                            width: 300
                        };
                    }
                    static open(options) {
                        return new AutoArrangeDialog(options);
                    }
                    okButton_onClick(e) {
                        this.okAndClose();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    columnCount_init() {
                        this.m_columnCount =
                            new PDJS.Shared.UI.Controls.Fields.NumericField({
                                label: "Column Count",
                                numericType: "int32"
                            });
                        this.controls.add(this.m_columnCount);
                    }
                    columnWidth_init() {
                        this.m_columnWidth =
                            new PDJS.Shared.UI.Controls.Fields.NumericField({
                                label: "Column Width",
                                numericType: "int32"
                            });
                        this.m_columnWidth.validators
                            .add(new PDJS.Shared.UI.Controls.Fields.FieldValidatorMultipleOf({
                            multipleOf: 5
                        }));
                        this.controls.add(this.m_columnWidth);
                    }
                    columnSpacing_init() {
                        this.m_columnSpacing =
                            new PDJS.Shared.UI.Controls.Fields.NumericField({
                                label: "Column Spacing",
                                numericType: "int32"
                            });
                        this.m_columnSpacing.validators
                            .add(new PDJS.Shared.UI.Controls.Fields.FieldValidatorMultipleOf({
                            multipleOf: 5
                        }));
                        this.controls.add(this.m_columnSpacing);
                    }
                    rowSpacing_init() {
                        this.m_rowSpacing =
                            new PDJS.Shared.UI.Controls.Fields.NumericField({
                                label: "Row Spacing",
                                numericType: "int32"
                            });
                        this.m_rowSpacing.validators
                            .add(new PDJS.Shared.UI.Controls.Fields.FieldValidatorMultipleOf({
                            multipleOf: 5
                        }));
                        this.controls.add(this.m_rowSpacing);
                    }
                    validate() {
                        this.controls.each((control) => {
                            if (control instanceof PDJS.Shared.UI.Controls.Fields.Field) {
                                control.validate();
                            }
                        });
                    }
                    isValid() {
                        let result = true;
                        this.controls.each((control) => {
                            if (control instanceof PDJS.Shared.UI.Controls.Fields.Field && result) {
                                result = control.isValid;
                            }
                        });
                        return result;
                    }
                    okAndClose() {
                        this.validate();
                        if (!this.isValid()) {
                            return;
                        }
                        Design.ElementLayoutSettings.columnCount = this.m_columnCount.value;
                        Design.ElementLayoutSettings.columnWidth = this.m_columnWidth.value;
                        Design.ElementLayoutSettings.columnSpacing = this.m_columnSpacing.value;
                        Design.ElementLayoutSettings.rowSpacing = this.m_rowSpacing.value;
                        Design.ElementLayoutSettings.save();
                        this.close({
                            name: "ok"
                        });
                    }
                }
                Dialogs.AutoArrangeDialog = AutoArrangeDialog;
            })(Dialogs = Design.Dialogs || (Design.Dialogs = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dialogs;
            (function (Dialogs) {
                class ExternalFilesDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get input() {
                        return this.node.find("textarea");
                    }
                    get value() {
                        return this.state.get("value", []);
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-canvas-external-files-dialog">
                        <div>
                            In the input below add one URL per line to each external stylesheet or javascript file you wish to reference.
                        </div>
                        <div>
                            <textarea></textarea>
                        </div>
                        <div>
                            <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>`);
                    }
                    static open(options) {
                        return new ExternalFilesDialog(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.input.val(this.value.join("\n"));
                    }
                    getDefaultOptions() {
                        return {
                            title: "Edit | External Files",
                            height: 300,
                            width: 500
                        };
                    }
                    okButton_onClick(e) {
                        this.okAndClose();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    isValid() {
                        let value = this.input.val();
                        let lines = value.split("\n");
                        let invalidLines = [];
                        let validLines = [];
                        lines.forEach((line, index) => {
                            var _a;
                            line = line.toLowerCase();
                            let ext = (_a = Jade.Path.getFileExtension(line)) === null || _a === void 0 ? void 0 : _a.toLowerCase();
                            if (ext != ".js" && ext != ".css") {
                                invalidLines.push(index + 1);
                                return;
                            }
                            else {
                                validLines.push(line);
                            }
                        });
                        if (invalidLines.length > 0) {
                            Jade.UI.Dialogs.MessageDialog.open({
                                title: "Error | Invalid References",
                                message: "Only files with the .js and .css extensions may be referenced. Please remove any invalid references.",
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK
                            });
                            return false;
                        }
                        this.value = validLines;
                        return true;
                    }
                    okAndClose() {
                        if (!this.isValid()) {
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: {
                                value: this.value
                            }
                        });
                    }
                }
                Dialogs.ExternalFilesDialog = ExternalFilesDialog;
            })(Dialogs = Design.Dialogs || (Design.Dialogs = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class AssignmentDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get variables() {
                        return this.state.get("variables", []);
                    }
                    get rootNode() {
                        return this.node.find(".-pdjs-canvas-dynamics-assignment-dialog-body");
                    }
                    template() {
                        return super.template(`<div class="-pdjs-canvas-dynamics-assignment-dialog-body" data-controls></div>`);
                    }
                    static open(options) {
                        return new AssignmentDialog(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.dialog_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                    }
                    onDialogSelect(e, data) {
                        e.handled = true;
                        this.okAndClose();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Variable",
                            height: 384,
                            width: 420,
                            resizable: false
                        };
                    }
                    dialog_init() {
                        this.node.addClass("-pdjs-canvas-dynamics-assignment-dialog");
                        this.buttonsDeck.addAutoButtons("ok", "cancel");
                        this.grid_init();
                    }
                    okAndClose() {
                        let color = null;
                        this.close({
                            name: "ok",
                            data: { color: color }
                        });
                    }
                    grid_init() {
                        this.m_grid = new Dynamics.AssignmentDialogGrid({
                            variables: this.variables,
                            select: (e) => {
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                }
                Dynamics.AssignmentDialog = AssignmentDialog;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class AssignmentDialogGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_types = {
                            1: "Boolean",
                            2: "Date",
                            3: "Number",
                            4: "String",
                        };
                        this.m_sources = {
                            1: "Local",
                            2: "System",
                            3: "Context"
                        };
                    }
                    get variables() {
                        return this.state.get("variables", []);
                    }
                    get selectCallback() {
                        return this.state.get("select", () => { });
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-design-variable-list"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.node,
                            pk: "id",
                            height: "100%",
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                mapping: (e) => {
                                    return _.extend(e.toJSON(), {
                                        id: e.id
                                    });
                                }
                            },
                            resizable: true,
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            messaging: {
                                noRecordsMessage: "No variables have been defined."
                            },
                            change: (e) => {
                                this.selectCallback(e.selection);
                            },
                            dblclick: (e) => {
                                this.selectCallback(e.selection);
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "icon",
                                    transform: function (data) {
                                        return Jade.IconSet.get("pdjs").resolve("function.png", Jade.IconSetSizeSpecificDirectory.x16);
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name",
                                    width: "200px",
                                    template: (data) => {
                                        return `<b>${data.name}</b>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "type",
                                    title: "Type",
                                    width: "100px",
                                    template: (data) => {
                                        return `${this.m_types[data.type] || "Unknown"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "source",
                                    title: "Source",
                                    width: "100px",
                                    template: (data) => {
                                        return `${this.m_sources[data.source] || "Unknown"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "isNullable",
                                    title: "Allow Null",
                                    width: "80px",
                                    template: (data) => {
                                        return `${data.isNullable ? "True" : "False"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ]
                        });
                        this.m_grid.get_dataSource().data(this.variables);
                    }
                }
                Dynamics.AssignmentDialogGrid = AssignmentDialogGrid;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class DynamicsEditor extends FeatureBlendJS.Views.EditorExtender {
                    get addButtonNode() {
                        return this.node.find("button");
                    }
                    get document() {
                        return Jade.Application
                            .instance
                            .contexts
                            .findClosestContext(["canvas"])
                            .store
                            .get("document");
                    }
                    get dynamics() {
                        return this.feature.dynamics.find((item) => {
                            return item.clientPath === this.editorModel.name ||
                                item.serverPath === this.editorModel.name;
                        });
                    }
                    get listNode() {
                        return this.node.find("select[role=list]");
                    }
                    get textNode() {
                        return this.node.find("input[role=text]");
                    }
                    get textValue() {
                        return this.textNode.val();
                    }
                    set textValue(value) {
                        this.textNode.val(value);
                    }
                    get variables() {
                        return this.state.get("variables", []);
                    }
                    set variables(value) {
                        this.state.set("variables", value);
                    }
                    get hasVariables() {
                        return this.variables.length > 0;
                    }
                    get isVariableAssigned() {
                        return this.dynamics != null
                            && this.dynamics.variableId != null;
                    }
                    template() {
                        return `<div class="-pdjs-dynamics-editor">
                        <div data-controls>
                            <select role="list" tabIndex="-1"></select>
                            <input type="test" role="text"></select>
                        </div>
                        <div>
                            <button role="add" class="-pdjs-dynamics-editor-btn-add" title="Add new variable."></button>
                        </div>
                    </div>`;
                    }
                    createButton() {
                        return $(`<button class="-pdjs-dynamics-editor-toggle"></button>`);
                    }
                    isActive() {
                        return this.dynamics != null;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.variables = this.getVariableList(true);
                        this.list_init();
                        this.text_init();
                        this.addButton_init();
                        if (this.isVariableAssigned) {
                            this.setInitialValue();
                        }
                        this.setTooltip(this.isVariableAssigned);
                        this.toggleVisibleState(this.isVariableAssigned);
                        this.clickCallback({
                            visible: this.isVariableAssigned
                        });
                        this.subscriptions.add(Dynamics.EventsHub.variableAddedSubscribe(() => {
                            this.variables = this.getVariableList(true);
                            this.list_init();
                            this.text_init();
                        }));
                        this.featureSet.controller.onCommit(() => {
                            this.setValue(this.dynamics.variableId, false);
                        });
                    }
                    activeButton_onClick(e) {
                        if (e.visible) {
                            this.setValue(this.textValue);
                            this.setHighlight(this.textValue);
                            this.setTooltip(e.visible);
                        }
                        else {
                            this.dynamics.variableId = null;
                            this.setHighlight("");
                            this.setTooltip(e.visible);
                        }
                    }
                    addButton_click(e) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: "New | Variable",
                            args: {
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Canvas.CanvasVariableArbiter",
                                targetType: "ProspectDirector.Web.UI.Canvas.CanvasVariable",
                                properties: {
                                    variables: JSON.stringify(this.getVariableList()),
                                    dataType: this.getDynamicsTypeId()
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.addToVariableList(e.target);
                                    Dynamics.EventsHub.variableAddedPublish();
                                    this.setValue(e.target.id);
                                }
                            }
                        });
                    }
                    addButton_init() {
                        this.addButtonNode.click((e) => {
                            this.addButton_click(e);
                        });
                    }
                    list_change(e) {
                        let value = this.listNode.val();
                        this.setValue(value, true);
                        this.setHighlight(value);
                        this.listNode.val("");
                    }
                    list_init() {
                        this.listNode.off(Jade.BrowserEvent.CHANGE);
                        this.listNode.empty();
                        this.listNode.append(`<option value=""></option>`);
                        this.variables.forEach(item => {
                            this.listNode.append(`<option value="${item.name}">${item.name}</option>`);
                        });
                        this.listNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.list_change, this));
                    }
                    getDynamicsTypeId() {
                        switch (this.dynamics.dataType.toLowerCase()) {
                            case "boolean":
                                return Canvas.Core.Dynamics.CanvasVariableType.Boolean;
                            case "numeric":
                                return Canvas.Core.Dynamics.CanvasVariableType.Number;
                            case "datetime":
                                return Canvas.Core.Dynamics.CanvasVariableType.Date;
                            case "string":
                                return Canvas.Core.Dynamics.CanvasVariableType.String;
                        }
                    }
                    text_init() {
                        this.textNode.off(Jade.BrowserEvent.KEYUP);
                        this.textNode.off(Jade.BrowserEvent.FOCUS);
                        this.textNode.off(Jade.BrowserEvent.BLUR);
                        this.textNode.css({
                            position: "absolute",
                            inset: 0,
                            right: "20px"
                        });
                        if (!this.hasVariables) {
                            this.textNode.val("No variables defined.");
                            this.textNode.addClass("-pdjs-dynamics-variable-invalid");
                        }
                        this.textNode.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.setHighlight(this.textValue, true);
                        });
                        this.textNode.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.setHighlight(this.textValue, true);
                        });
                        this.textNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.setHighlight(this.textValue);
                            this.setValue(this.textValue, true);
                        });
                    }
                    setHighlight(value, fuzzyCheck = false) {
                        let className = this.isValidVariable(value) ?
                            "-pdjs-dynamics-variable" :
                            "-pdjs-dynamics-variable-invalid";
                        this.clearHighlight();
                        this.textNode.addClass(className);
                    }
                    clearHighlight() {
                        let classNames = [
                            "-pdjs-dynamics-variable",
                            "-pdjs-dynamics-variable-invalid"
                        ];
                        classNames.forEach(name => {
                            this.textNode.removeClass(name);
                        });
                    }
                    setInitialValue() {
                        let variable = this.getVariableById(this.dynamics.variableId);
                        if (variable != null) {
                            this.textValue = variable.name;
                            this.setHighlight(variable.name);
                        }
                    }
                    setValue(value, setByName = false) {
                        let variable = setByName ?
                            this.getVariableByName(value) :
                            this.getVariableById(value);
                        if (variable != null) {
                            this.textValue = variable.name;
                            this.dynamics.variableId = variable.id;
                            this.setHighlight(variable.name);
                        }
                        else {
                            this.dynamics.variableId = null;
                            this.clearHighlight();
                            this.setHighlight(value);
                        }
                    }
                    isValidVariable(value, fuzzyCheck = false) {
                        if (fuzzyCheck) {
                            return this.variables
                                .filter(item => value != null && item.name.toLowerCase().indexOf(value.toString().toLowerCase()) > -1)
                                .length > 0;
                        }
                        return this.variables
                            .filter(item => value != null && item.name.toLowerCase() == value.toString().toLowerCase())
                            .length > 0;
                    }
                    getVariableList(filtered = false) {
                        let result = [];
                        if (this.document != null) {
                            result = this.document.source.variables.toArray();
                        }
                        if (filtered) {
                            result = result.filter((item) => {
                                return this.dynamics != null && this.getDynamicsTypeId() == item.type;
                            });
                        }
                        return result;
                    }
                    addToVariableList(item) {
                        if (this.document != null) {
                            this.document.source.variables.add(item);
                        }
                    }
                    getVariableById(id) {
                        return _.first(this.variables.filter(item => {
                            return id != null && item.id.toLowerCase() == id.toString().toLowerCase();
                        }));
                    }
                    getVariableByName(name) {
                        return _.first(this.variables.filter(item => {
                            return name != null && item.name.toLowerCase() == name.toString().toLowerCase();
                        }));
                    }
                    setTooltip(usingVariable) {
                        usingVariable ?
                            this.button.attr("title", "Click to use a fixed value for this property.") :
                            this.button.attr("title", "Click to use a varible for this property.");
                    }
                }
                Dynamics.DynamicsEditor = DynamicsEditor;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                let Events;
                (function (Events) {
                    Events["VariableAdded"] = "Canvas:VariableAdded";
                })(Events = Dynamics.Events || (Dynamics.Events = {}));
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static variableAddedPublish() {
                        this.current.publish(Events.VariableAdded);
                    }
                    static variableAddedSubscribe(handler) {
                        return this.current.subscribe(Events.VariableAdded, handler);
                    }
                }
                Dynamics.EventsHub = EventsHub;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class CommandState {
                    static setCanvasVariables(args) {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/canvas/variables": args
                        });
                    }
                }
                Dynamics.CommandState = CommandState;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                let Events;
                (function (Events) {
                    Events["CanvasVariablesUpdated"] = "canvas/variables/updated";
                })(Events = Dynamics.Events || (Dynamics.Events = {}));
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariablesDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get splitter() {
                        return this.m_splitter;
                    }
                    get splitterNode() {
                        return this.node.find("div[data-role=splitter]");
                    }
                    template() {
                        return super.template(`<div class="-pdjs-canvas-variables-dialog">
                    <div data-role="toolbar"></div>
                    <div data-role="content"></div>
                    <div data-role="deck">
                        <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.cancelButton_onClick(e);
                        });
                        this.okButton.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.okButton_onClick(e);
                        });
                        this.node.on(Jade.BrowserEvent.KEYPRESS, "input", (e) => {
                            if (e.which === Jade.KeyCode.Enter) {
                                this.okAndClose();
                            }
                        });
                        this.toolbars_init();
                        this.grid_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Manage | Variables",
                            height: 400,
                            width: 600
                        };
                    }
                    onResize() {
                        if (this.m_splitter) {
                            this.m_splitter.resize();
                        }
                    }
                    splitter_init() {
                        this.m_splitter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true },
                                { resizable: true, size: "300px" }
                            ],
                            orientation: "vertical"
                        }).data("kendoSplitter");
                    }
                    okButton_onClick(e) {
                        this.okAndClose();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    okAndClose() {
                        Dynamics.VariableList.sourceVariables.clear();
                        Dynamics.VariableList.variables.toArray().forEach(variable => {
                            Dynamics.VariableList.sourceVariables.add(variable);
                        });
                        this.close({
                            name: "ok"
                        });
                    }
                    grid_init() {
                        this.m_list = new Dynamics.VariableList({
                            insertAt: "div[data-role=content]",
                            select: (e) => {
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    toolbars_init() {
                        this.m_toolbarList = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[data-role=toolbar]",
                            segments: [
                                new Dynamics.VariablesListToolbar()
                            ]
                        });
                        this.controls.add(this.m_toolbarList);
                    }
                    setCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/canvas/variables": {
                                $list: this.m_list
                            }
                        });
                    }
                    static open(options) {
                        return new VariablesDialog(options);
                    }
                }
                Dynamics.VariablesDialog = VariablesDialog;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_types = {
                            1: "Boolean",
                            2: "Date",
                            3: "Number",
                            4: "String",
                        };
                        this.m_sources = {
                            1: "Local",
                            2: "System",
                            3: "Context"
                        };
                    }
                    get selectCallback() {
                        return this.state.get("select", () => { });
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-design-variable-list"></div>`;
                    }
                    refresh(e) {
                        this.m_grid.get_dataSource().data([]);
                        this.m_grid.get_dataSource().data(VariableList.variables.toArray());
                        this.m_grid.refresh(e);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.node,
                            pk: "id",
                            height: "100%",
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                mapping: (e) => {
                                    return _.extend(e.toJSON(), {
                                        id: e.id
                                    });
                                }
                            },
                            footer: {
                                visible: false
                            },
                            resizable: true,
                            sortable: {
                                mode: "single",
                                allowUnsort: true
                            },
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true,
                                sort: [
                                    { field: "name", dir: "asc" }
                                ]
                            },
                            messaging: {
                                noRecordsMessage: "No variables have been defined."
                            },
                            change: (e) => {
                                if (this.m_grid) {
                                    Dynamics.CommandState.setCanvasVariables({ $list: this });
                                    this.selectCallback(e.selection);
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/canvas/variables:variable/edit");
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "icon",
                                    transform: function (data) {
                                        return Jade.IconSet.get("pdjs").resolve("function.png", Jade.IconSetSizeSpecificDirectory.x16);
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name",
                                    width: "200px",
                                    template: (data) => {
                                        return `<b>${data.name}</b>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "type",
                                    title: "Type",
                                    width: "100px",
                                    template: (data) => {
                                        return `${this.m_types[data.type] || "Unknown"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "source",
                                    title: "Source",
                                    width: "100px",
                                    template: (data) => {
                                        return `${this.m_sources[data.source] || "Unknown"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "isNullable",
                                    title: "Allow Null",
                                    width: "80px",
                                    template: (data) => {
                                        return `${data.isNullable ? "True" : "False"}`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ]
                        });
                        this.m_grid.get_dataSource().data(Dynamics.VariableList.variables.toArray());
                    }
                    static get variables() {
                        let store = Jade.Application.instance.contexts.current.store;
                        if (store.get("variables") == null) {
                            store.set("variables", new Canvas.Core.Dynamics.VariableCollection(this.sourceVariables.toArray()));
                        }
                        return store.get("variables");
                    }
                    static get sourceVariables() {
                        let result = null;
                        let document = Jade.Application
                            .instance
                            .contexts
                            .findClosestContext(["canvas"])
                            .store
                            .get("document");
                        if (document != null) {
                            result = document.source.variables;
                        }
                        return result;
                    }
                }
                Dynamics.VariableList = VariableList;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableListItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get name() {
                        return this.state.get("name");
                    }
                    get description() {
                        return this.state.get("description");
                    }
                    template() {
                        return `<table class="pdjs-canvas-design-variable-list-item">
                        <tr>                    
                            <td style="width:200px;border:1px solid;"><div>${this.name}</div></td>
                            <td style="left:200px;right:0;"><div>${this.description}</div></td>
                        </tr>
                    </table>`;
                    }
                }
                Dynamics.VariableListItem = VariableListItem;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariablesListToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "pdjs/canvas/variables:variable/create"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "pdjs/canvas/variables:variable/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "pdjs/canvas/variables:variable/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "pdjs/canvas/variables:variable/clear"
                        }));
                    }
                }
                Dynamics.VariablesListToolbar = VariablesListToolbar;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableCommand extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set("$list", null);
                    }
                    get document() {
                        this.ensureDocument();
                        return this.m_document;
                    }
                    get elements() {
                        return this.document.source.elements.toArray();
                    }
                    get selections() {
                        return this.grid.getSelections().toArray();
                    }
                    get list() {
                        return this.state.get("$list");
                    }
                    get grid() {
                        return this.list.grid;
                    }
                    setCommandState() {
                        Dynamics.CommandState.setCanvasVariables({
                            $list: this.list
                        });
                    }
                    ensureDocument() {
                        if (this.m_document == null) {
                            this.m_document = Jade.Application
                                .instance
                                .contexts
                                .findClosestContext(["canvas"])
                                .store
                                .get("document");
                        }
                    }
                    updateGrid(selections = []) {
                        this.list.refresh({
                            clear: true,
                            selections: selections.map((variable) => {
                                return variable.id;
                            })
                        });
                    }
                }
                Dynamics.VariableCommand = VariableCommand;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableClearCommand extends Dynamics.VariableCommand {
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selections.length === 1;
                    }
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Clear Variables?",
                            message: `Delete all of the variables in this canvas?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeClear();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/clear",
                            label: "Clear",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    executeClear() {
                        Dynamics.VariableList.variables.clear();
                        this.updateGrid();
                        this.setCommandState();
                    }
                }
                Dynamics.VariableClearCommand = VariableClearCommand;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/canvas/variables");
                    }
                    registerCommands(e) {
                        this.commands.add(new Dynamics.VariableCreateCommand());
                        this.commands.add(new Dynamics.VariableDeleteCommand());
                        this.commands.add(new Dynamics.VariableClearCommand());
                        this.commands.add(new Dynamics.VariableEditCommand());
                    }
                }
                Dynamics.VariableCommands = VariableCommands;
                Jade.Application.onStart(function () {
                    Jade.CommandGroups.add(VariableCommands);
                });
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableCreateCommand extends Dynamics.VariableCommand {
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: "New | Variable",
                            height: 460,
                            width: 450,
                            args: {
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Canvas.CanvasVariableArbiter",
                                targetType: "ProspectDirector.Web.UI.Canvas.CanvasVariable",
                                properties: {
                                    variables: JSON.stringify(Dynamics.VariableList.variables.toArray())
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    Dynamics.VariableList.variables.add(e.target);
                                    this.updateGrid([e.target]);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/create",
                            label: "Add",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                }
                Dynamics.VariableCreateCommand = VariableCreateCommand;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableDeleteCommand extends Dynamics.VariableCommand {
                    get variable() {
                        return _.first(this.selections);
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selections.length > 0;
                    }
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Delete Selected Variable?",
                            message: `Delete the "${this.variable.name}" variable?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeDelete();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    executeDelete() {
                        let variableId = this.variable.id;
                        Dynamics.VariableList.variables.remove(variableId);
                        this.updateGrid();
                        let elements = this.elements.filter(element => {
                            return element.dynamics != null &&
                                element.dynamics.length > 0;
                        });
                        elements.forEach(element => {
                            let active = element.dynamics.filter(item => {
                                return item.variableId !== variableId;
                            });
                            ;
                            element.dynamics = active;
                        });
                        this.setCommandState();
                    }
                }
                Dynamics.VariableDeleteCommand = VariableDeleteCommand;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Dynamics;
            (function (Dynamics) {
                class VariableEditCommand extends Dynamics.VariableCommand {
                    get variable() {
                        return _.first(this.selections);
                    }
                    setState(state, options) {
                        super.setState(state, options);
                        this.enabled = this.selections.length === 1;
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: "Edit | Variable",
                            height: 460,
                            width: 450,
                            args: {
                                targetId: this.variable.id,
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Canvas.CanvasVariableArbiter",
                                targetType: "ProspectDirector.Web.UI.Canvas.CanvasVariable",
                                properties: {
                                    variables: JSON.stringify(Dynamics.VariableList.variables.toArray())
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    Dynamics.VariableList.variables.add(e.target);
                                    this.updateGrid([e.target.id]);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                }
                Dynamics.VariableEditCommand = VariableEditCommand;
            })(Dynamics = Design.Dynamics || (Design.Dynamics = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormElementBase extends Design.ElementViewBase {
                    constructor(options) {
                        super(options);
                    }
                }
                Forms.FormElementBase = FormElementBase;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormButton extends Forms.FormElementBase {
                    get buttonIconNode() {
                        return this.buttonNode.find("div:nth-child(2)");
                    }
                    get buttonImageNode() {
                        return this.buttonIconNode.find("img");
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get buttonTextNode() {
                        return this.buttonNode.find("div:nth-child(3)");
                    }
                    get imageUrl() {
                        return Jade.Path.resolve(`~/resources/${this.source.image}`);
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-form-button">
                        <button>
                            <div></div>
                            <div><img/></div>
                            <div></div>
                            <div></div>
                        </button>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.buttonNode.css({
                            borderRadius: borderRadius
                        });
                        if (this.source.hasImage) {
                            this.buttonImageNode.show();
                            this.buttonImageNode.attr("src", this.imageUrl);
                        }
                        else {
                            this.buttonImageNode.hide();
                        }
                        if (this.source.hasLabel) {
                            this.buttonTextNode.show();
                            this.buttonTextNode.text(this.source.label);
                        }
                        else {
                            this.buttonTextNode.hide();
                        }
                        this.buttonImageNode.css({
                            maxWidth: this.buttonNode.width(),
                            maxHeight: this.buttonNode.height()
                        });
                        this.source.hasImage && this.source.hasLabel ?
                            this.buttonIconNode.css({ paddingRight: "5px" }) :
                            this.buttonIconNode.css({ paddingRight: "0" });
                        this.styleInjector.clear();
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle(".-pdjs-canvas-form-button button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                }
                Forms.FormButton = FormButton;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let FormField = class FormField extends Forms.FormElementBase {
                    get formId() {
                        return this.source.formId;
                    }
                    get label() {
                        return this.source.label || this.source.defaultLabel;
                    }
                    get labelNode() {
                        return this.formFieldNode.children("[role=label]");
                    }
                    get controlNode() {
                        return this.formFieldNode.children("[role=control]");
                    }
                    get formFieldNode() {
                        return this.node.find(`.${Canvas.Shared.CanvasCss.FormField}`);
                    }
                    get deck() {
                        return this.m_deck;
                    }
                    template() {
                        return `<div class="${Canvas.Shared.CanvasCss.FormField}">
                        <div role="label">${this.label}:</div>
                        <div role="control" data-controls>
                        </div>
                    </div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.deck_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.labelNode.text(`${this.source.activeLabel}:`);
                        this.labelNode.css({
                            color: this.source.activeLabelColor
                        });
                        if (this.source.activeEnabledState) {
                            this.formFieldNode.removeClass(PDJS.Shared.UI.CssClass.Disabled);
                        }
                        else {
                            this.formFieldNode.addClass(PDJS.Shared.UI.CssClass.Disabled);
                        }
                    }
                    deck_init() {
                        this.m_deck = new Forms.FormFieldDeck({
                            insertAt: `.${Canvas.Shared.CanvasCss.FormField}`
                        });
                        this.controls.add(this.m_deck);
                        this.deck.controls.add(new Forms.FormFieldToolTip({
                            formField: this
                        }));
                    }
                };
                FormField = __decorate([
                    Jade.UI.Controls.toolingTags("form-field")
                ], FormField);
                Forms.FormField = FormField;
                class FormFieldBase extends FormField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.FormFieldBase = FormFieldBase;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class BuiltInField extends Forms.FormFieldBase {
                }
                Forms.BuiltInField = BuiltInField;
                class BuildInFieldBase extends BuiltInField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.BuildInFieldBase = BuildInFieldBase;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class ExtensionField extends Forms.FormFieldBase {
                    onActivate(e) {
                        super.onActivate(e);
                        this.source.inBatchMode = CanvasJS
                            .Actual
                            .Environment
                            .document
                            .state
                            .get("isBatchMode");
                        this.deck.controls.add(new Forms.FormFieldBatchEdit({
                            extensionField: this
                        }));
                    }
                }
                Forms.ExtensionField = ExtensionField;
                class ExtensionFieldBase extends ExtensionField {
                    get source() {
                        return this.m_source;
                    }
                }
                Forms.ExtensionFieldBase = ExtensionFieldBase;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class EntityDescriptionField extends Forms.BuildInFieldBase {
                    get inputNode() {
                        return this.node.find("textarea");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.controlNode.append(`<textarea 
                                        class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" 
                                        style="overflow-y:scroll;">
                                    </textarea>`);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                }
                Forms.EntityDescriptionField = EntityDescriptionField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let EntityIconField = class EntityIconField extends Forms.BuildInFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityIconFieldComboBox({
                            defaultMask: "Select...",
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp
                        });
                        this.controls.add(this.m_comboBox);
                    }
                };
                EntityIconField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], EntityIconField);
                Forms.EntityIconField = EntityIconField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let EntityNameField = class EntityNameField extends Forms.BuildInFieldBase {
                    get inputNode() {
                        return this.controlNode.find("input[type=text]");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                        this.controlNode.append(`<input 
                                        type="text"
                                        class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" />`);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                };
                EntityNameField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], EntityNameField);
                Forms.EntityNameField = EntityNameField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let EntityParentField = class EntityParentField extends Forms.BuildInFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    get navigate() {
                        return this.m_navigate;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                        this.navigate_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("--pdjs-canvas-shared-entity-parent-field");
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                        this.comboBox.selection = {
                            entityID: 0,
                            entityName: "Parent 'A'",
                            entityTypeIcon: "cube_green.png",
                            entityTypeName: "",
                            entityTypeId: 0
                        };
                        Canvas.Shared.Forms.NavigateLink.setDesignDisplay(this.navigate);
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityParentFieldComboBox({
                            defaultMask: "Select...",
                            entityTypeId: this.source.entityTypeId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                        });
                        this.controls.add(this.m_comboBox);
                    }
                    navigate_init() {
                        this.m_navigate = new Canvas.Shared.Forms.NavigateLink({});
                        this.controls.add(this.m_navigate);
                    }
                };
                EntityParentField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], EntityParentField);
                Forms.EntityParentField = EntityParentField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class EntityProcessField extends Forms.BuildInFieldBase {
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_assignment = new Canvas.Shared.Forms.EntityProcessField({
                            entityTypeId: this.source.entityTypeId,
                            keyIcon: "SIGNAL_FLAG_BLUE.PNG",
                            keyName: "Evaluation",
                            processName: `Process "A"`,
                            stageId: this.source.stageId,
                            stageName: "Ready To Complete",
                            stageIcon: this.source.stageIcon,
                            statusId: this.source.statusId,
                            statusName: "Approved",
                            statusIcon: "BULLET_BALL_GREEN.PNG",
                            showKey: this.source.showKey,
                            showProcess: this.source.showProcess,
                            showStage: this.source.showStage,
                            showStatus: this.source.showStatus
                        });
                        this.controls.add(this.m_assignment);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_assignment.showKey = this.source.showKey;
                        this.m_assignment.showProcess = this.source.showProcess;
                        this.m_assignment.showStage = this.source.showStage;
                        this.m_assignment.showStatus = this.source.showStatus;
                    }
                }
                Forms.EntityProcessField = EntityProcessField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let BooleanField = class BooleanField extends Forms.ExtensionFieldBase {
                    get itemLabelNode() {
                        return this.controlNode.find("div[role=input-label]");
                    }
                    get checkboxNode() {
                        return this.controlNode.find("input[type=checkbox]");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BooleanField);
                        this.controlNode.append(`<label>
                                        <input type="checkbox" />
                                        <div role="input-label">
                                            ${this.source.itemLabel}
                                        </div>
                                    </label>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let iconPath = null;
                        if (this.source.itemIcon != null) {
                            iconPath = Jade.IconSet.get("pd")
                                .resolve(this.source.itemIcon, Jade.IconSetSizeSpecificDirectory.x16);
                            this.itemLabelNode.css({
                                paddingLeft: "24px",
                                backgroundImage: `url(${iconPath})`,
                                backgroundRepeat: "no-repeat",
                                backgroundPosition: "3px 3px"
                            });
                        }
                        else {
                            this.itemLabelNode.css({
                                paddingLeft: "4px"
                            });
                        }
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BooleanField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.checkboxNode.prop("disabled", !this.source.activeEnabledState);
                        this.itemLabelNode.css({
                            opacity: this.source.activeEnabledState ? 1 : .5
                        });
                    }
                };
                BooleanField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], BooleanField);
                Forms.BooleanField = BooleanField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let DateField = class DateField extends Forms.ExtensionFieldBase {
                    get dateBox() {
                        return this.m_dateBox;
                    }
                    get itemLabelNode() {
                        return this.controlNode.find("div[role=input-label]");
                    }
                    get checkboxNode() {
                        return this.controlNode.find("input[type=checkbox]");
                    }
                    get formatExample() {
                        return new Date(2010, 9, 31);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.dateBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.DateField);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setFormat();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setFormat();
                        this.itemLabelNode.css({
                            opacity: this.source.activeEnabledState ? 1 : .5
                        });
                        this.m_dateBox.enabled = this.source.activeEnabledState;
                    }
                    dateBox_init() {
                        this.m_dateBox = new PDJS.Shared.UI.Controls.DateTextBox({
                            format: this.source.activeFormat
                        });
                        this.controls.add(this.m_dateBox);
                    }
                    setFormat() {
                        if (this.dateBox.node) {
                            this.dateBox.mask = kendo.toString(this.formatExample, this.source.activeFormat);
                        }
                    }
                };
                DateField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], DateField);
                Forms.DateField = DateField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let DecimalField = class DecimalField extends Forms.ExtensionFieldBase {
                    get format() {
                        return this.source.activeFormat;
                    }
                    get numericBox() {
                        return this.m_numericTextBox;
                    }
                    get formatExample() {
                        return this.state.get("formatExample", 999999999);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.numericBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.NumericField);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setFormat();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setFormat();
                        this.numericBox.enabled = this.source.activeEnabledState;
                    }
                    numericBox_init() {
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.decimal,
                            format: this.format
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    setFormat() {
                        if (this.numericBox.node) {
                            this.numericBox.maskValue = kendo.toString(this.formatExample, this.format);
                        }
                    }
                };
                DecimalField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], DecimalField);
                Forms.DecimalField = DecimalField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let EntityField = class EntityField extends Forms.ExtensionFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    get navigate() {
                        return this.m_navigate;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                        this.navigate_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                        this.comboBox.selection = {
                            entityID: 0,
                            entityName: "Entity 'A'",
                            entityTypeIcon: "cube_yellow.png",
                            entityTypeName: ""
                        };
                        Canvas.Shared.Forms.NavigateLink.setDesignDisplay(this.navigate);
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.EntityFieldComboBox({
                            defaultMask: "Select...",
                            viewId: this.source.viewId,
                            viewStateId: this.source.viewStateId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp
                        });
                        this.controls.add(this.m_comboBox);
                    }
                    navigate_init() {
                        this.m_navigate = new Canvas.Shared.Forms.NavigateLink({});
                        this.controls.add(this.m_navigate);
                    }
                };
                EntityField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], EntityField);
                Forms.EntityField = EntityField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let Int32Field = class Int32Field extends Forms.ExtensionFieldBase {
                    get format() {
                        return this.source.format || this.source.columnFormat;
                    }
                    get numericBox() {
                        return this.m_numericTextBox;
                    }
                    get formatExample() {
                        return this.state.get("formatExample", 1750000);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.numericBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.NumericField);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setFormat();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setFormat();
                        this.m_numericTextBox.enabled = this.source.activeEnabledState;
                    }
                    numericBox_init() {
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.decimal,
                            format: this.format
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    setFormat() {
                        if (this.numericBox.node) {
                            this.numericBox.maskValue = kendo.toString(this.formatExample, this.format);
                        }
                    }
                };
                Int32Field = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], Int32Field);
                Forms.Int32Field = Int32Field;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let Int64Field = class Int64Field extends Forms.ExtensionFieldBase {
                    get format() {
                        return this.source.format || this.source.columnFormat;
                    }
                    get numericBox() {
                        return this.m_numericTextBox;
                    }
                    get formatExample() {
                        return this.state.get("formatExample", 1750000);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.numericBox_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.NumericField);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setFormat();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setFormat();
                        this.m_numericTextBox.enabled = this.source.activeEnabledState;
                    }
                    numericBox_init() {
                        this.m_numericTextBox = new PDJS.Shared.UI.Controls.NumericTextBox({
                            insertAt: "[role=control]",
                            numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.decimal,
                            format: this.format
                        });
                        this.controls.add(this.m_numericTextBox);
                    }
                    setFormat() {
                        if (this.numericBox.node) {
                            this.numericBox.maskValue = kendo.toString(this.formatExample, this.format);
                        }
                    }
                };
                Int64Field = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], Int64Field);
                Forms.Int64Field = Int64Field;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class MultiSelectField extends Forms.ExtensionFieldBase {
                    get multiSelect() {
                        return this.m_multiSelect;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.multiSelect_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.controlNode.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.controlNode.addClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                        this.controlNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.controlNode.removeClass(Canvas.Shared.CanvasCss.FormFieldFocus);
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.multiSelect.enabled = this.source.activeEnabledState;
                    }
                    template() {
                        return `<div class="${Canvas.Shared.CanvasCss.FormField} ${Canvas.Shared.CanvasCss.MultiSelectField}">
                        <div role="label">${this.label}:</div>
                        <div role="control" data-controls class="${Canvas.Shared.CanvasCss.FormFieldAnimationTarget}">
                        </div>
                    </div>`;
                    }
                    multiSelect_init() {
                        this.m_multiSelect = new PDJS.Shared.UI.Controls.MultiSelect({
                            onItemChecked: (e) => {
                                this.source.value = [];
                                this.multiSelect.items.each((item) => {
                                    if (item.checked) {
                                        this.source.value[this.source.value.length] = item.itemId;
                                    }
                                });
                            }
                        });
                        this.controls.add(this.m_multiSelect);
                        _.each(this.source.items, (item) => {
                            this.multiSelect.controls.add(new PDJS.Shared.UI.Controls.MultiSelectItem({
                                itemId: item.id,
                                label: item.label,
                                icon: item.icon
                            }));
                        });
                    }
                }
                Forms.MultiSelectField = MultiSelectField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let SingleSelectField = class SingleSelectField extends Forms.ExtensionFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_comboBox.enabled = this.source.activeEnabledState;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.SingleSelectFieldComboBox({
                            defaultMaskText: "Select...",
                            items: this.source.items,
                            onValueChanged: () => {
                                if (this.m_comboBox.selection != null) {
                                    this.source.selectedId = this.m_comboBox.selection.uid;
                                }
                                else {
                                    this.source.selectedId = null;
                                }
                            }
                        });
                        this.controls.add(this.m_comboBox);
                    }
                };
                SingleSelectField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], SingleSelectField);
                Forms.SingleSelectField = SingleSelectField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class StringField extends Forms.ExtensionFieldBase {
                    get inputNode() {
                        return this.node.find("[role=text]");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.controlNode.append(this.createInput());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.controlNode.html(this.createInput());
                        this.controlNode.addClass(this.source.multiLine ? "multiline" : "singleline");
                        this.controlNode.removeClass(this.source.multiLine ? "singleline" : "multiline");
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                    createInput() {
                        let result = "";
                        if (this.source.multiLine) {
                            result = `<textarea
                            role="text"
                            style="overflow-y:scroll;">
                            </textarea>`;
                        }
                        else {
                            result = `<input
                            role="text"
                            type="text" />`;
                        }
                        return result;
                    }
                }
                Forms.StringField = StringField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let UserField = class UserField extends Forms.ExtensionFieldBase {
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.comboBox.enabled = this.source.activeEnabledState;
                    }
                    comboBox_init() {
                        this.m_comboBox = new Canvas.Shared.Forms.UserFieldComboBox({
                            defaultMask: "Select...",
                            viewId: this.source.viewId,
                            viewStateId: this.source.viewStateId,
                            mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp
                        });
                        this.controls.add(this.m_comboBox);
                    }
                };
                UserField = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], UserField);
                Forms.UserField = UserField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormFieldDeckItem extends Jade.UI.Control {
                }
                Forms.FormFieldDeckItem = FormFieldDeckItem;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormFieldBatchEdit extends Forms.FormFieldDeckItem {
                    constructor(options) {
                        super(options);
                    }
                    get extensionField() {
                        return this.state.get("extensionField");
                    }
                    get checkBoxNode() {
                        return this.node.find("input");
                    }
                    get isVisible() {
                        return !this.extensionField.source.isDisabled
                            && !this.extensionField.source.isReadOnly
                            && CanvasJS.Design.Environment.document.isListBased;
                    }
                    template() {
                        return `<div class="-pd-form-field-deck-item" style="padding-top:7px;cursor:pointer;"><input type='checkbox'/></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.isVisible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                    }
                }
                Forms.FormFieldBatchEdit = FormFieldBatchEdit;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormFieldDeck extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    template() {
                        return `<div class="-pd-form-field-deck"></div>`;
                    }
                }
                Forms.FormFieldDeck = FormFieldDeck;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class FormFieldToolTip extends Forms.FormFieldDeckItem {
                    constructor(options) {
                        super(options);
                    }
                    get formField() {
                        return this.state.get("formField");
                    }
                    template() {
                        let tooltipIcon = Jade.IconSet.get("pdjs")
                            .resolve("question.png", Jade.IconSetSizeSpecificDirectory.x16);
                        return `<div class="-pd-form-field-deck-item" style="padding: 5px 1px 2px 1px;cursor:pointer;"><img src='${tooltipIcon}'/></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formField.source.state.on("change", _.bind(this.onStateChanged, this));
                    }
                    onStateChanged() {
                        if (this.formField.source.hasTooltip) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                    }
                }
                Forms.FormFieldToolTip = FormFieldToolTip;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Views;
            (function (Views) {
                class IViewComponentGuard extends Jade.InterfaceGuard {
                    get signature() {
                        return {
                            id: "8a1e94fe-4ba8-4b9a-8025-371115c2416c",
                            label: "IViewComponentGuard"
                        };
                    }
                }
                Views.IViewComponentGuard = IViewComponentGuard;
            })(Views = Shared.Views || (Shared.Views = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                let BatchField = class BatchField extends Forms.FormFieldBase {
                    get batch() {
                        return this.m_batch;
                    }
                    get viewStateId() {
                        return this.source.viewStateId;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.BatchField);
                        this.batch_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.batch.showCheckboxes = this.source.showCheckboxes;
                        this.batch_populate();
                    }
                    batch_init() {
                        this.m_batch = new PDJS.Shared.UI.Controls.BatchField({
                            dialogViewStateId: this.source.viewStateId,
                            dialogTitle: this.source.dialogTitle,
                            dialogHeight: this.source.dialogHeight,
                            dialogWidth: this.source.dialogWidth,
                            dialogFilters: [],
                            showCheckboxes: this.source.showCheckboxes,
                            change: (items) => {
                                this.source.listItems.splice(0, this.source.listItems.length);
                                items.forEach((item) => {
                                    this.source.listItems[this.source.listItems.length] = item;
                                });
                            }
                        });
                        this.controls.add(this.batch);
                    }
                    batch_populate() {
                        if (this.source.selectIdentities) {
                            this.batch.reload([
                                { active: true, selected: true, icon: null, id: 1, label: `User A`, visible: true },
                                { active: true, selected: false, icon: null, id: 2, label: `User B`, visible: true },
                                { active: true, selected: false, icon: null, id: 3, label: `Group A`, visible: true },
                                { active: true, selected: false, icon: null, id: 4, label: `User C`, visible: true },
                                { active: true, selected: false, icon: null, id: 5, label: `Group B`, visible: true }
                            ], "");
                        }
                        else {
                            this.batch.reload([
                                { active: true, selected: true, icon: null, id: 1, label: `Entity "A"`, visible: true },
                                { active: true, selected: false, icon: null, id: 2, label: `Entity "B"`, visible: true },
                                { active: true, selected: false, icon: null, id: 3, label: `Entity "C"`, visible: true },
                                { active: true, selected: false, icon: null, id: 4, label: `Entity "D"`, visible: true },
                                { active: true, selected: false, icon: null, id: 5, label: `Entity "E"`, visible: true }
                            ], "");
                        }
                    }
                };
                BatchField = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Shared.Views.IViewComponentGuard),
                    Jade.UI.Controls.toolingTags("view")
                ], BatchField);
                Forms.BatchField = BatchField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Forms;
            (function (Forms) {
                class TextField extends Forms.FormFieldBase {
                    get inputNode() {
                        return this.node.find("[role=text]");
                    }
                    onAttach(e) {
                        super.onAttach(e);
                        this.controlNode.append(this.createInput());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.formFieldNode.addClass(Canvas.Shared.CanvasCss.StringField);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.controlNode.html(this.createInput());
                        this.controlNode.addClass(this.source.multiLine ? "multiline" : "singleline");
                        this.controlNode.removeClass(this.source.multiLine ? "singleline" : "multiline");
                        this.inputNode.val(this.source.value);
                        if (this.source.activeEnabledState) {
                            this.inputNode.removeAttr("disabled");
                        }
                        else {
                            this.inputNode.attr("disabled", "disabled");
                        }
                    }
                    createInput() {
                        let result = "";
                        if (this.source.multiLine) {
                            result = `<textarea 
                            role="text"
                            style="overflow-y:scroll;">
                            </textarea>`;
                        }
                        else {
                            result = `<input 
                            role="text"
                            type="text" />`;
                        }
                        return result;
                    }
                }
                Forms.TextField = TextField;
            })(Forms = Design.Forms || (Design.Forms = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Process;
            (function (Process) {
                let DecisionButton = class DecisionButton extends Design.ElementViewBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get styleInjector() {
                        this.ensureStyleInjector();
                        return this.m_styleInjector;
                    }
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;">
                        <button style="height:100%;width:100%;box-sizing:border-box;"></button>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let borderRadius = Jade.String.isNullOrWhiteSpace(this.source.borderRadius) ? "0" : this.source.borderRadius;
                        this.buttonNode.css({
                            borderRadius: borderRadius
                        });
                        this.buttonNode.text(this.source.activeLabel);
                        this.styleInjector.clear();
                        this.setDefaultStyle();
                        this.setActiveStyle();
                        this.setFocusStyle();
                        this.setHoverStyle();
                        this.setInactiveStyle();
                        this.styleInjector.inject(this);
                    }
                    ensureStyleInjector() {
                        if (this.m_styleInjector == null) {
                            this.m_styleInjector = new PDJS.Shared.UI.StyleInjector({
                                id: this.ID
                            });
                        }
                    }
                    setActiveStyle() {
                        if (this.source.cssStates.hasActiveStates) {
                            this.styleInjector.addStyle("button:active", this.source.cssStates.getActiveStates());
                        }
                    }
                    setDefaultStyle() {
                        if (this.source.cssStates.hasDefaultStates) {
                            this.styleInjector.addStyle("button:not(:is(:active, :focus, :hover, :disabled))", this.source.cssStates.getDefaultStates());
                        }
                    }
                    setFocusStyle() {
                        if (this.source.cssStates.hasFocusStates) {
                            this.styleInjector.addStyle("button:focus", this.source.cssStates.getFocusStates());
                        }
                    }
                    setHoverStyle() {
                        if (this.source.cssStates.hasHoverStates) {
                            this.styleInjector.addStyle("button:hover", this.source.cssStates.getHoverStates());
                        }
                    }
                    setInactiveStyle() {
                        if (this.source.cssStates.hasInactiveStates) {
                            this.styleInjector.addStyle("button:disabled", this.source.cssStates.getInactiveStates());
                        }
                    }
                };
                DecisionButton = __decorate([
                    Jade.UI.Controls.toolingTags("form-field", "element")
                ], DecisionButton);
                Process.DecisionButton = DecisionButton;
            })(Process = Design.Process || (Design.Process = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Process;
            (function (Process) {
                class ProcessDecisions extends Design.ElementViewBase {
                    template() {
                        return `<div class="-pdjs-canvas-process-decisions" style="position:absolute;inset:0;" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessDecisions({});
                        this.controls.add(this.m_view);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_view.load(this.getDesignerData());
                    }
                    getDesignerData() {
                        let result = this.source.toJSON();
                        result.currentKey = Canvas.Shared.Process.DataSet.currentKey;
                        result.currentStage = Canvas.Shared.Process.DataSet.currentStage;
                        result.currentStatus = Canvas.Shared.Process.DataSet.currentStatus;
                        result.decisions = Canvas.Shared.Process.DataSet.selectedStageDecisions;
                        return result;
                    }
                }
                Process.ProcessDecisions = ProcessDecisions;
            })(Process = Design.Process || (Design.Process = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Process;
            (function (Process) {
                let ProcessState = class ProcessState extends Design.ElementViewBase {
                    template() {
                        return `<div class="-pdjs-canvas-process-state" style="position:absolute;top:0;left:0;right:0;bottom:0;" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessState({});
                        this.controls.add(this.m_view);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_view.load(this.getDesignerData());
                    }
                    getDesignerData() {
                        let result = this.source.toJSON();
                        result.processName = Canvas.Shared.Process.DataSet.currentProcess;
                        result.currentKey = Canvas.Shared.Process.DataSet.currentKey;
                        result.currentStage = Canvas.Shared.Process.DataSet.currentStage;
                        result.currentStatus = Canvas.Shared.Process.DataSet.currentStatus;
                        this.setDimensions(result);
                        return result;
                    }
                    setDimensions(data) {
                        this.source.height = this.source.absoluteHeight;
                        this.source.minHeight = this.source.absoluteHeight;
                        this.source.maxHeight = this.source.absoluteHeight;
                    }
                };
                ProcessState = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w)
                ], ProcessState);
                Process.ProcessState = ProcessState;
            })(Process = Design.Process || (Design.Process = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Process;
            (function (Process) {
                class ProcessView extends Design.ElementViewBase {
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_view = new PDJS.Canvas.Shared.Process.ProcessView({});
                        this.controls.add(this.m_view);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_view.load(this.getDesignerData());
                        this.setDecisionDestinationVisibility();
                    }
                    getDesignerData() {
                        let result = this.source.toJSON();
                        this.source.suspendStateChanged = true;
                        this.source.minHeight = (result.showKeys ? result.keyHeight : 0) +
                            (result.showStages ? result.stageHeight : 0) +
                            (result.showDecisions ? 150 : 0) +
                            (result.showState ? 40 : 0);
                        if (!result.showStages) {
                            this.source.maxHeight = (result.showKeys ? result.keyHeight : 0) +
                                (result.showDecisions ? 150 : 0) +
                                (result.showState ? 40 : 0);
                        }
                        else {
                            this.source.maxHeight = null;
                        }
                        this.source.suspendStateChanged = false;
                        result.currentKey = Canvas.Shared.Process.DataSet.currentKey;
                        result.currentStage = Canvas.Shared.Process.DataSet.currentStage;
                        result.currentStatus = Canvas.Shared.Process.DataSet.currentStatus;
                        result.keys = Canvas.Shared.Process.DataSet.keys;
                        result.stages = Canvas.Shared.Process.DataSet.stages;
                        return result;
                    }
                    setDecisionDestinationVisibility() {
                        if (this.source.showDecisionDestinations) {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .events
                                .publish(Canvas.Shared.Process.ProcessEvent.DecisionsMap, {
                                maps: Canvas.Shared.Process.DataSet.selectedStageDecisionMaps
                            });
                        }
                        else {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .events
                                .publish(Canvas.Shared.Process.ProcessEvent.DecisionsMap, {
                                maps: []
                            });
                        }
                    }
                }
                Process.ProcessView = ProcessView;
            })(Process = Design.Process || (Design.Process = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ArrangeRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Arrange", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:gridlines/toggle"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/standard:selection/bring-forward"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/standard:selection/send-back"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            label: "Alignment",
                            tooltip: "Automatically align or distribute the selected elements.",
                            width: 80,
                            icon: Jade.IconSet.get("pdjs").resolve("object_alignment_left.png", Jade.IconSetSizeSpecificDirectory.x32),
                            menu: ["element-alignment"]
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:elements/auto-arrange"
                        }));
                    }
                }
                RibbonBar.ArrangeRibbonGroup = ArrangeRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ClipboardRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Clipboard", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/clipboard:clipboard/cut"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/clipboard:clipboard/copy"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/clipboard:clipboard/paste"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/clipboard:clipboard/duplicate"
                        }));
                    }
                }
                RibbonBar.ClipboardRibbonGroup = ClipboardRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class CodeAndStylesRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Scripts and Styles", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/internal-code"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/internal-styles"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/external-code-and-styles"
                        }));
                    }
                }
                RibbonBar.CodeAndStylesRibbonGroup = CodeAndStylesRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ElementRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Element", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:element/properties"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/standard:selection/delete"
                        }));
                    }
                }
                RibbonBar.ElementRibbonGroup = ElementRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class DocumentRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Document", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/save"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/settings"
                        }));
                    }
                }
                RibbonBar.DocumentRibbonGroup = DocumentRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class FormFieldBehaviorRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Behaviors", toolingId: "element" });
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            icon: Jade.IconSet.get("pdjs").resolve("keyboard_key_blank_large.png", Jade.IconSetSizeSpecificDirectory.x32),
                            label: "Set Tab Order",
                            tooltip: "Automatically set the tab order for the selected elements.",
                            menu: ["tab-index"]
                        }));
                    }
                }
                RibbonBar.FormFieldBehaviorRibbonGroup = FormFieldBehaviorRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class FormFieldRequiredRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Required Field", toolingId: "form-field" });
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:form-field/required/enable"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:form-field/required/disable"
                        }));
                    }
                }
                RibbonBar.FormFieldRequiredRibbonGroup = FormFieldRequiredRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class GroupingRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Grouping", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/standard:selection/group"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "canvas/standard:selection/ungroup"
                        }));
                    }
                }
                RibbonBar.GroupingRibbonGroup = GroupingRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class LineRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Line", toolingId: "line" });
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarSet({
                            width: 150,
                            items: [
                                new Jade.UI.Controls.RibbonBarButtonSmall({
                                    icon: Jade.IconSet.get("pdjs").resolve("shapes.png", Jade.IconSetSizeSpecificDirectory.x16),
                                    label: "Start",
                                    toolip: "Set the shape of the start cap of the selected line elements.",
                                    menu: ["start-cap-shape"]
                                }),
                                new Jade.UI.Controls.RibbonBarButtonSmall({
                                    icon: Jade.IconSet.get("pdjs").resolve("shapes.png", Jade.IconSetSizeSpecificDirectory.x16),
                                    label: "End",
                                    toolip: "Set the shape of the end cap of the selected line elements.",
                                    menu: ["end-cap-shape"]
                                }),
                                new Jade.UI.Controls.RibbonBarButtonSmall({
                                    commandId: "pdjs/canvas/standard:line/shape/scale-up"
                                }),
                                new Jade.UI.Controls.RibbonBarButtonSmall({
                                    commandId: "pdjs/canvas/standard:line/shape/scale-down"
                                })
                            ]
                        }));
                    }
                }
                RibbonBar.LineRibbonGroup = LineRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class RulesAndVariablesRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Rules and Variables", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/rules"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/variables"
                        }));
                    }
                }
                RibbonBar.RulesAndVariablesRibbonGroup = RulesAndVariablesRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class StyleRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Style", toolingId: "style" });
                        this.shouldAlwaysShow(true);
                    }
                    onActivate(e) {
                        this.controls.add(new Design.ShapeRibbonSet({}));
                    }
                }
                RibbonBar.StyleRibbonGroup = StyleRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class TriangleRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "Triangle", toolingId: "triangle" });
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            label: "Rotate Left",
                            tooltip: "Rotate the selected shapes to the left (counter-clockwise).",
                            icon: "rotate_left.png",
                            commandId: "pdjs/canvas/standard:shape/rotate",
                            value: 0
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            label: "Rotate Right",
                            tooltip: "Rotate the selected shapes to the right (clockwise).",
                            icon: "rotate_right.png",
                            commandId: "pdjs/canvas/standard:shape/rotate",
                            value: 1
                        }));
                    }
                }
                RibbonBar.TriangleRibbonGroup = TriangleRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ViewRibbonGroup extends Jade.UI.Controls.RibbonBarGroup {
                    constructor() {
                        super({ label: "View", toolingId: "view" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onActivate(e) {
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:view/designer"
                        }));
                    }
                }
                RibbonBar.ViewRibbonGroup = ViewRibbonGroup;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class FormFieldRibbonSection extends Jade.UI.Controls.RibbonBarSection {
                    constructor() {
                        super({ label: "Forms", toolingId: "form-field" });
                    }
                    onPopulate() {
                        this.groups.add(new RibbonBar.FormFieldRequiredRibbonGroup());
                        this.groups.add(new RibbonBar.FormFieldBehaviorRibbonGroup());
                        this.groups.add(new RibbonBar.ArrangeRibbonGroup());
                        this.groups.add(new RibbonBar.GroupingRibbonGroup());
                    }
                }
                RibbonBar.FormFieldRibbonSection = FormFieldRibbonSection;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class HomeRibbonSection extends Jade.UI.Controls.RibbonBarSection {
                    constructor() {
                        super({ label: "Canvas", toolingId: "element" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onPopulate() {
                        this.groups.add(new RibbonBar.DocumentRibbonGroup());
                        this.groups.add(new RibbonBar.ClipboardRibbonGroup());
                        this.groups.add(new RibbonBar.ArrangeRibbonGroup());
                        this.groups.add(new RibbonBar.GroupingRibbonGroup());
                        this.groups.add(new RibbonBar.ElementRibbonGroup());
                        this.groups.add(new RibbonBar.StyleRibbonGroup());
                    }
                }
                RibbonBar.HomeRibbonSection = HomeRibbonSection;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class CodeAndStylesRibbonSection extends Jade.UI.Controls.RibbonBarSection {
                    constructor() {
                        super({ label: "Code and Styles", toolingId: "scripts-and-styles" });
                    }
                    get alwaysShow() {
                        return true;
                    }
                    onPopulate() {
                        this.groups.add(new RibbonBar.RulesAndVariablesRibbonGroup());
                        this.groups.add(new RibbonBar.CodeAndStylesRibbonGroup());
                    }
                }
                RibbonBar.CodeAndStylesRibbonSection = CodeAndStylesRibbonSection;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ShapeRibbonSection extends Jade.UI.Controls.RibbonBarSection {
                    constructor() {
                        super({ label: "Shapes", toolingId: "shape" });
                    }
                    onPopulate() {
                        this.groups.add(new RibbonBar.TriangleRibbonGroup());
                        this.groups.add(new RibbonBar.LineRibbonGroup());
                        this.groups.add(new RibbonBar.ArrangeRibbonGroup());
                        this.groups.add(new RibbonBar.GroupingRibbonGroup());
                    }
                }
                RibbonBar.ShapeRibbonSection = ShapeRibbonSection;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var RibbonBar;
            (function (RibbonBar) {
                class ViewRibbonSection extends Jade.UI.Controls.RibbonBarSection {
                    constructor() {
                        super({ label: "View", toolingId: "view" });
                    }
                    onPopulate() {
                        this.groups.add(new RibbonBar.ViewRibbonGroup());
                    }
                }
                RibbonBar.ViewRibbonSection = ViewRibbonSection;
            })(RibbonBar = Design.RibbonBar || (Design.RibbonBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            class ShapeRibbonSet extends Jade.UI.Controls.RibbonBarSet {
                constructor(options) {
                    super(options);
                    this.subscriptions.add(CanvasJS.Design.Environment
                        .events
                        .subscribe(CanvasJS.Design.CanvasEvent.SELECTION_CHANGE, () => {
                        var enabled = false;
                        CanvasJS
                            .Design
                            .Environment
                            .selection
                            .each((view) => {
                            if (view.tooling.contains("style")) {
                                enabled = true;
                                return false;
                            }
                        });
                        this.controls.each((control) => {
                            if (control instanceof Jade.UI.Controls.RibbonBarButtonSmall) {
                                control.enabled = enabled;
                            }
                        });
                    }));
                }
                onPopulate() {
                    this.controls.add(new Jade.UI.Controls.RibbonBarButtonSmall({
                        label: "Background",
                        tooltip: "Set the background color of the selected elements.",
                        icon: Jade.IconSet.get("pdjs").resolve("paint_bucket.png", Jade.IconSetSizeSpecificDirectory.x16),
                        menu: ["color-palette"],
                        enabled: false
                    }));
                    this.controls.add(new Jade.UI.Controls.RibbonBarButtonSmall({
                        label: "Border",
                        tooltip: "Set the border color, style, or weight of the selected elements.",
                        icon: Jade.IconSet.get("pdjs").resolve("marker.png", Jade.IconSetSizeSpecificDirectory.x16),
                        menu: ["shape-border"],
                        enabled: false
                    }));
                }
            }
            Design.ShapeRibbonSet = ShapeRibbonSet;
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class Shape extends CanvasJS.Design.ElementDesignViewBase {
                }
                Shapes.Shape = Shape;
                let ShapeBase = class ShapeBase extends Shape {
                    get source() {
                        return this.m_source;
                    }
                    get containerNode() {
                        return this.node.find("[role=container]");
                    }
                    template() {
                        return `<div style="position:absolute;top:0;left:0;right:0;bottom:0;" role="container" data-controls></div>`;
                    }
                };
                ShapeBase = __decorate([
                    Jade.UI.Controls.toolingTags("style")
                ], ShapeBase);
                Shapes.ShapeBase = ShapeBase;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class Ellipse extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        this.m_shape = new Canvas.Shared.Shapes.Ellipse({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth
                        });
                        this.controls.add(this.m_shape);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_shape.backgroundColor = this.source.backgroundColor;
                        this.m_shape.borderColor = this.source.borderColor;
                        this.m_shape.borderStyle = this.source.borderStyle;
                        this.m_shape.borderWidth = this.source.borderWidth;
                    }
                }
                Shapes.Ellipse = Ellipse;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                let Line = class Line extends CanvasJS.Design.ElementDesignViewBase {
                    onInit(e) {
                        super.onInit(e);
                        this.m_shape = new Canvas.Shared.Shapes.Line({
                            endCapShape: this.source.endCapShape,
                            endCapColor: this.source.endCapColor,
                            endCapHeight: this.source.endCapHeight,
                            endCapWidth: this.source.endCapWidth,
                            lineColor: this.source.lineColor,
                            lineWeight: this.source.lineWeight,
                            startCapColor: this.source.startCapColor,
                            startCapHeight: this.source.startCapHeight,
                            startCapShape: this.source.startCapShape,
                            startCapWidth: this.source.startCapWidth
                        });
                        this.controls.add(this.m_shape);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_shape.lineColor = this.source.lineColor;
                        this.m_shape.lineWeight = this.source.lineWeight;
                        this.m_shape.startCapColor = this.source.startCapColor;
                        this.m_shape.startCapHeight = this.source.startCapHeight;
                        this.m_shape.startCapShape = this.source.startCapShape;
                        this.m_shape.startCapWidth = this.source.startCapWidth;
                        this.m_shape.endCapColor = this.source.endCapColor;
                        this.m_shape.endCapHeight = this.source.endCapHeight;
                        this.m_shape.endCapShape = this.source.endCapShape;
                        this.m_shape.endCapWidth = this.source.endCapWidth;
                        this.m_shape.redraw();
                        this.setArea({
                            height: Jade.Arithmetic.roundUp(this.source.currentMaxHeight < 10 ? 10 : this.source.currentMaxHeight, 5),
                            width: this.source.width
                        });
                    }
                };
                Line = __decorate([
                    CanvasJS.Design.allowedSizingHandles(CanvasJS.Design.GeometryBoxHandle.e, CanvasJS.Design.GeometryBoxHandle.w),
                    Jade.UI.Controls.toolingTags("shape", "line")
                ], Line);
                Shapes.Line = Line;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class Rectangle extends Shapes.ShapeBase {
                    onInit(e) {
                        super.onInit(e);
                        this.m_shape = new Canvas.Shared.Shapes.Rectangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            borderRadius: this.source.borderRadius
                        });
                        this.controls.add(this.m_shape);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_shape.backgroundColor = this.source.backgroundColor;
                        this.m_shape.borderColor = this.source.borderColor;
                        this.m_shape.borderStyle = this.source.borderStyle;
                        this.m_shape.borderWidth = this.source.borderWidth;
                        this.m_shape.borderRadius = this.source.borderRadius;
                    }
                }
                Shapes.Rectangle = Rectangle;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class Triangle extends Shapes.ShapeBase {
                }
                Shapes.Triangle = Triangle;
                let TriangleBase = class TriangleBase extends Triangle {
                    get source() {
                        return this.m_source;
                    }
                };
                TriangleBase = __decorate([
                    Jade.UI.Controls.toolingTags("shape", "triangle")
                ], TriangleBase);
                Shapes.TriangleBase = TriangleBase;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class IsoscelesTriangle extends Shapes.TriangleBase {
                    onInit(e) {
                        super.onInit(e);
                        this.m_shape = new Canvas.Shared.Shapes.IsoscelesTriangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            rotation: this.source.rotation,
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.controls.add(this.m_shape);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_shape.backgroundColor = this.source.backgroundColor;
                        this.m_shape.borderColor = this.source.borderColor;
                        this.m_shape.borderStyle = this.source.borderStyle;
                        this.m_shape.borderWidth = this.source.borderWidth;
                        this.m_shape.rotation = this.source.rotation;
                        this.m_shape.height = this.source.height;
                        this.m_shape.width = this.source.width;
                        this.m_shape.redraw();
                    }
                }
                Shapes.IsoscelesTriangle = IsoscelesTriangle;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Shapes;
            (function (Shapes) {
                class RightTriangle extends Shapes.TriangleBase {
                    onInit(e) {
                        super.onInit(e);
                        this.m_shape = new Canvas.Shared.Shapes.RightTriangle({
                            backgroundColor: this.source.backgroundColor,
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth,
                            rotation: this.source.rotation,
                            height: this.source.height,
                            width: this.source.width
                        });
                        this.controls.add(this.m_shape);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_shape.backgroundColor = this.source.backgroundColor;
                        this.m_shape.borderColor = this.source.borderColor;
                        this.m_shape.borderStyle = this.source.borderStyle;
                        this.m_shape.borderWidth = this.source.borderWidth;
                        this.m_shape.rotation = this.source.rotation;
                        this.m_shape.height = this.source.height;
                        this.m_shape.width = this.source.width;
                        this.m_shape.redraw();
                    }
                }
                Shapes.RightTriangle = RightTriangle;
            })(Shapes = Design.Shapes || (Design.Shapes = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var StatusBar;
            (function (StatusBar) {
                class Errors extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_erroredElements = new Jade.MappedCollection({
                            key: "ID"
                        });
                    }
                    get erroredElements() {
                        return this.m_erroredElements;
                    }
                    get errorsList() {
                        return this.m_errorsList;
                    }
                    get labelNode() {
                        return this.node.children("div[role=label]");
                    }
                    template() {
                        return `<div class="-pdjs-statusbar-errors">
                        <div role="label"></div>
                        <div role="popup" data-controls></div>
                    </div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.DOCUMENT_LOAD, () => { this.getErroredElements(); });
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.ELEMENT_DELETE, () => { this.getErroredElements(); });
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.ELEMENT_PASTE, () => { this.getErroredElements(); });
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.ELEMENT_CUT, () => { this.getErroredElements(); });
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.ELEMENT_EDIT, () => { this.getErroredElements(); });
                        this.subscriptions.add(CanvasJS.Design.CanvasEvent.TOOLBOX_ITEMS_ADD, () => { this.getErroredElements(); });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_errorsList = new StatusBar.ErrorsList({
                            anchor: this.node
                        });
                        this.controls.add(this.errorsList);
                        this.setIconAndText();
                        this.errorsList.refresh(this.erroredElements);
                        this.labelNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.errorsList.toggle();
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setIconAndText();
                        if (this.errorsList != null) {
                            this.errorsList.refresh(this.erroredElements);
                            if (this.erroredElements.count == 0) {
                                this.errorsList.hide();
                            }
                        }
                    }
                    getErroredElements() {
                        this.erroredElements.clear();
                        CanvasJS.Design.Environment
                            .document
                            .controls
                            .getByType(Design.ElementView)
                            .each((element) => {
                            if (element.source.hasErrors) {
                                this.erroredElements.add(element);
                            }
                        });
                        this.onStateChanged();
                    }
                    setIconAndText() {
                        if (this.labelNode == null) {
                            return;
                        }
                        let url = null;
                        let label = "";
                        if (this.erroredElements.count === 0) {
                            url = Jade.IconSet.get("pdjs").resolve("ok.png", Jade.IconSetSizeSpecificDirectory.x16);
                            label = "No errors.";
                        }
                        else {
                            url = Jade.IconSet.get("pdjs").resolve("error.png", Jade.IconSetSizeSpecificDirectory.x16);
                            label = `${this.erroredElements.count} errors.`;
                        }
                        this.labelNode.css({
                            backgroundImage: `url(${url})`
                        });
                        this.labelNode.text(label);
                    }
                }
                StatusBar.Errors = Errors;
            })(StatusBar = Design.StatusBar || (Design.StatusBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var StatusBar;
            (function (StatusBar) {
                class ErrorsList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get anchor() {
                        return this.state.get("anchor");
                    }
                    get popUpNode() {
                        return $(`#popup-${this.ID}`);
                    }
                    get itemsNode() {
                        return this.node.children("div[role=items]");
                    }
                    get closeNode() {
                        return this.node.find("div[role=title-close]");
                    }
                    show() {
                        Tipped.show(this.anchor);
                    }
                    hide() {
                        Tipped.hide(this.anchor);
                    }
                    toggle() {
                        Tipped.toggle(this.anchor);
                    }
                    refresh(erroredElements) {
                        this.controls.clear();
                        this.itemsNode.empty();
                        erroredElements.each((element) => {
                            this.controls.add(new StatusBar.ErrorsListItem({
                                element: element
                            }));
                        });
                        if (erroredElements.count == 0) {
                            this.itemsNode.append(`<table style="height:100%;width:100%;"><tr><td style="text-align:center;vertical-align:middle;font-size:13px;">No errors.</td></tr></table>`);
                        }
                    }
                    destroy() {
                        this.hide();
                        Tipped.remove(this.anchor.get(0));
                        this.node.closest(".tpd-tooltip").remove();
                        super.destroy();
                    }
                    template() {
                        return `<div class="-pdjs-statusbar-errors-list" style="height:350px;width:400px;">
                        <div role="title">
                            <div role="title-label">Errors</div>
                            <div role="title-close" style="background-image:url(${Jade.IconSet.get("pd").resolve("cancel_white.png", Jade.IconSetSizeSpecificDirectory.misc)})"></div>
                        </div>
                        <div role="items" data-controls></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.createPopUp();
                        this.closeNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.hide();
                        });
                    }
                    createPopUp() {
                        PDJS.Shared.PopOver.menu(this.anchor, `<div id="popup-${this.ID}" style="height:350px;width: 400px;"></div>`, {
                            hideOn: false,
                            offset: { x: -1, y: -3 },
                            position: {
                                target: "topright",
                                tooltip: "bottomright"
                            },
                            zIndex: 10004
                        });
                        this.show();
                        this.hide();
                        this.node.detach();
                        this.popUpNode.append(this.node);
                    }
                }
                StatusBar.ErrorsList = ErrorsList;
            })(StatusBar = Design.StatusBar || (Design.StatusBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var StatusBar;
            (function (StatusBar) {
                class ErrorsListItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get element() {
                        return this.state.get("element");
                    }
                    get itemsNode() {
                        return this.node.find("div[role=items]");
                    }
                    get buttonNode() {
                        return this.node.find("[role=resolve] button");
                    }
                    template() {
                        return `<div class="-pdjs-statusbar-errors-list-item" style="position:relative;">
                        <div role="title">${this.element.source.componentName}</div>
                        <div role="items" data-controls></div>
                        <div role="resolve" style="position:absolute;right:0;top:10px;padding:5px;box-sizing:border-box;"><button>Resolve</button></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.setIcon();
                        _.each(this.element.source.errors, (item) => {
                            this.itemsNode.append(`<div>${item.message}<div>`);
                        });
                        this.node.on(Jade.BrowserEvent.CLICK, "div[role=title], div[role=items]", _.bind(this.onClick, this));
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.resolveOnClick, this));
                    }
                    onClick(e) {
                        this.selectElement();
                    }
                    resolveOnClick(e) {
                        e.cancelBubble = true;
                        e.preventDefault();
                        this.selectElement();
                        if (this.element.source.hasNonRecoverableErrors) {
                            this.deleteElement();
                        }
                        else {
                            this.recoverElement();
                        }
                    }
                    deleteElement() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                            title: "Delete Unrecoverable Element",
                            message: "This element has unrecoverable errors and should be deleted. Proceed with deleting this element?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                                    CanvasJS.Design.Environment.document.controls.remove(this.element);
                                    CanvasJS.Design.Environment.context.commands.execute("canvas/standard:selection/delete", {
                                        suppressConfirmation: true
                                    });
                                }
                            }
                        });
                    }
                    recoverElement() {
                        CanvasJS.Design.Environment
                            .context
                            .commands
                            .execute("pdjs/canvas/standard:element/properties");
                    }
                    selectElement() {
                        CanvasJS.Design.Environment.selection.clear();
                        CanvasJS.Design.Environment.selection.add(this.element);
                        CanvasJS.Design.Environment.selection.box.hide();
                        CanvasJS.Design.Environment.selection.box.show();
                    }
                    setIcon() {
                        let iconName = this.element.source.hasNonRecoverableErrors ? "skull.png" : "error.png";
                        let iconPath = Jade.IconSet.get("pdjs")
                            .resolve(iconName, Jade.IconSetSizeSpecificDirectory.x24);
                        this.node.css({
                            backgroundImage: `url(${iconPath})`
                        });
                    }
                }
                StatusBar.ErrorsListItem = ErrorsListItem;
            })(StatusBar = Design.StatusBar || (Design.StatusBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var StatusBar;
            (function (StatusBar) {
                class Theme extends Jade.UI.Control {
                    get selectNode() {
                        return this.node.find("select");
                    }
                    constructor(options = {}) {
                        super(options);
                    }
                    template() {
                        return `<div class="-pdjs-statusbar-theme">
                        <div role="label">Theme:</div>
                        <div role="input">
                            <select></select>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.onThemeChange(this.selectNode.val());
                        });
                        this.populateThemes();
                    }
                    onThemeChange(themeId) {
                        PDJS.Shared.Themes.Theme.canvas.switchTheme(themeId);
                    }
                    populateThemes() {
                        let service = new PDJS.Services.Themes.ThemeService();
                        service.list({
                            enabledOnly: true,
                            success: (e) => {
                                this.selectNode.append(`<option value="">- Current Hub Theme -</option>`);
                                e.data.forEach(item => {
                                    this.selectNode.append(`<option value="${item.id}">${item.name}</option>`);
                                });
                            }
                        });
                    }
                }
                StatusBar.Theme = Theme;
            })(StatusBar = Design.StatusBar || (Design.StatusBar = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class ToolBoxAction extends CanvasJS.Design.ToolBoxAction {
                    createStates(args) {
                        let states = [];
                        let x = args.x;
                        let y = args.y;
                        let count = 0;
                        let success = (state) => {
                            if (state != null) {
                                states.push(_.extend(state, {
                                    id: Jade.Guid.new(),
                                    x: x,
                                    y: y
                                }));
                                x += 20;
                                y += 20;
                            }
                            count += 1;
                            if (count == args.items.length) {
                                this.initElements(states);
                            }
                        };
                        args.items.forEach(item => {
                            this.createState(_.clone(item), success);
                        });
                    }
                    createState(item, success) {
                        success({});
                    }
                    initElements(states) {
                        let document = CanvasJS.Design.Environment.document;
                        let service = new PDJS.Services.Canvas.ElementService();
                        service.createDesignElements({
                            sessionId: document.source.sessionId,
                            documentId: document.source.id,
                            elements: states,
                            success: (e) => {
                                this.createElements(e.data);
                            }
                        });
                    }
                    createElements(states) {
                        let elements = [];
                        states.forEach(state => {
                            let success = (element) => {
                                if (element) {
                                    elements.push(element);
                                }
                            };
                            this.createElement(state, success);
                        });
                        this.appendElements(elements);
                    }
                    createElement(state, success) {
                        success(null);
                    }
                    appendElements(elements) {
                        CanvasJS.Design.Environment.selection.clear();
                        elements.forEach(element => {
                            CanvasJS.Design.Environment.selection.add(element);
                            this.fireToolBoxItemAddedEvent({
                                elements: elements,
                                item: this
                            });
                        });
                        CanvasJS.Design.Environment.selection.box.show();
                    }
                }
                ToolBox.ToolBoxAction = ToolBoxAction;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class BatchFieldAction extends ToolBox.ToolBoxAction {
                    get instance() {
                        return this.parameters["instance"];
                    }
                    get batchFieldType() {
                        return this.m_batchFieldType;
                    }
                    set batchFieldType(value) {
                        this.m_batchFieldType = value;
                    }
                    execute(e) {
                        ToolBox.BatchFieldActionDialog.open({
                            select: {
                                ok: (sender, e2) => {
                                    sender.close();
                                    this.batchFieldType = e2.batchFieldType;
                                    this.createStates({
                                        items: [this.instance],
                                        x: e.x,
                                        y: e.y
                                    });
                                }
                            }
                        });
                    }
                    createState(item, success) {
                        let result = _.extend({}, item, {
                            selectIdentities: this.batchFieldType == ToolBox.BatchFieldType.Identities,
                        });
                        success(result);
                    }
                    createElement(state) {
                        return CanvasJS.Design.Environment.document.createElementOf(state, true);
                    }
                }
                ToolBox.BatchFieldAction = BatchFieldAction;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                let BatchFieldType;
                (function (BatchFieldType) {
                    BatchFieldType[BatchFieldType["Entities"] = 0] = "Entities";
                    BatchFieldType[BatchFieldType["Identities"] = 1] = "Identities";
                })(BatchFieldType = ToolBox.BatchFieldType || (ToolBox.BatchFieldType = {}));
                class BatchFieldActionDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get entitiesButton() {
                        return this.node.find("[data-role=entities]");
                    }
                    get identitiesButton() {
                        return this.node.find("[data-role=identities]");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.entitiesButton.on("click", _.bind(this.entitiesButton_onClick, this));
                        this.identitiesButton.on("click", _.bind(this.identitiesButton_onClick, this));
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-canvas-design-toolbox-batch-field-action-dialog">
                        <div data-role="grid">
                            <div>
                                <button data-role="entities">
                                    <img src="${Jade.IconSet.get("pdjs").resolve("objects.png", Jade.IconSetSizeSpecificDirectory.x64)}"/><br/>
                                    Entities
                                </button>
                            </div>
                            <div>
                                <button data-role="identities">
                                    <img src="${Jade.IconSet.get("pdjs").resolve("users.png", Jade.IconSetSizeSpecificDirectory.x64)}"/><br/>
                                    Users / Groups
                                </button>
                            </div>
                        </div>
                    </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Batch Field Type",
                            height: 150,
                            width: 350
                        };
                    }
                    entitiesButton_onClick(e) {
                        this.m_selection = BatchFieldType.Entities;
                        this.returnSelected();
                    }
                    identitiesButton_onClick(e) {
                        this.m_selection = BatchFieldType.Identities;
                        this.returnSelected();
                    }
                    returnSelected() {
                        if (this.m_selection == null) {
                            alert("No batch field type was selected!");
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: {
                                batchFieldType: this.m_selection
                            }
                        });
                    }
                    static open(options) {
                        return new BatchFieldActionDialog(options);
                    }
                }
                ToolBox.BatchFieldActionDialog = BatchFieldActionDialog;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class FormFieldAction extends ToolBox.ToolBoxAction {
                    get fieldMap() {
                        return this.parameters["fieldMap"];
                    }
                    execute(e) {
                        let document = CanvasJS.Design.Environment.document;
                        ToolBox.FormFieldActionDialog.open({
                            extensionId: document.extensionId,
                            canvasType: document.canvasType,
                            select: {
                                ok: (sender, result) => {
                                    sender.close();
                                    this.createStates({
                                        items: result,
                                        x: e.x,
                                        y: e.y
                                    });
                                }
                            }
                        });
                    }
                    createState(item, success) {
                        let state = _.clone(this.fieldMap[item.fieldType]);
                        let result = _.extend(state, {
                            columnId: item.columnId,
                            columnFormat: item.columnFormat,
                            defaultLabel: item.columnName
                        });
                        success(result);
                    }
                    createElement(state, success) {
                        success(CanvasJS.Design.Environment.document.createElementOf(state, true));
                    }
                }
                ToolBox.FormFieldAction = FormFieldAction;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class FormFieldActionDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get grid() {
                        return this.state.get("grid");
                    }
                    get canvasType() {
                        return this.state.get("canvasType");
                    }
                    get extensionId() {
                        return this.state.get("extensionId");
                    }
                    get okButton() {
                        return this.node.find("[data-role=ok]");
                    }
                    get cancelButton() {
                        return this.node.find("[data-role=cancel]");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_onActivate();
                        this.okButton.on("click", _.bind(this.okButton_onClick, this));
                        this.cancelButton.on("click", _.bind(this.cancelButton_onClick, this));
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-form-field-selection-dialog">
                    <div data-role="grid"></div>
                    <div data-role="deck">
                        <button class="-jadeui-dialog-button" data-role="ok">OK</button>
                        <button class="-jadeui-dialog-button" data-role="cancel">Cancel</button>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Form Field | Select",
                            height: 500,
                            width: 650
                        };
                    }
                    okButton_onClick(e) {
                        this.returnSelected();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    grid_onActivate() {
                        let type = Jade.Type.getType("PD.Web.UI.Controls.ViewGrid");
                        let grid = new type({
                            container: `#${this.ID} DIV[data-role=grid]`,
                            viewStateId: this.state.get("viewStateId"),
                            selection: {
                                map: function (e) {
                                    return _.map(e.selections.toArray(), (item) => {
                                        return {
                                            columnId: item.ColumnID,
                                            columnName: item.ColumnName,
                                            columnFormat: item.ColumnFormat,
                                            fieldType: item.ObjectType
                                        };
                                    });
                                }
                            },
                            defaultSelectionEnabled: false,
                            selectionMode: "multiple",
                            needContext: (e) => {
                                e.addFilter(PDJS.Core.Views.FormFieldFilter.listData(this.canvasType == Canvas.Core.CanvasType.List).toJSON());
                                if (this.canvasType == Canvas.Core.CanvasType.DocumentType) {
                                    e.addFilter(PDJS.Core.Views.FormFieldFilter.fileBased().toJSON());
                                }
                                if (this.canvasType == Canvas.Core.CanvasType.List) {
                                    e.addFilter(PDJS.Core.Views.FormFieldFilter.extension(this.extensionId).toJSON());
                                }
                            },
                            dblclick: (e) => {
                                this.returnSelected();
                            }
                        });
                        this.state.set({
                            grid: grid
                        });
                    }
                    returnSelected() {
                        let fields = this.grid.getSelections().toArray();
                        if (fields.length == 0) {
                            alert("No selections hae been made!");
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: fields
                        });
                    }
                    static open(options) {
                        let result = null;
                        PDJS.Ajax.call({
                            url: Jade.Path.resolve("~/Manage/Canvas/ToolBox/FormFieldSelection"),
                            success: (e) => {
                                let args = _.extend(options, {
                                    viewStateId: e.viewStateId
                                });
                                new FormFieldActionDialog(args);
                            }
                        });
                        return result;
                    }
                }
                ToolBox.FormFieldActionDialog = FormFieldActionDialog;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class ImageAction extends ToolBox.ToolBoxAction {
                    get template() {
                        return this.parameters["template"];
                    }
                    execute(e) {
                        PDJS.Manage.Resources.SelectFileDialog.open({
                            title: "Select | Image",
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                            extensions: [".jpeg", ".jpg", ".png", ".bmp", ".gif"],
                            select: {
                                ok: (sender, result) => {
                                    sender.close();
                                    this.createStates({
                                        items: result,
                                        x: e.x,
                                        y: e.y
                                    });
                                }
                            }
                        });
                    }
                    createState(item, success) {
                        let state = _.clone(this.template);
                        let result = _.extend(state, {
                            imageUrl: item.path,
                        });
                        this.getImageDimensions(item.path, (e) => {
                            result.height = e.height;
                            result.width = e.width;
                            success(result);
                        });
                    }
                    createElement(state, success) {
                        success(CanvasJS.Design.Environment.document.createElementOf(state, true));
                    }
                    getImageDimensions(imageUrl, callback) {
                        let path = `${Jade.Path.resolve("~/Resources")}${imageUrl}`;
                        const getMeta = (url, callback) => {
                            const img = new Image();
                            img.onload = () => callback(null, img);
                            img.onerror = (err) => callback(err);
                            img.src = url;
                        };
                        getMeta(path, (err, img) => {
                            callback({
                                height: img != null ? this.roundToNearestGridDimension(img.naturalHeight) : 100,
                                width: img != null ? this.roundToNearestGridDimension(img.naturalWidth) : 150
                            });
                        });
                    }
                    roundToNearestGridDimension(number) {
                        return Math.round(number / 5) * 5;
                    }
                }
                ToolBox.ImageAction = ImageAction;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var ToolBox;
            (function (ToolBox) {
                class ToolBoxElementValidated extends CanvasJS.Design.ToolBoxElement {
                    execute(e) {
                        let state = _.extend(this.instance, {
                            id: Jade.Guid.new(),
                            x: e.x + CanvasJS.Design.Environment.gridUnit,
                            y: e.y + CanvasJS.Design.Environment.gridUnit
                        });
                        this.validateState(state, (states) => {
                            let element = CanvasJS.Design.Environment.document.createElement(states[0], true);
                            if (element) {
                                CanvasJS.Design.Environment.selection.clear();
                                CanvasJS.Design.Environment.selection.add(element);
                                CanvasJS.Design.Environment.selection.box.show();
                                this.fireToolBoxItemAddedEvent({
                                    elements: [element],
                                    item: this
                                });
                            }
                        });
                    }
                    validateState(state, onSuccess) {
                        let document = CanvasJS.Design.Environment.document;
                        if (!state.isCreatable) {
                            onSuccess([state]);
                            return;
                        }
                        let service = new PDJS.Services.Canvas.ElementService();
                        service.createDesignElements({
                            sessionId: document.source.sessionId,
                            documentId: document.source.id,
                            elements: [state],
                            success: (e) => {
                                onSuccess(e.data);
                            }
                        });
                    }
                }
                ToolBox.ToolBoxElementValidated = ToolBoxElementValidated;
            })(ToolBox = Design.ToolBox || (Design.ToolBox = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Views;
            (function (Views) {
                class IViewComponentGridGuard extends Jade.InterfaceGuard {
                    get signature() {
                        return {
                            id: "b510bb96-40d5-4efb-970d-c9611f3274c0",
                            label: "IViewComponentGridGuard"
                        };
                    }
                }
                Views.IViewComponentGridGuard = IViewComponentGridGuard;
            })(Views = Shared.Views || (Shared.Views = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Views;
            (function (Views) {
                let EventHistoryView = class EventHistoryView extends Design.ElementViewBase {
                    get grid() {
                        return this.m_grid;
                    }
                    get viewStateId() {
                        return this.source.viewStateId;
                    }
                    template() {
                        return `<div style="position:absolute;inset:0;" role="grid"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.redrawGrid();
                    }
                    onResize() {
                        super.onResize();
                        this.redrawGrid();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.children("[role=grid]"),
                            height: "100%",
                            viewStateId: this.source.viewStateId
                        });
                    }
                    redrawGrid() {
                        if (this.grid != null) {
                            this.grid.redraw();
                        }
                    }
                };
                EventHistoryView = __decorate([
                    Jade.InterfaceGuard.implement(Canvas.Shared.Views.IViewComponentGuard, Canvas.Shared.Views.IViewComponentGridGuard),
                    Jade.UI.Controls.toolingTags("view")
                ], EventHistoryView);
                Views.EventHistoryView = EventHistoryView;
            })(Views = Design.Views || (Design.Views = {}));
        })(Design = Canvas.Design || (Canvas.Design = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            let CanvasCss;
            (function (CanvasCss) {
                CanvasCss["FormField"] = "-pdjs-canvas-form-field";
                CanvasCss["FormFieldFocus"] = "-pdjs-canvas-form-field-focus";
                CanvasCss["FormFieldAnimationTarget"] = "-pdjs-canvas-form-field-animation-target";
                CanvasCss["SingleSelectField"] = "-pdjs-canvas-ssl-field";
                CanvasCss["MultiSelectField"] = "-pdjs-canvas-msl-field";
                CanvasCss["EntityField"] = "-pdjs-canvas-entity-field";
                CanvasCss["UserField"] = "-pdjs-canvas-user-field";
                CanvasCss["StringField"] = "-pdjs-canvas-string-field";
                CanvasCss["BooleanField"] = "-pdjs-canvas-boolean-field";
                CanvasCss["DateField"] = "-pdjs-canvas-date-field";
                CanvasCss["NumericField"] = "-pdjs-canvas-numeric-field";
                CanvasCss["TextElement"] = "-pdjs-text-element";
                CanvasCss["BatchField"] = "-pdjs-batch-field";
                CanvasCss["Disabled"] = "-pdjs-disabled";
            })(CanvasCss = Shared.CanvasCss || (Shared.CanvasCss = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class CssInjector {
                constructor(options) {
                    this.m_id = options.id;
                }
                get id() {
                    return this.m_id;
                }
                get styles() {
                    return this.m_styles;
                }
                set styles(value) {
                    this.m_styles = value;
                }
                add(e) {
                }
                remove() {
                    $(`#${this.id}`);
                }
                render(control) {
                    let style = ``;
                    let regex = new RegExp(/(a-z)*([A-Z])(a-z)*/g);
                    for (let clazz in this.styles) {
                        clazz.replace(regex, (match, $1, $2, $3) => {
                            return `${$1}${"-" + $2.toLowerCase()}${$3}`;
                        });
                    }
                }
            }
            Shared.CssInjector = CssInjector;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class ElementBar extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get source() {
                    return this.state.get("source");
                }
                cacheLastUpdatedFormatted() {
                    return kendo.toString(new Date(this.source.cacheLastUpdated), "g");
                }
                get visible() {
                    return this.state.get("visible");
                }
                set visible(value) {
                    this.state.set("visible", value);
                }
                get showRefresh() {
                    return this.state.get("showRefresh", false);
                }
                set showRefresh(value) {
                    this.state.set("showRefresh", value);
                }
                get onRefreshCallback() {
                    return this.state.get("onRefresh", () => { });
                }
                get refreshNode() {
                    return this.node.find("span[role=refresh]");
                }
                template() {
                    return `<div class="-pdjs-canvas-shared-element-bar"></div>`;
                }
                update() {
                    this.updateUI();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.on(Jade.BrowserEvent.CLICK, "span[role=refresh]", () => {
                        this.onRefreshCallback();
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.updateUI();
                }
                updateUI() {
                    let text = null;
                    if (this.visible) {
                        this.node.show();
                    }
                    else {
                        this.node.hide();
                    }
                    text = `<b>As of:</b> ${this.cacheLastUpdatedFormatted()}`;
                    if (this.showRefresh) {
                        text = `${text}<span role="refresh">Refresh</span>`;
                    }
                    this.node.empty();
                    this.node.append(text);
                }
            }
            Shared.ElementBar = ElementBar;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            let VerticalAlign;
            (function (VerticalAlign) {
                VerticalAlign["top"] = "flex-start";
                VerticalAlign["middle"] = "center";
                VerticalAlign["bottom"] = "flex-end";
            })(VerticalAlign || (VerticalAlign = {}));
            let HorizontalAlign;
            (function (HorizontalAlign) {
                HorizontalAlign["left"] = "flex-start";
                HorizontalAlign["center"] = "center";
                HorizontalAlign["right"] = "flex-end";
            })(HorizontalAlign || (HorizontalAlign = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            let ElementMenuPosition;
            (function (ElementMenuPosition) {
                ElementMenuPosition[ElementMenuPosition["topLeft"] = 0] = "topLeft";
                ElementMenuPosition[ElementMenuPosition["topRight"] = 1] = "topRight";
                ElementMenuPosition[ElementMenuPosition["bottomLeft"] = 2] = "bottomLeft";
                ElementMenuPosition[ElementMenuPosition["bottomRight"] = 3] = "bottomRight";
            })(ElementMenuPosition = Shared.ElementMenuPosition || (Shared.ElementMenuPosition = {}));
            class ElementMenu extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.state.unset("source");
                    this.m_items = new Jade.ObservableMappedCollection({
                        key: "ID",
                        callbacks: {
                            onAfterAdd: (e) => {
                                e.item.menu = this;
                                if (this.popUp != null) {
                                    this.popUp.controls.add(e.item);
                                }
                            },
                            onAfterRemove: (e) => {
                                e.item.menu = null;
                                if (this.popUp != null) {
                                    this.popUp.controls.remove(e.item);
                                }
                            }
                        }
                    });
                }
                get visible() {
                    return this.state.get("visible", true);
                }
                set visible(value) {
                    this.state.set("visible", value);
                }
                get position() {
                    return this.state.get("position", ElementMenuPosition.topRight);
                }
                set position(value) {
                    this.state.set("position", value);
                }
                get items() {
                    return this.m_items;
                }
                get loadedCallback() {
                    return this.state.get("loaded", () => { });
                }
                get popUp() {
                    return this.m_popUp;
                }
                template() {
                    return `<div class="-pdjs-canavas-element-menu">
                        <i class="icofont-navigation-menu"></i>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.m_popUp = new Shared.ElementMenuPopUp({
                        anchor: this.node,
                        init: () => {
                            this.items.each((item) => {
                                if (this.popUp.controls.getById(item.ID) == null) {
                                    this.popUp.controls.add(item);
                                }
                            });
                        }
                    });
                    this.controls.add(this.m_popUp);
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.loadedCallback();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.node.css({
                        top: this.positionTop(),
                        bottom: this.positionBottom(),
                        left: this.positionLeft(),
                        right: this.positionRight(),
                        display: this.visible ? "block" : "none"
                    });
                    this.node.attr("title", "Actions and Settings");
                }
                positionTop() {
                    return this.position == ElementMenuPosition.topLeft ||
                        this.position == ElementMenuPosition.topRight ? "5px" : null;
                }
                positionBottom() {
                    return this.position == ElementMenuPosition.bottomLeft ||
                        this.position == ElementMenuPosition.bottomRight ? "5px" : null;
                }
                positionLeft() {
                    return this.position == ElementMenuPosition.topLeft ||
                        this.position == ElementMenuPosition.bottomLeft ? "5px" : null;
                }
                positionRight() {
                    return this.position == ElementMenuPosition.topRight ||
                        this.position == ElementMenuPosition.bottomRight ? "5px" : null;
                }
            }
            Shared.ElementMenu = ElementMenu;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class ElementMenuItem extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get menu() {
                    return this.m_menu;
                }
                set menu(value) {
                    this.m_menu = value;
                }
                get visible() {
                    return this.state.get("visible", true);
                }
                set visible(value) {
                    this.state.set("visible", value);
                }
                get showCallback() {
                    return this.state.get("show", () => { });
                }
                show() {
                    this.showCallback(this);
                }
            }
            Shared.ElementMenuItem = ElementMenuItem;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class ElementMenuItemAction extends Shared.ElementMenuItem {
                constructor(options) {
                    super(options);
                }
                get icon() {
                    return this.state.get("icon");
                }
                set icon(value) {
                    this.state.set("icon", value);
                }
                get iconNode() {
                    return this.node.find("div[role=icon]");
                }
                get labelNode() {
                    return this.node.find("div[role=label]");
                }
                get label() {
                    return this.state.get("label", "");
                }
                set label(value) {
                    this.state.set("label", value);
                }
                get clickCallback() {
                    return this.state.get("click", () => { });
                }
                template() {
                    return `<div class="-pdjs-element-menu-item-action">
                        <div role="icon"></div>
                        <div role="label"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                        this.clickCallback();
                        this.menu.popUp.hide();
                    }, this));
                }
                onStateChanged() {
                    super.onStateChanged();
                    if (this.icon != null) {
                        this.iconNode.append(this.getIcon(this.icon));
                    }
                    this.labelNode.text(this.label);
                }
                getIcon(imageUrl) {
                    if (imageUrl == null)
                        return "";
                    imageUrl = imageUrl.toLowerCase();
                    if (!this.isFontIcon(imageUrl)) {
                        return `<img src="${imageUrl}">`;
                    }
                    return this.getFontIcon(imageUrl);
                }
                getFontIcon(imageUrl) {
                    let name = Jade.Path.getFileNameWithoutExtension(imageUrl);
                    let size = Jade.Path.getFileExtension(name).replace(".", "");
                    if (!Jade.String.isNullOrWhiteSpace(size)) {
                        name = Jade.Path.getFileNameWithoutExtension(name);
                        size = size;
                    }
                    else {
                        size = "12px";
                    }
                    return `<i class="icofont-${name}" style="font-size:${size};"></i>`;
                }
                isFontIcon(name) {
                    return Jade.Path.getFileExtension(name) == ".font";
                }
            }
            Shared.ElementMenuItemAction = ElementMenuItemAction;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class ElementMenuItemBoard extends Shared.ElementMenuItem {
                constructor(options) {
                    super(options);
                }
                get content() {
                    return this.state.get("content", "");
                }
                set content(value) {
                    this.state.set("content", value);
                }
                template() {
                    return `<div class="-pdjs-canavas-element-menu-item-board">${this.content}</div>`;
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.node.empty();
                    this.node.append(this.content);
                }
            }
            Shared.ElementMenuItemBoard = ElementMenuItemBoard;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            class ElementMenuPopUp extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_items = new Jade.ObservableMappedCollection({
                        key: "id"
                    });
                }
                get anchor() {
                    return this.state.get("anchor", $());
                }
                get hideCallback() {
                    return this.state.get("hide", () => { });
                }
                get showCallback() {
                    return this.state.get("show", () => { });
                }
                get initCallback() {
                    return this.state.get("init", () => { });
                }
                hide() {
                    Tipped.hide(this.anchor);
                    this.hideCallback();
                }
                show() {
                    Tipped.show(this.anchor);
                }
                template() {
                    return `<div></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.css({
                        boxSizing: "border-box",
                        width: "200px",
                        overflowY: "auto",
                        maxHeight: "300px"
                    });
                    PDJS.Shared.PopOver.menu(this.anchor, this.node, {
                        position: "bottomright",
                        showOn: "click",
                        onShow: () => {
                            this.showCallback();
                            this.controls.each((item) => {
                                item.show();
                            });
                        }
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.show();
                    this.hide();
                    this.initCallback();
                }
            }
            Shared.ElementMenuPopUp = ElementMenuPopUp;
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Charts;
            (function (Charts) {
                class ChartOptions {
                    constructor(options) {
                        this.m_state = null;
                        this.m_style = null;
                        this.m_state = new Jade.StateBag(options);
                        this.m_style = new Charts.ChartStyle(options);
                    }
                    get state() {
                        return this.m_state;
                    }
                    get style() {
                        return this.m_style;
                    }
                    get styleSource() {
                        return this.state.get("style");
                    }
                    get data() {
                        return this.state.get("data");
                    }
                    get series() {
                        var _a;
                        return ((_a = this.data) === null || _a === void 0 ? void 0 : _a.series) || [];
                    }
                    get categories() {
                        var _a;
                        return ((_a = this.data) === null || _a === void 0 ? void 0 : _a.categories) || [];
                    }
                    getOptions() {
                        return {
                            theme: "silver",
                            categoryAxis: this.getCategoryAxis(),
                            chartArea: this.style.chartArea,
                            legend: this.style.legend,
                            plotArea: this.style.plotArea,
                            series: this.getSeries(),
                            seriesDefaults: this.getSeriesDefaults(),
                            title: this.style.title,
                            tooltip: this.getTooltip(),
                            valueAxis: [this.getValueAxis()],
                            transitions: false
                        };
                    }
                    getCategoryAxis() {
                        return {};
                    }
                    getSeries() {
                        return {};
                    }
                    getValueAxis() {
                        return this.style.valueAxis;
                    }
                    getSeriesDefaults() {
                        return this.style.seriesDefaults;
                    }
                    getTooltip() {
                        return this.style.tooltip;
                    }
                }
                Charts.ChartOptions = ChartOptions;
            })(Charts = Shared.Charts || (Shared.Charts = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Charts;
            (function (Charts) {
                class ChartOptionsFactory {
                    static create(data) {
                        let result = null;
                        let type = data.seriesType;
                        switch (type) {
                            case "pie":
                                result = new Charts.PieChart(data);
                                break;
                            default:
                                result = new Charts.DefaultChart(data);
                                break;
                        }
                        return result;
                    }
                }
                Charts.ChartOptionsFactory = ChartOptionsFactory;
            })(Charts = Shared.Charts || (Shared.Charts = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Charts;
            (function (Charts) {
                class ChartStyle {
                    constructor(options) {
                        this.m_state = null;
                        this.m_state = new Jade.StateBag(options);
                    }
                    get state() {
                        return this.m_state;
                    }
                    get style() {
                        return this.state.get("style");
                    }
                    get categoryAxis() {
                        return this.getCategoryAxis();
                    }
                    get chartArea() {
                        return this.getChartArea();
                    }
                    get legend() {
                        return this.getLegend();
                    }
                    get plotArea() {
                        return this.getPlotArea();
                    }
                    get seriesDefaults() {
                        return this.getSeriesDefaults();
                    }
                    get title() {
                        return this.getTitle();
                    }
                    get tooltip() {
                        return this.getTooltip();
                    }
                    get valueAxis() {
                        return this.getValueAxis();
                    }
                    getCategoryAxis() {
                        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
                        let result = {
                            categories: [],
                            labels: {},
                            line: {},
                            title: {},
                            majorGridLines: {},
                            minorGridLines: {},
                            majorTicks: {},
                            minorTicks: {}
                        };
                        let categoryAxis = this.style.categoryAxis;
                        if (categoryAxis == null) {
                            return result;
                        }
                        let labels = (_a = this.style.categoryAxis) === null || _a === void 0 ? void 0 : _a.labels;
                        let line = (_b = this.style.categoryAxis) === null || _b === void 0 ? void 0 : _b.line;
                        let title = (_c = this.style.categoryAxis) === null || _c === void 0 ? void 0 : _c.title;
                        let majorGridLines = (_d = this.style.categoryAxis) === null || _d === void 0 ? void 0 : _d.majorGridLines;
                        let minorGridLines = (_e = this.style.categoryAxis) === null || _e === void 0 ? void 0 : _e.minorGridLines;
                        result.justified = false;
                        if (labels) {
                            result.labels.color = (_f = labels.color) !== null && _f !== void 0 ? _f : "var(--visiv-theme-canvas-chart-category-axis-label-text-color)";
                            result.labels.font = labels.fontSize + " " + labels.fontName;
                            result.labels.rotation = labels.rotation;
                            result.labels.visible = labels.visible;
                        }
                        if (line) {
                            result.line.color = (_g = line.color) !== null && _g !== void 0 ? _g : "var(--visiv-theme-canvas-chart-category-axis-line-color)";
                            result.line.width = line.width;
                            result.line.visible = line.visible;
                        }
                        if (title) {
                            result.title.color = (_h = title.color) !== null && _h !== void 0 ? _h : "var(--visiv-theme-canvas-chart-category-axis-title-text-color)";
                            result.title.font = `${title.fontSize} ${title.fontName}`;
                            result.title.position = title.position;
                            result.title.rotation = title.rotation;
                            result.title.text = title.text;
                            result.title.visible = title.visible;
                        }
                        if (majorGridLines) {
                            result.majorGridLines.color = (_j = majorGridLines.color) !== null && _j !== void 0 ? _j : "var(--visiv-theme-canvas-chart-category-axis-major-grid-line-color)";
                            result.majorGridLines.dashType = majorGridLines.dashType;
                            result.majorGridLines.visible = majorGridLines.visible;
                            result.majorTicks.visible = majorGridLines.tickMarks;
                        }
                        if (minorGridLines) {
                            result.minorGridLines.color = (_k = minorGridLines.color) !== null && _k !== void 0 ? _k : "var(--visiv-theme-canvas-chart-category-axis-minor-grid-line-color)";
                            result.minorGridLines.dashType = minorGridLines.dashType;
                            result.minorGridLines.visible = minorGridLines.visible;
                            result.minorTicks.visible = minorGridLines.tickMarks;
                        }
                        return result;
                    }
                    getChartArea() {
                        var _a;
                        let result = { border: {} };
                        let chartArea = this.style.chartArea;
                        if (chartArea == null) {
                            return result;
                        }
                        result.height = this.state.get("height", 250);
                        result.width = this.state.get("width", 400);
                        result.background = (_a = chartArea.backColor) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-area-back-color)";
                        result.margin = chartArea.margin;
                        return result;
                    }
                    getLegend() {
                        var _a;
                        let result = {
                            border: {},
                            labels: {}
                        };
                        let legend = this.style.legend;
                        if (legend == null) {
                            return result;
                        }
                        result.position = legend.position;
                        result.visible = legend.visible;
                        let border = this.style.legend.border;
                        let labels = this.style.legend.labels;
                        if (border) {
                            result.border.color = border.color;
                            result.border.width = border.width;
                        }
                        if (labels) {
                            result.labels.color = (_a = labels.color) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-legend-label-text-color)";
                            result.labels.font = `${labels.fontSize}  ${labels.fontName}`;
                        }
                        return result;
                    }
                    getPlotArea() {
                        var _a, _b;
                        var result = { border: {} };
                        let plotArea = this.style.plotArea;
                        if (plotArea == null) {
                            return result;
                        }
                        result.background = (_a = plotArea.backColor) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-plot-back-color)";
                        result.border.color = (_b = plotArea.borderColor) !== null && _b !== void 0 ? _b : "var(--visiv-theme-canvas-chart-plot-border-color)";
                        result.border.width = plotArea.borderWidth;
                        return result;
                    }
                    getSeriesDefaults() {
                        var _a, _b, _c, _d, _e, _f, _g, _h;
                        var result = {
                            overlay: {},
                            labels: {
                                border: {}
                            },
                            tooltip: {
                                border: {}
                            }
                        };
                        if (!this.style.series) {
                            return result;
                        }
                        let labels = (_a = this.style.series) === null || _a === void 0 ? void 0 : _a.labels;
                        let tooltip = (_b = this.style.series) === null || _b === void 0 ? void 0 : _b.tooltip;
                        result.overlay.gradient = this.style.series.gradient;
                        if (labels) {
                            result.labels.background = (_c = labels.backColor) !== null && _c !== void 0 ? _c : "var(--visiv-theme-canvas-chart-series-label-back-color)";
                            result.labels.border.color = (_d = labels.borderColor) !== null && _d !== void 0 ? _d : "var(--visiv-theme-canvas-chart-series-label-border-color)";
                            result.labels.border.width = labels.borderWidth;
                            result.labels.color = (_e = labels.color) !== null && _e !== void 0 ? _e : "var(--visiv-theme-canvas-chart-series-label-text-color)";
                            result.labels.font = `${labels.fontSize} ${labels.fontName}`;
                            result.labels.padding = labels.padding;
                            result.labels.visible = labels.visible;
                        }
                        if (tooltip) {
                            result.tooltip.background = (_f = tooltip.backColor) !== null && _f !== void 0 ? _f : "var(--visiv-theme-canvas-chart-series-tooltip-back-color)";
                            result.tooltip.border.color = (_g = tooltip.borderColor) !== null && _g !== void 0 ? _g : "var(--visiv-theme-canvas-chart-series-tooltip-border-color)";
                            result.tooltip.border.width = tooltip.borderWidth;
                            result.tooltip.color = (_h = tooltip.color) !== null && _h !== void 0 ? _h : "var(--visiv-theme-canvas-chart-series-tooltip-text-color)";
                            result.tooltip.font = `${tooltip.fontSize} ${tooltip.fontName}`;
                            result.tooltip.padding = tooltip.padding;
                            result.tooltip.visible = tooltip.visible;
                        }
                        return result;
                    }
                    getTitle() {
                        var _a;
                        let result = {};
                        let title = this.style.title;
                        if (title == null) {
                            return result;
                        }
                        result.align = title.align;
                        result.font = `${title.fontSize}  ${title.fontName}`;
                        result.position = title.position;
                        result.text = title.text;
                        result.visible = title.visible;
                        result.color = (_a = title.color) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-title-text-color)";
                        return result;
                    }
                    getValueAxis() {
                        var _a, _b, _c, _d, _e;
                        let result = {
                            labels: {},
                            line: {},
                            title: {},
                            majorGridLines: {},
                            minorGridLines: {},
                            majorTicks: {},
                            minorTicks: {},
                            axisCrossingValue: [0, -1000000000000, -1000000000000]
                        };
                        let valueAxis = this.style.valueAxis;
                        if (valueAxis == null) {
                            return result;
                        }
                        if (valueAxis.min != null) {
                            result.min = valueAxis.min;
                        }
                        if (valueAxis.max != null) {
                            result.max = valueAxis.max;
                        }
                        let labels = valueAxis.labels;
                        let line = valueAxis.line;
                        let title = valueAxis.title;
                        let majorGridLines = valueAxis.majorGridLines;
                        let minorGridLines = valueAxis.minorGridLines;
                        if (labels) {
                            result.labels.color = (_a = labels.color) !== null && _a !== void 0 ? _a : "var(--visiv-theme-canvas-chart-value-axis-label-text-color)";
                            result.labels.font = labels.fontSize + " " + labels.fontName;
                            result.labels.rotation = labels.rotation;
                            result.labels.visible = labels.visible;
                        }
                        if (line) {
                            result.line.color = (_b = line.color) !== null && _b !== void 0 ? _b : "var(--visiv-theme-canvas-chart-value-axis-line-color)";
                            result.line.width = line.width;
                            result.line.visible = line.visible;
                        }
                        if (title) {
                            result.title.color = (_c = title.color) !== null && _c !== void 0 ? _c : "var(--visiv-theme-canvas-chart-value-axis-title-text-color)";
                            result.title.font = title.fontSize + " " + title.fontName;
                            result.title.position = title.position;
                            result.title.rotation = title.rotation;
                            result.title.text = title.text;
                            result.title.visible = title.visible;
                        }
                        if (majorGridLines) {
                            result.majorGridLines.color = (_d = majorGridLines.color) !== null && _d !== void 0 ? _d : "var(--visiv-theme-canvas-chart-value-axis-major-grid-line-color)";
                            result.majorGridLines.dashType = majorGridLines.dashType;
                            result.majorGridLines.visible = majorGridLines.visible;
                            result.majorTicks.visible = majorGridLines.tickMarks;
                        }
                        if (minorGridLines) {
                            result.minorGridLines.color = (_e = minorGridLines.color) !== null && _e !== void 0 ? _e : "var(--visiv-theme-canvas-chart-value-axis-minor-grid-line-color)";
                            result.minorGridLines.dashType = minorGridLines.dashType;
                            result.minorGridLines.visible = minorGridLines.visible;
                            result.minorTicks.visible = minorGridLines.tickMarks;
                        }
                        return result;
                    }
                    getTooltip() {
                        var _a, _b;
                        return {
                            visible: (_a = this.style.tooltip) === null || _a === void 0 ? void 0 : _a.visible,
                            template: (_b = this.style.tooltip) === null || _b === void 0 ? void 0 : _b.template
                        };
                    }
                }
                Charts.ChartStyle = ChartStyle;
            })(Charts = Shared.Charts || (Shared.Charts = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Charts;
            (function (Charts) {
                class DefaultChart extends Charts.ChartOptions {
                    getCategoryAxis() {
                        let result = [];
                        let categories = this.categories || [];
                        let categoryAxis = null;
                        if (categories.length > 0) {
                            categories.forEach((category, index) => {
                                category.isDate ?
                                    category = this.formatDateValues(category) : null;
                                categoryAxis = this.style.categoryAxis;
                                categoryAxis.categories = category.data;
                                categoryAxis.labels.format = this.getDataFormatString(category.format);
                                result[index] = categoryAxis;
                            });
                        }
                        else {
                            result.push(this.style.categoryAxis);
                        }
                        return result;
                    }
                    getSeries() {
                        let result = [];
                        let serie = null;
                        let series = this.state.get("data.series");
                        _.each(series, (item) => {
                            serie = $.extend(true, {}, {
                                tooltip: {
                                    format: this.getDataFormatString(item["format"])
                                }
                            }, item);
                            if (serie.isDate) {
                                serie = this.formatDateValues(serie);
                            }
                            serie.stack = this.state.get("style.valueAxis.stack");
                            result[result.length] = serie;
                        });
                        return result;
                    }
                    getValueAxis() {
                        let result = super.getValueAxis();
                        if (this.series.length > 0) {
                            result.labels.format = this.getDataFormatString(_.first(this.series).format);
                            let min = this.data.minValue;
                            let max = this.data.maxValue;
                            if (min != null && max != null) {
                                if (min > -1 && max < 1) {
                                    result.majorUnit = 0.1;
                                }
                                else if (min > -5 && max < 5) {
                                    result.majorUnit = 1;
                                }
                            }
                        }
                        return result;
                    }
                    getSeriesDefaults() {
                        let result = this.style.seriesDefaults;
                        result.labels.template = null;
                        return result;
                    }
                    getDataFormatString(format) {
                        var result = null;
                        if (format) {
                            result = "{0:" + format + "}";
                        }
                        return result;
                    }
                    formatDateValues(src) {
                        let index = 0;
                        if (src.isDate) {
                            _.each(src.data, (item) => {
                                if (item != null) {
                                    let num = Date.parse(item);
                                    if (!isNaN(num)) {
                                        src.data[index] = kendo.toString(new Date(num), src.format);
                                    }
                                }
                                index += 1;
                            });
                        }
                        return src;
                    }
                }
                Charts.DefaultChart = DefaultChart;
            })(Charts = Shared.Charts || (Shared.Charts = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Charts;
            (function (Charts) {
                class PieChart extends Charts.ChartOptions {
                    getSeries() {
                        let result = [];
                        let serie = null;
                        this.series.forEach((item, index) => {
                            serie = $.extend(true, serie, {
                                tooltip: {
                                    format: this.getDataFormatString(item.format)
                                }
                            }, item, {
                                data: this.transformSeriesData(item, index)
                            });
                            if (serie.isDate) {
                                serie = this.formatDateValues(serie);
                            }
                            result[result.length] = serie;
                        });
                        return result;
                    }
                    getDataFormatString(format) {
                        var result = null;
                        if (format) {
                            result = "{0:" + format + "}";
                        }
                        return result;
                    }
                    formatDateValues(src) {
                        let index = 0;
                        if (src.isDate) {
                            _.each(src.data, (item) => {
                                if (item != null) {
                                    let num = Date.parse(item);
                                    if (!isNaN(num)) {
                                        src.data[index] = kendo.toString(new Date(num), src.format);
                                    }
                                }
                                index += 1;
                            });
                        }
                        return src;
                    }
                    getSeriesDefaults() {
                        let result = this.style.seriesDefaults;
                        result.labels.template =
                            (e) => {
                                return `${e.category} - ${e.value}`;
                            };
                        return result;
                    }
                    getTooltip() {
                        let result = _.extend(this.style.tooltip, {
                            visible: true,
                            template: "#= category # - #= value #"
                        });
                        return result;
                    }
                    transformSeriesData(series, seriesIndex) {
                        let result = [];
                        let category = _.first(this.categories);
                        series.data.forEach((value, index) => {
                            result.push({
                                category: category.data[index],
                                value: value
                            });
                        });
                        return result;
                    }
                }
                Charts.PieChart = PieChart;
            })(Charts = Shared.Charts || (Shared.Charts = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class NavigateLink extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_imageUrl = this.getImagePath();
                    }
                    get entityId() {
                        return this.state.get("entityId", null);
                    }
                    set entityId(value) {
                        this.state.set("entityId", value);
                    }
                    get entityName() {
                        return this.state.get("entityName", null);
                    }
                    set entityName(value) {
                        this.state.set("entityName", value);
                    }
                    get imageUrl() {
                        return this.m_imageUrl;
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    template() {
                        return `<a href="#"><img src="${this.imageUrl}" onload="SVGInject(this)"/></a>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            top: "3px",
                            right: "26px",
                            bottom: "3px",
                            width: "16px",
                            display: "none"
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.entityId > 0) {
                            this.node.attr("href", Jade.Path.resolve(`~/explore/${this.entityId}`));
                        }
                        else {
                            this.node.attr("href", "#");
                        }
                        this.node.attr("title", `Navigate to ${this.entityName}`);
                        this.node.css({
                            display: this.entityId != null ? "inline-block" : "none"
                        });
                        this.node.attr("tabIndex", this.tabIndex);
                    }
                    getImagePath() {
                        return Jade.IconSet.get("pdjs")
                            .resolve("nav_right.svg", Jade.IconSetSizeSpecificDirectory.svg);
                    }
                    static setDesignDisplay(link) {
                        link.entityId = 0;
                        link.entityName = "Entity 'A'";
                    }
                }
                Forms.NavigateLink = NavigateLink;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let ComboBoxMode;
                (function (ComboBoxMode) {
                    ComboBoxMode[ComboBoxMode["List"] = 0] = "List";
                    ComboBoxMode[ComboBoxMode["PopUp"] = 1] = "PopUp";
                })(ComboBoxMode = Controls.ComboBoxMode || (Controls.ComboBoxMode = {}));
                class ComboBox extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.ensureDataSource(options.data);
                        this.state.unset("data");
                    }
                    get defaultMask() {
                        return this.state.get("defaultMask", "Select...");
                    }
                    set defaultMask(value) {
                        this.state.set("defaultMask", value);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get data() {
                        return this.m_data;
                    }
                    get input() {
                        return this.m_input;
                    }
                    get list() {
                        return this.m_list;
                    }
                    get mode() {
                        return this.state.get("mode", ComboBoxMode.List);
                    }
                    set mode(value) {
                        this.state.set("mode", value);
                    }
                    get maskValue() {
                        return this.input.maskValue;
                    }
                    set maskValue(value) {
                        this.input.maskValue = value;
                    }
                    get maskVisible() {
                        return this.input.maskNode.is(":visible");
                    }
                    get textValue() {
                        return this.input.textValue;
                    }
                    set textValue(value) {
                        this.input.textValue = value;
                    }
                    get textVisible() {
                        return this.input.textNode.is(":visible");
                    }
                    get selection() {
                        return this.state.get("selection");
                    }
                    set selection(value) {
                        this.state.set("selection", value);
                    }
                    get icon() {
                        return this.m_icon;
                    }
                    get iconValue() {
                        return this.icon.path;
                    }
                    set iconValue(value) {
                        this.icon.path = value;
                    }
                    get button() {
                        return this.m_button;
                    }
                    get onFilterCallback() {
                        return this.state.get("onFilter");
                        ;
                    }
                    get onCreateListItemCallback() {
                        return this.state.get("onCreateListItem", (e) => { return this.createListItem(e); });
                    }
                    get onSelectionChangedCallback() {
                        return this.state.get("onSelectionChanged", () => { });
                    }
                    get onShowDialogCallback() {
                        return this.state.get("onShowDialog", () => { });
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    template() {
                        return `<div></div>`;
                    }
                    focusMask() {
                        this.input.focusMask();
                    }
                    focusText() {
                        this.input.focusText();
                    }
                    hideList() {
                        this.list.hide();
                    }
                    showList() {
                        this.list.show();
                    }
                    showMask() {
                        this.input.showMask();
                        this.setDisplayMode();
                    }
                    showText() {
                        this.input.showText();
                        this.setDisplayMode();
                    }
                    getInputEvent(args) {
                        return new Controls.ComboBoxInputEvent(args);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_input = new Controls.MaskedTextBox({
                            defaultMaskText: this.defaultMask,
                            onMaskDoubleClick: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.DOUBLECLICK,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onMaskBlur: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.BLUR,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onMaskFocus: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.FOCUS,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onMaskKeyDown: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYDOWN,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onMaskKeyPress: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYPRESS,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onMaskKeyUp: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYUP,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.mask
                                }).execute();
                            },
                            onTextBlur: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.BLUR,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.text
                                }).execute();
                            },
                            onTextFocus: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.FOCUS,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.text
                                }).execute();
                            },
                            onTextKeyDown: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYDOWN,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.text
                                }).execute();
                            },
                            onTextKeyPress: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYPRESS,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.text
                                }).execute();
                            },
                            onTextKeyUp: (e) => {
                                this.getInputEvent({
                                    event: e,
                                    eventType: Jade.BrowserEvent.KEYUP,
                                    comboBox: this,
                                    source: Controls.ComboBoxInputEventSource.text
                                }).execute();
                            }
                        });
                        this.m_icon = new Controls.ComboBoxIcon();
                        this.m_button = new Controls.ComboBoxButton({
                            mode: this.mode,
                            onShowList: _.bind(this.onShowList, this),
                            onShowDialog: _.bind(this.onShowDialog, this),
                            tabIndex: this.tabIndex
                        });
                        this.controls.add(this.input);
                        this.controls.add(this.icon);
                        this.controls.add(this.button);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_list = this.createList();
                        this.controls.add(this.list);
                        this.node.addClass(Controls.CssClass.ComboBox);
                        this.data.bind();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.triggerSelectionChange();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.input.enabled = this.enabled;
                        this.input.tabIndex = this.tabIndex;
                        this.button.enabled = this.enabled;
                        this.button.tabIndex = this.tabIndex;
                        if (this.state.hasChanged("selection")) {
                            this.triggerSelectionChange();
                        }
                    }
                    onSelectionChange(selection) {
                        if (selection == null) {
                            this.iconValue = null;
                            this.maskValue = this.defaultMask;
                            this.textValue = "";
                        }
                    }
                    onDataBind(data) {
                        if (data != null) {
                            this.list.clear();
                            data.each((record) => {
                                let item = this.onCreateListItemCallback(record);
                                if (item != null) {
                                    this.list.controls.add(item);
                                }
                            });
                            this.onDataBound(data);
                        }
                    }
                    onDataBound(data) {
                        if (data.count === 0) {
                            this.list.showMessage("No matching items.");
                        }
                    }
                    onFilter(e) {
                        this.onFilterCallback(e);
                    }
                    createDataSource(e) {
                        return new Controls.ComboBoxDataSource({
                            data: e
                        });
                    }
                    createListItem(e) {
                        return new Controls.ComboBoxListItem(e);
                    }
                    createList() {
                        return new PDJS.Shared.UI.Controls.ComboBoxList({
                            comboBox: this,
                            anchor: this.node,
                            width: this.node.outerWidth() - 2
                        });
                    }
                    onShowDialog(e) {
                        this.onShowDialogCallback();
                    }
                    onShowList(e) {
                        this.list.toggle();
                        if (this.input.isMaskVisible) {
                            this.focusMask();
                        }
                        else {
                            this.focusText();
                        }
                    }
                    ensureDataSource(data) {
                        if (data == null) {
                            data = [];
                        }
                        if (data instanceof Array) {
                            this.m_data = this.createDataSource(data);
                        }
                        if (data instanceof Controls.ComboBoxDataSource) {
                            this.m_data = data;
                        }
                        this.data.onChangeCallback = _.bind(this.onDataBind, this);
                        this.data.onFilterCallback = _.bind(this.onFilter, this);
                    }
                    setDisplayMode() {
                        let addPadding = Jade.String.isNullOrWhiteSpace(this.iconValue) && this.input.isMaskVisible;
                        this.input.maskNode.css({
                            paddingLeft: addPadding ? "5px" : "25px"
                        });
                        this.icon.visible = this.input.isMaskVisible;
                    }
                    triggerSelectionChange() {
                        this.onSelectionChange(this.selection);
                        this.onSelectionChangedCallback(this.selection);
                        this.setDisplayMode();
                    }
                }
                Controls.ComboBox = ComboBox;
                class ComboBoxOf extends ComboBox {
                    constructor(options) {
                        super(options);
                    }
                    get selection() {
                        return this.state.get("selection");
                    }
                    set selection(value) {
                        this.state.set("selection", value);
                    }
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                    }
                }
                Controls.ComboBoxOf = ComboBoxOf;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityIconFieldComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                        if (selection != null) {
                            this.iconValue = selection.icon;
                            this.maskValue = selection.name;
                        }
                    }
                    createListItem(e) {
                        return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                            data: e,
                            uidMap: "icon",
                            labelMap: "name",
                            iconMap: "icon"
                        });
                    }
                    onFilter(e) {
                        let service = new PDJS.Services.System.IconService();
                        service.search({
                            term: this.textValue,
                            success: (e2) => {
                                e.result.addRange(e2.data.data);
                                e.complete();
                                this.list.resize(e2.data.data.length * 24);
                            }
                        });
                    }
                    onShowDialog(e) {
                        PDJS.Shared.Dialogs.IconBrowserDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    this.selection = {
                                        icon: e.value,
                                        name: e.value.replace("_", " ")
                                    };
                                }
                            }
                        });
                    }
                }
                Forms.EntityIconFieldComboBox = EntityIconFieldComboBox;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityParentFieldComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                    constructor(options) {
                        super(options);
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    createListItem(data) {
                        return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                            data: data,
                            uidMap: "entityID",
                            labelMap: "entityName",
                            iconMap: "entityTypeIcon"
                        });
                    }
                    onFilter(e) {
                        let service = new PDJS.Services.Canvas.Forms.FormFieldService();
                        service.entityParentFieldQuery({
                            searchTerm: this.textValue,
                            childTypeId: this.entityTypeId,
                            success: (e2) => {
                                e.result.addRange(e2.data.entities);
                                e.complete();
                                this.list.resize(e2.data.entities.length * 24);
                            }
                        });
                    }
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                        if (selection != null) {
                            this.iconValue = selection.entityTypeIcon;
                            this.maskValue = selection.entityName;
                            this.icon.title = selection.entityTypeName;
                        }
                    }
                    onShowDialog() {
                        PDJS.Shared.Entities.EntityBrowserDialog.open({
                            filters: [PDJS.Core.Views.EntityFilter.parentFilter([this.entityTypeId])],
                            select: {
                                ok: (sender, e) => {
                                    this.selection = {
                                        entityID: e.entityId,
                                        entityName: e.entityName,
                                        entityTypeIcon: e.entityTypeIcon,
                                        entityTypeName: e.entityTypeName,
                                        entityTypeId: null
                                    };
                                }
                            }
                        });
                    }
                }
                Forms.EntityParentFieldComboBox = EntityParentFieldComboBox;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityProcessField extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.isUnassigned = options.stageId == null;
                    }
                    get assignment() {
                        return this.m_assignment;
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get isUnassigned() {
                        return this.state.get("isUnassigned", false);
                    }
                    set isUnassigned(value) {
                        this.state.set("isUnassigned", value);
                    }
                    get keyIcon() {
                        return this.state.get("keyIcon");
                    }
                    set keyIcon(value) {
                        this.state.set("keyIcon", value);
                    }
                    get keyName() {
                        return this.state.get("keyName");
                    }
                    set keyName(value) {
                        this.state.set("keyName", value);
                    }
                    get keyNode() {
                        return this.node.find("div[role=key]");
                    }
                    get keyNameNode() {
                        return this.node.find("div[role=key-name]");
                    }
                    get processName() {
                        return this.state.get("processName", "");
                    }
                    set processName(value) {
                        this.state.set("processName", value);
                    }
                    get processNode() {
                        return this.node.find("div[role=process]");
                    }
                    get processNameNode() {
                        return this.node.find("div[role=process-name]");
                    }
                    get stageId() {
                        return this.state.get("stageId");
                    }
                    set stageId(value) {
                        this.state.set("stageId", value);
                    }
                    get stageIcon() {
                        return this.state.get("stageIcon", "GEAR.PNG");
                    }
                    set stageIcon(value) {
                        this.state.set("stageIcon", value);
                    }
                    get stageName() {
                        return this.state.get("stageName");
                    }
                    set stageName(value) {
                        this.state.set("stageName", value);
                    }
                    get stageNode() {
                        return this.node.find("div[role=stage]");
                    }
                    get stageNameNode() {
                        return this.node.find("div[role=stage-name]");
                    }
                    get statusId() {
                        return this.state.get("statusId");
                    }
                    set statusId(value) {
                        this.state.set("statusId", value);
                    }
                    get statusIcon() {
                        return this.state.get("statusIcon");
                    }
                    set statusIcon(value) {
                        this.state.set("statusIcon", value);
                    }
                    get statusName() {
                        return this.state.get("statusName");
                    }
                    set statusName(value) {
                        this.state.set("statusName", value);
                    }
                    get statusNode() {
                        return this.node.find("div[role=status]");
                    }
                    get statusNameNode() {
                        return this.node.find("div[role=status-name]");
                    }
                    get showKey() {
                        return this.state.get("showKey");
                    }
                    set showKey(value) {
                        this.state.set("showKey", value);
                    }
                    get showProcess() {
                        return this.state.get("showProcess");
                    }
                    set showProcess(value) {
                        this.state.set("showProcess", value);
                    }
                    get showStage() {
                        return this.state.get("showStage");
                    }
                    set showStage(value) {
                        this.state.set("showStage", value);
                    }
                    get showStatus() {
                        return this.state.get("showStatus");
                    }
                    set showStatus(value) {
                        this.state.set("showStatus", value);
                    }
                    get onChangeCallback() {
                        return this.state.get("onChange", () => { });
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex");
                    }
                    template() {
                        return `
                    <div class="-pdjs-entity-process-field">
                        <div role="process">
                            <div>Process:</div>
                            <div role="process-name"></div>
                        </div>
                        <div role="key">
                            <div>Key:</div>
                            <div role="key-name"></div>
                        </div>
                        <div role="stage">
                            <div>Stage:</div>
                            <div role="stage-name"></div>
                        </div>
                        <div role="status">
                            <div>Status:</div>
                            <div role="status-name"></div>
                        </div>
                    </div>
                `;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_assignment = new Forms.EntityProcessFieldAssignment({
                            tabIndex: this.tabIndex,
                            onClick: (e) => {
                                Forms.EntityProcessFieldDialog.open({
                                    entityTypeId: this.entityTypeId,
                                    select: {
                                        ok: (sender, e) => {
                                            this.processName = e.processName;
                                            this.keyIcon = e.keyIcon;
                                            this.keyName = e.keyName;
                                            this.stageName = e.stageName;
                                            this.statusId = e.statusId;
                                            this.statusName = e.statusName;
                                            this.statusIcon = e.statusIcon;
                                            this.stageId = e.stageId;
                                            this.onChangeCallback();
                                        }
                                    }
                                });
                            }
                        });
                        this.controls.add(this.assignment);
                        if (this.isUnassigned) {
                            this.node.on(Jade.BrowserEvent.MOUSEENTER, () => {
                                if (this.stageId != null) {
                                    this.assignment.visible = true;
                                }
                            });
                            this.node.on(Jade.BrowserEvent.MOUSELEAVE, () => {
                                if (this.stageId != null) {
                                    this.assignment.visible = false;
                                }
                            });
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.processNameNode.text(this.processName);
                        this.processNameNode.css({
                            backgroundImage: `url(${Jade.IconSet.get("pd").resolve("gears.png", Jade.IconSetSizeSpecificDirectory.x16)})`
                        });
                        this.showNode(this.processNode, this.showProcess && this.stageId != null);
                        this.keyNameNode.text(this.keyName);
                        this.keyNameNode.css({
                            backgroundImage: `url(${Jade.IconSet.get("pd").resolve(this.keyIcon, Jade.IconSetSizeSpecificDirectory.x16)})`
                        });
                        this.showNode(this.keyNode, this.showKey && this.stageId != null);
                        this.stageNameNode.text(this.stageName);
                        this.stageNameNode.css({
                            backgroundImage: `url(${Jade.IconSet.get("pd").resolve("gear.png", Jade.IconSetSizeSpecificDirectory.x16)})`
                        });
                        this.showNode(this.stageNode, this.showStage && this.stageId != null);
                        this.statusNameNode.text(this.statusName);
                        this.statusNameNode.css({
                            backgroundImage: `url(${Jade.IconSet.get("pd").resolve(this.statusIcon, Jade.IconSetSizeSpecificDirectory.x16)})`
                        });
                        this.showNode(this.statusNode, this.showStatus && this.stageId != null);
                        this.assignment.visible = this.stageId == null;
                    }
                    showNode(node, show) {
                        if (show) {
                            node.show();
                        }
                        else {
                            node.hide();
                        }
                    }
                }
                Forms.EntityProcessField = EntityProcessField;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityProcessFieldAssignment extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", true);
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get onClickCallback() {
                        return this.state.get("onClick", () => { });
                    }
                    template() {
                        return `<div class="-pdjs-entity-process-field-assignment">
                        <button tabIndex="${this.tabIndex}">Assign Process</button>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.onClickCallback(e);
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.visible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                    }
                }
                Forms.EntityProcessFieldAssignment = EntityProcessFieldAssignment;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityProcessFieldDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get processList() {
                        return this.m_processList;
                    }
                    get statusList() {
                        return this.m_statusList;
                    }
                    get tree() {
                        return this.m_tree;
                    }
                    get treeFieldNode() {
                        return this.node.find("div[role=tree-field]");
                    }
                    get treeLabelNode() {
                        return this.treeFieldNode.find("[role=label]");
                    }
                    get treeControlNode() {
                        return this.treeFieldNode.find("[role=control]");
                    }
                    get result() {
                        return this.state.get("value");
                    }
                    set result(value) {
                        this.state.set("value", value);
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-canvas-shared-entity-process-field-dialog">
                    <div role="inputs" data-controls></div>
                    <div>
                        <div role="tree-field" class="-pdjs-shared-ui-field">
                            <div role="label">Assign Stage Of:</div>
                            <div role="control"></div>
                        </div>
                    </div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Assign | Process",
                            height: 450,
                            width: 450,
                            minHeight: 300
                        };
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.processList_init();
                        this.statusList_init();
                        this.addMessage();
                        this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    processList_init() {
                        this.m_processList = new PDJS.Shared.UI.Controls.Fields.ProcessField({
                            label: "Assign to Process",
                            width: "100%",
                            required: true,
                            entityTypeId: this.entityTypeId,
                            onSelectionChanged: (value) => {
                                this.statusList.processId = value === null || value === void 0 ? void 0 : value.id;
                                if ((value === null || value === void 0 ? void 0 : value.id) != null) {
                                    this.stageTree_init();
                                }
                                else {
                                    this.addMessage();
                                }
                            }
                        });
                        this.controls.add(this.processList);
                        this.processList.node.css({
                            marginBottom: "10px"
                        });
                    }
                    statusList_init() {
                        this.m_statusList = new PDJS.Shared.UI.Controls.Fields.ProcessStatusField({
                            label: "Assign Status Of",
                            width: "100%",
                            required: true
                        });
                        this.controls.add(this.statusList);
                    }
                    stageTree_init() {
                        this.removeMessage();
                        if (this.m_tree != null) {
                            this.m_tree.destroy();
                            this.m_tree = null;
                            this.result = null;
                        }
                        this.m_tree = new PDJS.Hub.Explorer.EntityProcessTree({
                            insertAt: "div[role=tree-field] > [role=control]",
                            processId: this.m_processList.processId,
                            select: (e) => {
                                if (e == null) {
                                    return;
                                }
                                this.result = {
                                    processId: this.m_processList.processId,
                                    processName: this.m_processList.processName,
                                    keyIcon: e.parent.icon,
                                    keyName: e.parent.name,
                                    stageId: e.objectId,
                                    stageName: e.name,
                                    statusId: this.m_statusList.statusId,
                                    statusIcon: this.m_statusList.statusIcon,
                                    statusName: this.m_statusList.statusName
                                };
                            }
                        });
                        this.controls.add(this.m_tree);
                    }
                    okButton_onClick(e) {
                        if (this.isValid()) {
                            this.close({
                                name: "ok",
                                data: this.result
                            });
                        }
                    }
                    cancelButton_onClick(e) {
                        this.close({
                            name: "cancel"
                        });
                    }
                    isValid() {
                        let result = true;
                        PDJS.Shared.PopOver.remove(this.treeLabelNode);
                        this.treeFieldNode.removeClass("-pdjs-validation-errors");
                        this.treeLabelNode.css({
                            color: "inherit",
                            backgroundImage: "inherit"
                        });
                        this.controls.each((control) => {
                            if (control instanceof PDJS.Shared.UI.Controls.Fields.Field) {
                                control.validate();
                                if (control.errors.count > 0) {
                                    result = false;
                                }
                            }
                        });
                        if (result == true && this.result == null) {
                            result = false;
                            this.treeFieldNode.addClass("-pdjs-validation-errors");
                            this.treeLabelNode.css({
                                color: "var(--visiv-required-text-color)",
                                backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                            PDJS.Shared.PopOver.validation(this.treeLabelNode, `A process stage must be selected.`);
                        }
                        return result;
                    }
                    addMessage(text = null) {
                        this.removeMessage();
                        let message = new PDJS.Shared.UI.Controls.Message({
                            insertAt: "div[role=tree-input]",
                            message: text || "Select a process above to see list of available stages.",
                            borderWidth: 1
                        });
                        if (message != null) {
                            this.controls.add(message);
                        }
                    }
                    removeMessage() {
                        let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message != null) {
                            this.controls.remove(message);
                            message.destroy();
                        }
                    }
                    static open(options) {
                        return new EntityProcessFieldDialog(options);
                    }
                }
                Forms.EntityProcessFieldDialog = EntityProcessFieldDialog;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let CssSelectors;
                (function (CssSelectors) {
                    CssSelectors["node"] = "li[data-uid]";
                    CssSelectors["innerNode"] = "li[data-uid] span.k-in";
                    CssSelectors["topMidBot"] = ".k-top, .k-mid, .k-bot";
                })(CssSelectors || (CssSelectors = {}));
                class TreeView extends Jade.UI.Control {
                    get model() {
                        this.ensureModel();
                        return this.m_model;
                    }
                    set model(value) {
                        this.m_model = value;
                    }
                    get cssClass() {
                        return this.state.get("cssClass", "");
                    }
                    get dragAndDrop() {
                        return this.state.get("dragAndDrop", false);
                    }
                    get selectedNode() {
                        return this.tree.select();
                    }
                    get tree() {
                        return this.m_tree;
                    }
                    set tree(value) {
                        this.m_tree = value;
                    }
                    addNode(model, parentId = null) {
                        let parentNode = this.getNodeById(parentId) ||
                            this.selectedNode;
                        let addedNode = this.tree.append(model.toKendoJSON(), parentNode);
                        this.tree.expand(parentNode);
                        if (addedNode.length > 0) {
                            this.tree.select(addedNode);
                            addedNode.get(0).scrollIntoView({
                                behavior: "smooth",
                                block: "end"
                            });
                        }
                    }
                    getNodeModel(node) {
                        let result = null;
                        let item = this.tree.dataItem(node);
                        if (item) {
                            result = this.model.getNode(item.id);
                        }
                        return result;
                    }
                    removeNode(id) {
                        let removeNode = this.getNodeById(id);
                        let fallbackNode = null;
                        fallbackNode = removeNode.next(CssSelectors.node);
                        if (fallbackNode.length == 0) {
                            fallbackNode = removeNode.prev(CssSelectors.node);
                        }
                        if (fallbackNode.length == 0) {
                            fallbackNode = removeNode.parent().closest(CssSelectors.node);
                        }
                        this.tree.remove(removeNode);
                        if (fallbackNode.length > 0) {
                            this.tree.select(fallbackNode);
                            fallbackNode.get(0).scrollIntoView({
                                behavior: "smooth",
                                block: "end"
                            });
                        }
                    }
                    select(nodeId, expand = false) {
                        let node = this.getNodeById(nodeId);
                        if (node != null) {
                            this.tree.select(node);
                            if (expand) {
                                this.tree.expand(node);
                            }
                        }
                    }
                    applyTemplate(modelNodeId) {
                        var _a;
                        let model = this.model.getNode(modelNodeId);
                        if (model == null) {
                            return;
                        }
                        let uid = (_a = this.tree.dataSource.get(model.id)) === null || _a === void 0 ? void 0 : _a.uid;
                        let node = this.tree.findByUid(uid);
                        let kin = node.find(".k-in").first();
                        node.attr("data-id", model.id);
                        node.attr("data-role", model.role);
                        kin.html(model.toMarkup());
                    }
                    refresh(args = {}) {
                        this.model.requestNodes({
                            nodeId: args.nodeId,
                            expanded: args.expanded || this.getExpandedNodeIds(args.nodeId),
                            success: () => {
                                if (args.nodeId == null) {
                                    this.tree.dataSource.data([]);
                                    this.tree.dataSource.data(this.model.toJSON().nodes);
                                }
                                else {
                                    let modelNode = this.model.getNode(args.nodeId);
                                    this.rebuildNode(modelNode.toJSON(), args.expand);
                                }
                                if (args.selected) {
                                    this.select(args.nodeId);
                                }
                                _.isFunction(args.success) ?
                                    args.success() : null;
                                this.onNodeRequestComplete({
                                    nodeId: args.nodeId,
                                    initialize: false
                                });
                            }
                        });
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-tree-view ${this.cssClass}">
                        <div role="tree"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.tree_init();
                    }
                    onSelect(e) {
                    }
                    onChange(e) {
                    }
                    onNodeDrop(e) {
                    }
                    onNodeRequestComplete(e) {
                    }
                    createModel() {
                        return new PDJS.Core.Data.Hierarchical.ModelBase();
                    }
                    ensureModel() {
                        if (this.m_model == null) {
                            this.m_model = this.createModel();
                        }
                    }
                    expandNode(args) {
                        if (args.data == null || args.model.nodes.count > 0) {
                            _.isFunction(args.success) ?
                                args.success() : null;
                            return;
                        }
                        this.refresh({
                            nodeId: args.model.id,
                            expand: true,
                            success: args.success,
                            selected: args.node.find("div > span.k-state-selected").length != 0
                        });
                    }
                    getExpandedNodeIds(nodeId = null) {
                        return this.model.getExpandedNodeIds(nodeId);
                    }
                    getNodeById(id) {
                        let result = null;
                        let data = this.tree.dataSource.get(id);
                        if (data) {
                            result = this.tree.findByUid(data.uid);
                        }
                        return result;
                    }
                    getNodeInfo(value) {
                        let result = null;
                        let isTreeViewNodeId = _.isString(value) || _.isNumber(value);
                        switch (true) {
                            case isTreeViewNodeId:
                                result = this.getNodeInfoById(value);
                                break;
                            case value instanceof Element:
                                result = this.getNodeInfoByNode($(value));
                                break;
                            case value instanceof jQuery:
                                result = this.getNodeInfoByNode(value);
                                break;
                            case value instanceof PDJS.Core.Data.Hierarchical.ModelNodeBase:
                                result = this.getNodeInfoByNodeModel(value);
                                break;
                        }
                        return result;
                    }
                    getSelectedModelNode() {
                        let result = null;
                        let item = this.tree.dataItem(this.tree.select());
                        if (item) {
                            result = this.model.getNode(item.id);
                        }
                        return result;
                    }
                    initializeNodes(id) {
                        var _a, _b;
                        let model = (_a = this.getNodeInfo(id)) === null || _a === void 0 ? void 0 : _a.model;
                        let models = ((_b = model === null || model === void 0 ? void 0 : model.nodes) === null || _b === void 0 ? void 0 : _b.toJSON()) || [];
                        if (model) {
                            this.applyTemplate(model.id);
                        }
                        models.forEach(model => {
                            this.initializeNodes(model.id);
                        });
                    }
                    rebuildNode(nodeData, expanded = null) {
                        let dst = this.getNodeInfo(nodeData.id);
                        if (dst.hasNode) {
                            let data = _.extend(nodeData, {
                                expanded: expanded == null ? nodeData.expanded : expanded,
                                hasNodes: nodeData.nodes.length > 0
                            });
                            this.tree.insertAfter(data, dst.node);
                            this.tree.remove(dst.node);
                        }
                    }
                    tree_init() {
                        let idName = this.model.bindings["id"];
                        let nodesName = this.model.bindings["nodes"];
                        let hasNodesName = this.model.bindings["hasNodes"];
                        this.m_tree = this.node.kendoTreeView({
                            dragAndDrop: this.dragAndDrop,
                            dataSource: new kendo.data.HierarchicalDataSource({
                                schema: {
                                    model: {
                                        id: idName,
                                        children: nodesName,
                                        hasChildren: (e) => {
                                            var _a;
                                            return e[hasNodesName] == true || ((_a = e[nodesName]) === null || _a === void 0 ? void 0 : _a.length) > 0;
                                        }
                                    }
                                }
                            }),
                            collapse: _.bind(this.tree_collapse, this),
                            dataBound: _.bind(this.tree_dataBound, this),
                            drop: _.bind(this.tree_drop, this),
                            expand: _.bind(this.tree_expand, this),
                            select: _.bind(this.tree_select, this),
                            template: _.bind(this.tree_template, this)
                        }).data("kendoTreeView");
                        this.model.requestNodes({
                            nodeId: null,
                            initialize: true,
                            success: (e) => {
                                this.tree.dataSource.data(this.model.toJSON().nodes);
                                this.onNodeRequestComplete({
                                    initialize: true
                                });
                            }
                        });
                    }
                    tree_change(e) {
                        let item = this.tree.dataItem(this.selectedNode);
                        let info = this.getNodeInfo(item === null || item === void 0 ? void 0 : item.id);
                        this.onChange({
                            data: info.data,
                            isDefaultPrevented: e.isDefaultPrevented,
                            model: info.model,
                            node: info.node,
                            preventDefault: e.preventDefault
                        });
                    }
                    tree_dataBound(e) {
                        if (!this.tree) {
                            return;
                        }
                        let item = e.node ?
                            this.tree.dataItem(e.node) :
                            this.tree.dataSource.get(this.model.nodes.first().id);
                        if (item) {
                            this.initializeNodes(item.id);
                        }
                    }
                    tree_drop(e) {
                        let srcNode = $(e.sourceNode).closest(".k-item");
                        let dstNode = $(e.dropTarget).closest(".k-item");
                        let srcData = this.tree.dataItem(srcNode);
                        let dstData = this.tree.dataItem(dstNode);
                        this.onNodeDrop({
                            dropPosition: e.dropPosition,
                            dropTarget: e.dropTarget,
                            dstData: dstData,
                            dstNode: dstNode,
                            isDefaultPrevented: e.isDefaultPrevented,
                            preventDefault: e.preventDefault,
                            srcData: srcData,
                            srcNode: srcNode,
                            setValid: e.setValid,
                            valid: e.valid
                        });
                    }
                    tree_expand(e) {
                        let info = this.getNodeInfo(e.node);
                        if (info.model) {
                            info.model.expanded = true;
                        }
                        this.expandNode({
                            node: info.node,
                            model: info.model,
                            data: info.data,
                            preventDefault: e.preventDefault,
                            isDefaultPrevented: e.isDefaultPrevented
                        });
                    }
                    tree_collapse(e) {
                        let info = this.getNodeInfo(e.node);
                        if (info.model) {
                            info.model.expanded = true;
                        }
                    }
                    tree_select(e) {
                        let item = this.tree.dataItem(e.node);
                        let info = this.getNodeInfo(item === null || item === void 0 ? void 0 : item.id);
                        this.onSelect(_.extend(e, {
                            data: info.data,
                            model: info.model,
                            node: info.node
                        }));
                    }
                    tree_template(e) {
                        let id = this.model.bindings["id"];
                        let info = this.getNodeInfo(e.item[id]);
                        let result = info.model != null ?
                            info.model.toMarkup() : "render error";
                        return result;
                    }
                    getNodeId(node) {
                        return this.tree.dataItem(node)[this.model.bindings.id];
                    }
                    getNodeInfoById(id) {
                        let data = this.tree.dataSource.get(id);
                        let node = data != null ?
                            this.tree.findByUid(data.uid) : null;
                        let model = this.model.getNode(id);
                        return {
                            data: data,
                            node: node,
                            model: model,
                            hasNode: node != null && node.length > -1,
                            nodeLoaded: data != null && data.loaded()
                        };
                    }
                    getNodeInfoByNode(node) {
                        return this.getNodeInfoById(this.getNodeId(node));
                    }
                    getNodeInfoByNodeModel(model) {
                        return this.getNodeInfoById(model.id);
                    }
                }
                Controls.TreeView = TreeView;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class EntityProcessTree extends PDJS.Shared.UI.Controls.TreeView {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return this.state.get("processId");
                }
                get selectCallback() {
                    return this.state.get("select", () => { });
                }
                createModel() {
                    return new PDJS.Core.Process.Explorer.Model({
                        processId: this.processId,
                        mode: PDJS.Core.Process.Explorer.IModelMode.StageSelect
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass(PDJS.Core.Process.ExplorerModel.CssClass.Model);
                    this.node.addClass("-pdjs-canvas-entity-process-tree");
                }
                onSelect(e) {
                    super.onSelect(e);
                    let model = e.model;
                    if (!model.isSelectable) {
                        e.preventDefault();
                    }
                    else {
                        this.selectCallback(model);
                    }
                }
            }
            Explorer.EntityProcessTree = EntityProcessTree;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityFieldComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                    constructor(options) {
                        super(options);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                        if (selection != null) {
                            this.iconValue = selection.entityTypeIcon;
                            this.maskValue = selection.entityName;
                            this.icon.title = selection.entityTypeName;
                        }
                    }
                    createListItem(data) {
                        return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                            data: data,
                            uidMap: "entityID",
                            labelMap: "entityName",
                            iconMap: "entityTypeIcon"
                        });
                    }
                    onFilter(e) {
                        let service = new PDJS.Services.Canvas.Forms.FormFieldService();
                        service.entityFieldQuery({
                            searchTerm: this.textValue,
                            viewId: this.viewId,
                            success: (e2) => {
                                e.result.addRange(e2.data.entities);
                                e.complete();
                                this.list.resize(e2.data.entities.length * 24);
                            }
                        });
                        this.showList();
                    }
                    onShowDialog() {
                        PDJS.Shared.Entities.EntityBrowserDialog.open({
                            viewStateId: this.viewStateId,
                            select: {
                                ok: (sender, e) => {
                                    this.selection = {
                                        entityID: e.entityId,
                                        entityName: e.entityName,
                                        entityTypeIcon: e.entityTypeIcon,
                                        entityTypeName: e.entityTypeName
                                    };
                                }
                            }
                        });
                    }
                }
                Forms.EntityFieldComboBox = EntityFieldComboBox;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class SingleSelectFieldComboBox extends PDJS.Shared.UI.Controls.ComboBox {
                    constructor(options) {
                        super(options);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    get items() {
                        return this.state.get("items");
                    }
                    setSelectedItem(options) {
                        this.selection = options;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.fill();
                    }
                    fill() {
                        _.each(this.items, (item) => {
                            this.list.controls.add(new PDJS.Shared.UI.Controls.ComboBoxListItem({
                                data: item,
                                uidMap: "id",
                                iconMap: "icon",
                                labelMap: "label"
                            }));
                        });
                        this.onFilter();
                    }
                    onMaskFocus() {
                        if (!Jade.String.isNullOrWhiteSpace(this.textValue)) {
                            this.showText();
                            this.focusText();
                        }
                    }
                    onInputBlur(e) {
                        this.showMask();
                    }
                    onFilter() {
                        let results = new Array();
                        let escape = function (value) {
                            return value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
                        };
                        if (this.textValue != null && this.textValue != "") {
                            let exp = new RegExp(`${escape(this.textValue.toLowerCase())}`, "i");
                            _.each(this.items, (item) => {
                                if (exp.test(item.label.toLowerCase())) {
                                    results[results.length] = item;
                                }
                            });
                        }
                        else {
                            results = this.items;
                        }
                        this.list.controls.clear();
                        _.each(results, (item) => {
                            this.list.controls.add(new PDJS.Shared.UI.Controls.ComboBoxListItem({
                                data: item,
                                uidMap: "id",
                                iconMap: "icon",
                                labelMap: "label"
                            }));
                        });
                    }
                    clearFilter() {
                        this.list.controls.clear();
                        _.each(this.items, (item) => {
                            this.list.controls.add(new PDJS.Shared.UI.Controls.ComboBoxListItem({
                                data: item,
                                uidMap: "id",
                                iconMap: "icon",
                                labelMap: "label"
                            }));
                        });
                    }
                }
                Forms.SingleSelectFieldComboBox = SingleSelectFieldComboBox;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class UserFieldComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                    constructor(options) {
                        super(options);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                        if (selection != null) {
                            this.maskValue = selection.userName;
                        }
                    }
                    createListItem(data) {
                        return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                            data: data,
                            uidMap: "userID",
                            labelMap: "userName"
                        });
                    }
                    onFilter(e) {
                        let service = new PDJS.Services.Canvas.Forms.FormFieldService();
                        service.userFieldQuery({
                            searchTerm: this.textValue,
                            viewId: this.viewId,
                            success: (e2) => {
                                e.result.addRange(e2.data.users);
                                e.complete();
                                this.list.resize(e2.data.users.length * 24);
                            }
                        });
                    }
                    onShowDialog() {
                        Forms.UserFieldComboBoxDialog.open({
                            viewStateId: this.viewStateId,
                            select: {
                                ok: (sender, e) => {
                                    let item = _.first(e.items);
                                    if (item != null) {
                                        this.selection = {
                                            userID: item.id,
                                            userName: item.name
                                        };
                                    }
                                }
                            }
                        });
                    }
                }
                Forms.UserFieldComboBox = UserFieldComboBox;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class UserFieldComboBoxDialog extends Jade.UI.Dialogs.DialogOf {
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.getSelections().toArray();
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-user-field-combo-box-dialog">
                    <div data-role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | User",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[data-role=grid]"),
                            selectionMode: "single",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.ObjectId,
                                            name: item.ObjectName,
                                            type: item.ObjectType
                                        };
                                    });
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            }
                        });
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: {
                                    items: this.selections
                                }
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No User Selected",
                                message: "No user has been selected. Select a user and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                    static open(options) {
                        return new UserFieldComboBoxDialog(options);
                    }
                }
                Forms.UserFieldComboBoxDialog = UserFieldComboBoxDialog;
            })(Forms = Shared.Forms || (Shared.Forms = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessColorPalette {
                    constructor(options) {
                        this.m_wheel = [];
                        options = options || {};
                        this.buildWheel(options.count);
                    }
                    static get colors() {
                        return this.m_colors;
                    }
                    get wheel() {
                        return this.m_wheel;
                    }
                    getColor(index) {
                        let result = null;
                        if (index < this.wheel.length) {
                            result = this.wheel[index];
                        }
                        return result;
                    }
                    setCount(index) {
                        this.buildWheel(index);
                    }
                    buildWheel(count) {
                        if (count == null) {
                            this.m_wheel = ProcessColorPalette.colors.slice(0);
                            return;
                        }
                        for (let i = 0; i < count; i++) {
                            this.wheel[i] = ProcessColorPalette.colors[i % ProcessColorPalette.colors.length];
                        }
                    }
                }
                ProcessColorPalette.m_colors = [
                    { light: "#a5f986", dark: "#52b030" },
                    { light: "#d6f8e9", dark: "#5cdba3" },
                    { light: "#c1c0fd", dark: "#615fde" },
                    { light: "#dcff9a", dark: "#8dcf11" },
                    { light: "#ccdce8", dark: "#5ea0d1" },
                    { light: "#fcd8e9", dark: "#e675aa" },
                    { light: "#81e7fd", dark: "#30aec9" },
                    { light: "#dda5fb", dark: "#b055e0" },
                    { light: "#fab7a5", dark: "#de7559" },
                    { light: "#fdf89d", dark: "#d1c932" }
                ];
                Process.ProcessColorPalette = ProcessColorPalette;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class Status {
                }
                Status.A = {
                    id: 1,
                    name: "Status A",
                    icon: "BULLET_BALL_BLUE.PNG"
                };
                Status.B = {
                    id: 2,
                    icon: "BULLET_BALL_GREEN.PNG",
                    name: "Status B"
                };
                Status.C = {
                    id: 3,
                    icon: "BULLET_BALL_RED.PNG",
                    name: "Status C"
                };
                Status.D = {
                    id: 1,
                    icon: "BULLET_BALL_YELLOW.PNG",
                    name: "Status D"
                };
                Process.Status = Status;
                class Stage {
                }
                Stage.A = { id: 1, name: "Stage A", decisions: [], keyId: 1, visited: true };
                Stage.B = { id: 2, name: "Stage B", decisions: [], keyId: 1, visited: true };
                Stage.C = { id: 3, name: "Stage C", decisions: [], keyId: 1, visited: true };
                Stage.D = { id: 4, name: "Stage D", decisions: [], keyId: 1, visited: true };
                Stage.E = { id: 5, name: "Stage E", decisions: [], keyId: 1, visited: true };
                Stage.F = { id: 6, name: "Stage F", decisions: [], keyId: 2, visited: true };
                Stage.G = { id: 7, name: "Stage G", decisions: [], keyId: 2, visited: true };
                Stage.H = { id: 8, name: "Stage H", decisions: [], keyId: 2, visited: true };
                Stage.I = { id: 9, name: "Stage I", decisions: [], keyId: 3, visited: true };
                Stage.J = { id: 10, name: "Stage J", decisions: [], keyId: 3 };
                Stage.K = { id: 11, name: "Stage K", decisions: [], keyId: 3 };
                Stage.L = { id: 12, name: "Stage L", decisions: [], keyId: 3 };
                Stage.M = { id: 13, name: "Stage M", decisions: [], keyId: 4 };
                Stage.N = { id: 14, name: "Stage N", decisions: [], keyId: 4 };
                Stage.O = { id: 15, name: "Stage O", decisions: [], keyId: 5 };
                Stage.P = { id: 16, name: "Stage P", decisions: [], keyId: 5 };
                Stage.Q = { id: 17, name: "Stage Q", decisions: [], keyId: 5 };
                Stage.List = [Stage.A, Stage.B, Stage.C, Stage.D, Stage.E,
                    Stage.F, Stage.G, Stage.H, Stage.I, Stage.J,
                    Stage.K, Stage.L, Stage.M, Stage.N, Stage.O,
                    Stage.P, Stage.Q];
                Process.Stage = Stage;
                class Key {
                }
                Key.One = { id: 1, name: "Key 1", icon: "SIGNAL_FLAG_WHITE.PNG", visited: true };
                Key.Two = { id: 2, name: "Key 2", icon: "SIGNAL_FLAG_YELLOW.PNG", visited: true };
                Key.Three = { id: 3, name: "Key 3", icon: "SIGNAL_FLAG_GREEN.PNG", visited: true };
                Key.Four = { id: 4, name: "Key 4", icon: "SIGNAL_FLAG_BLUE.PNG" };
                Key.Five = { id: 5, name: "Key 5", icon: "SIGNAL_FLAG_CHECKERED.PNG" };
                Key.List = [Key.One, Key.Two, Key.Three, Key.Four, Key.Five];
                Process.Key = Key;
                class Decision {
                }
                Decision.A = { id: 1, name: "Decision A", stageId: Stage.J.id, targetStage: Stage.K, targetStatus: Status.B };
                Decision.B = { id: 2, name: "Decision B", stageId: Stage.J.id, targetStage: Stage.F, targetStatus: Status.C };
                Decision.C = { id: 3, name: "Decision C", stageId: Stage.J.id, targetStage: Stage.D, targetStatus: Status.D };
                Decision.List = [Decision.A, Decision.B, Decision.C];
                Process.Decision = Decision;
                Stage.C.decisions = Decision.List;
                class DecisionMap {
                }
                DecisionMap.A = { color: Process.ProcessColorPalette.colors[0], stageId: Stage.K.id, index: 0 };
                DecisionMap.B = { color: Process.ProcessColorPalette.colors[1], stageId: Stage.F.id, index: 1 };
                DecisionMap.C = { color: Process.ProcessColorPalette.colors[2], stageId: Stage.D.id, index: 2 };
                DecisionMap.List = [DecisionMap.A, DecisionMap.B, DecisionMap.C];
                Process.DecisionMap = DecisionMap;
                class DataSet {
                    static get currentProcess() {
                        return "Process A";
                    }
                    static get currentKey() {
                        return Key.Three;
                    }
                    static get currentStage() {
                        return Stage.J;
                    }
                    static get currentStatus() {
                        return Status.A;
                    }
                    static get keys() {
                        return Key.List;
                    }
                    static get stages() {
                        return Stage.List;
                    }
                    static get selectedStage() {
                        return Stage.C;
                    }
                    static get selectedStageDecisions() {
                        return Decision.List;
                    }
                    static get selectedStageDecisionMaps() {
                        return DecisionMap.List;
                    }
                }
                Process.DataSet = DataSet;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Rules;
        (function (Rules) {
            class ScriptResponseOf {
                constructor(options) {
                    this.m_response = options;
                }
                get arguments() {
                    return this.m_arguments;
                }
                set arguments(value) {
                    this.m_arguments = value;
                }
                get hasAlerts() {
                    return this.response.hasScriptAlerts;
                }
                get hasErrors() {
                    return this.response.hasScriptErrors;
                }
                get response() {
                    return this.m_response;
                }
                set response(value) {
                    this.m_response = value;
                }
                get type() {
                    return Object.getPrototypeOf(this).constructor;
                }
                handle(e) {
                    this.arguments = e || {};
                    if (this.handleScriptErrors()) {
                        return true;
                    }
                    if (this.handleScriptAlerts()) {
                        return true;
                    }
                    if (this.handleScriptActions()) {
                        return true;
                    }
                    return false;
                }
                getScriptActions() {
                    return Rules.ScriptAction.actions;
                }
                handleScriptActions() {
                    if (!this.arguments.allowActions !== true) {
                        return false;
                    }
                    let result = false;
                    this.getScriptActions().every(type => {
                        let action = new (type)(this);
                        if (action != null && action.canHandle()) {
                            this.handleScriptAction(action);
                            result = true;
                            return false;
                        }
                        return true;
                    });
                    return result;
                }
                handleScriptAction(action) {
                    action.handle();
                }
                handleScriptAlerts() {
                    var _a, _b;
                    if (!this.response.hasScriptAlerts) {
                        return false;
                    }
                    Jade.UI.Dialogs.MultiMessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Success,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: (_a = this.arguments.alertDialogTitle) !== null && _a !== void 0 ? _a : "Alerts",
                        header: (_b = this.arguments.alertDialogHeader) !== null && _b !== void 0 ? _b : "The following alerts were generated:",
                        messages: this.response.scriptAlerts,
                        select: (e) => {
                            this.acknowledgedScriptAlerts(e);
                        }
                    });
                    return true;
                }
                handleScriptErrors() {
                    var _a, _b;
                    if (!this.response.hasScriptErrors) {
                        return false;
                    }
                    Jade.UI.Dialogs.MultiMessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: (_a = this.arguments.errorDialogTitle) !== null && _a !== void 0 ? _a : "Errors",
                        header: (_b = this.arguments.errorDialogHeader) !== null && _b !== void 0 ? _b : "The following errors were generated:",
                        messages: this.response.scriptErrors,
                        select: (e) => {
                            this.acknowledgedScriptErrors(e);
                        }
                    });
                    return true;
                }
                acknowledgedScriptErrors(e) {
                    e.close();
                    this.handleScriptActions();
                }
                acknowledgedScriptAlerts(e) {
                    e.close();
                    this.handleScriptActions();
                }
            }
            Rules.ScriptResponseOf = ScriptResponseOf;
            class ScriptResponse extends ScriptResponseOf {
            }
            Rules.ScriptResponse = ScriptResponse;
        })(Rules = Shared.Rules || (Shared.Rules = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ExecuteDecisionResponse extends PDJS.Shared.Rules.ScriptResponseOf {
                    handle(e = {}) {
                        this.arguments = e;
                        this.setDialogText();
                        if (super.handle(e)) {
                            return true;
                        }
                        ;
                        if (this.response.hasEntityChanges) {
                            PDJS.Hub.Explorer.Navigator.execute({
                                success: () => {
                                    PDJS.Hub.Explorer.EventsHub.entityChangedPublish(this.response.entityChanges);
                                    PDJS.Hub.Explorer.EventsHub.reloadExplorerPublish();
                                }
                            });
                        }
                        this.handleDefaultBehavior();
                        return true;
                    }
                    handleDefaultBehavior() {
                        window.location.reload();
                    }
                    setDialogText() {
                        this.arguments.errorDialogTitle = "Decision Execution Errors";
                        this.arguments.errorDialogHeader = "Decision execution failed due to the following errors:";
                        this.arguments.alertDialogTitle = "Decision Execution Success";
                        this.arguments.alertDialogHeader = "Decision execution succeeded with the following alerts:";
                    }
                }
                Process.ExecuteDecisionResponse = ExecuteDecisionResponse;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                let ProcessEvent;
                (function (ProcessEvent) {
                    ProcessEvent["StageSelect"] = "PDJS.CANVAS:PROCESSVIEW:STAGE:SELCT";
                    ProcessEvent["DecisionsMap"] = "PDJS.CANVAS:PROCESSVIEW:DECISIONS:MAP";
                })(ProcessEvent = Process.ProcessEvent || (Process.ProcessEvent = {}));
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessDecisionsComponent extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get eventBus() {
                        return Jade.Application.instance.contexts.current.events;
                    }
                    get source() {
                        return this.m_source;
                    }
                    template() {
                        return `<div></div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_source = this.state.get("source");
                        this.state.unset("source", { silent: true });
                    }
                }
                Process.ProcessDecisionsComponent = ProcessDecisionsComponent;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessDecisions extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_eventBus = new Jade.EventBus();
                        this.m_source = options.source;
                        this.state.unset("source", { silent: true });
                    }
                    get eventBus() {
                        return this.m_eventBus;
                    }
                    get source() {
                        return this.m_source;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-process-decisions" style="position:absolute;inset:0;"></div>`;
                    }
                    load(source) {
                        this.controls.clear();
                        this.m_source = source;
                        this.component_init();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                    component_init() {
                        this.m_component = new Process.ProcessDecisionsList({
                            source: this.source
                        });
                        this.controls.add(this.m_component);
                    }
                }
                Process.ProcessDecisions = ProcessDecisions;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessDecisionsList extends Process.ProcessDecisionsComponent {
                    get grid() {
                        return this.m_grid;
                    }
                    get selectedStage() {
                        return this.m_selectedStage;
                    }
                    set selectedStage(value) {
                        this.m_selectedStage = value;
                    }
                    get currentStage() {
                        return this.source.currentStage;
                    }
                    get selectedDecisions() {
                        let result = [];
                        this.source.decisions.forEach(decision => {
                            if (decision.stageId == this.selectedStage.id) {
                                result[result.length] = decision;
                            }
                        });
                        return result;
                    }
                    get isActiveStage() {
                        return this.selectedStage.id === this.currentStage.id;
                    }
                    get colors() {
                        return this.m_colors;
                    }
                    template() {
                        return `<div role="decisions" data-controls></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            overflow: "hidden",
                            overflowY: "auto"
                        });
                        this.setSelectedStage(this.source.currentStage);
                        this.grid_init();
                        this.grid_fill();
                        this.subscriptions.add(Process.ProcessEvent.StageSelect, (e) => {
                            this.onStageSelect(e);
                        });
                        this.node.on(Jade.BrowserEvent.CLICK, "div[role=decision-action]", (e) => {
                            this.action_onClick(e);
                        });
                    }
                    onDestroy(e) {
                        if (this.m_grid != null) {
                            this.m_grid.destroy();
                        }
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: this.node,
                            showToolbar: false,
                            height: "100%",
                            footer: {
                                visible: false
                            },
                            dataSource: {
                                data: this.selectedDecisions
                            },
                            messaging: {
                                noRecordsMessage: this.currentStage != null ?
                                    "No decisions available for this stage." :
                                    "Process has not been assigned."
                            },
                            selectionMode: "none",
                            resizable: true,
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "#",
                                    width: "30px",
                                    template: (e) => {
                                        return this.generateId(e);
                                    },
                                    headerAttributes: {
                                        style: "text-align: center;padding-left:0;"
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Decision",
                                    width: "150px",
                                    template: (e) => {
                                        return this.generateLabel(e);
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "Action",
                                    template: (e) => {
                                        return this.generateDescription(e);
                                    }
                                })
                            ]
                        });
                    }
                    grid_fill() {
                        this.m_grid.get_dataSource().data(this.selectedDecisions);
                        this.grid.redraw();
                    }
                    generateId(decision) {
                        let result = "";
                        this.selectedDecisions.forEach((item, index) => {
                            if (item.id === decision.id) {
                                let colors = this.colors.getColor(index);
                                result += `<div role="decision-id" style="border-color:${colors.dark};background-color:${colors.light};">${index += 1}</div>`;
                            }
                        });
                        return result;
                    }
                    generateLabel(decision) {
                        let result = "";
                        if (this.isActiveStage) {
                            result = `<div role="decision-action" data-id="${decision.id}">${decision.name}</div>`;
                        }
                        else {
                            result = `<div role="decision-label">${decision.name}</div>`;
                        }
                        return result;
                    }
                    generateDescription(decision, includeIcon = true) {
                        let result = "";
                        let hasTargetStage = decision.targetStage != null;
                        let hasTargetStatus = decision.targetStatus != null;
                        let isStageChanged = hasTargetStage &&
                            decision.targetStage.id != this.selectedStage.id;
                        let isStatusChanged = hasTargetStatus &&
                            (decision.stageId != this.source.currentStage.id ||
                                decision.targetStatus.id != this.source.currentStatus.id);
                        if (isStageChanged) {
                            result += `Move to <b>${decision.targetStage.name}</b>`;
                        }
                        if (isStageChanged && isStatusChanged) {
                            result += " and ";
                        }
                        if (isStatusChanged) {
                            let iconPath = Jade.IconSet
                                .get("pd").resolve(decision.targetStatus.icon, Jade.IconSetSizeSpecificDirectory.x16);
                            result += `${!isStageChanged ? "S" : "s"}et to <b>${decision.targetStatus.name}</b>`;
                            result += includeIcon ? `<img src="${iconPath}" style="margin-left: 5px;vertical-align:text-bottom;"/>` : "";
                        }
                        result += !isStageChanged && !isStatusChanged ? "No change." : "";
                        return result;
                    }
                    setSelectedStage(stage) {
                        this.selectedStage = stage;
                        this.m_colors = new Process.ProcessColorPalette({
                            count: this.selectedDecisions.length
                        });
                        this.publishDecisionMapEvent();
                    }
                    publishDecisionMapEvent() {
                        let maps = [];
                        this.selectedDecisions.forEach((decision, index) => {
                            maps[maps.length] = {
                                stageId: decision.targetStage ? decision.targetStage.id : null,
                                color: this.colors.getColor(index),
                                index: index
                            };
                        });
                        this.eventBus.publish(Process.ProcessEvent.DecisionsMap, {
                            maps: maps
                        });
                    }
                    onStageSelect(e) {
                        this.setSelectedStage(e.stage);
                        this.grid_fill();
                    }
                    action_onClick(e) {
                        let decisionId = $(e.target).data("id");
                        let decision = this.grid.get_dataSource().get_instance().get(decisionId);
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                            title: "Execute Decision",
                            message: `
                    Execute the decision:<br/><br/>
                    <div style="padding-left: 20px;">
                        <b style="font-size:16px">${decision.name}</b><br/><br/>
                    </div>
                    Take the following action:<br/><br/>
                    <div style="padding-left: 20px;">
                        ${this.generateDescription(decision, false)}
                    </div>`,
                            select: (e) => {
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                                    this.executeDecision(decision);
                                }
                                e.close();
                            }
                        });
                    }
                    executeDecision(decision) {
                        let service = new PDJS.Services.Process.ProcessService();
                        service.executeDecision({
                            decisionId: decision.id,
                            entityId: this.source.entityId,
                            success: (e) => {
                                let response = new Process.ExecuteDecisionResponse(e.data);
                                response.handle();
                            }
                        });
                    }
                }
                Process.ProcessDecisionsList = ProcessDecisionsList;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessState extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_source = options.source;
                        this.state.unset("source", { silent: true });
                    }
                    get source() {
                        return this.m_source;
                    }
                    template() {
                        return `<div></div>`;
                    }
                    load(source) {
                        this.controls.clear();
                        this.m_source = source;
                        this.controls.add(new Process.ProcessStateLayout({
                            source: this.source
                        }));
                    }
                }
                Process.ProcessState = ProcessState;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessStateLayout extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_source = options.source;
                        this.state.unset("source", { silent: true });
                    }
                    get source() {
                        return this.m_source;
                    }
                    get showProcess() {
                        return this.source.showProcess &&
                            this.source.processName != null;
                    }
                    get showKey() {
                        return this.source.showKey &&
                            this.source.currentKey != null;
                    }
                    get showStage() {
                        return this.source.showStage &&
                            this.source.currentStage != null;
                    }
                    get showStatus() {
                        return this.source.showStatus &&
                            this.source.currentStatus != null;
                    }
                    get isHorizontalOrientation() {
                        return this.source.orientation ==
                            Canvas.Core.Process.ProcessStateOrientation.Horizontal;
                    }
                    get headNode() {
                        return this.node.find("div[role=head]");
                    }
                    get bodyNode() {
                        return this.node.find("div[role=body]");
                    }
                    template() {
                        return `<div>${this.isHorizontalOrientation ? `<div role="head"></div><div role="body"></div>` : ""}</div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.showProcess) {
                            this.addProcess();
                        }
                        if (this.showKey) {
                            this.addKey();
                        }
                        if (this.showStage) {
                            this.addStage();
                        }
                        if (this.showStatus) {
                            this.addStatus();
                        }
                        if (this.isHorizontalOrientation) {
                            this.headNode.css({
                                display: "flex",
                                flexDirection: "row",
                                alignContent: "space-evenly",
                                columnCount: this.source.displayedSectionCount,
                                flexBasis: 0
                            });
                            this.bodyNode.css({
                                display: "flex",
                                flexDirection: "row",
                                alignContent: "space-evenly",
                                columnCount: this.source.displayedSectionCount,
                                flexBasis: 0
                            });
                        }
                    }
                    getAttachment() {
                        let result = {
                            headNode: this.node,
                            bodyNode: this.node
                        };
                        if (this.isHorizontalOrientation) {
                            result = {
                                headNode: this.headNode,
                                bodyNode: this.bodyNode
                            };
                        }
                        return result;
                    }
                    addProcess() {
                        this.generateHeaderNode(`Process`);
                        this.generateContentNode(this.source.processName, "GEARS.PNG");
                    }
                    addKey() {
                        this.generateHeaderNode(`Key`);
                        this.generateContentNode(this.source.currentKey.name, this.source.currentKey.icon);
                    }
                    addStage() {
                        this.generateHeaderNode(`Stage`);
                        this.generateContentNode(this.source.currentStage.name, this.source.currentStage.icon);
                    }
                    addStatus() {
                        this.generateHeaderNode(`Status`);
                        this.generateContentNode(this.source.currentStatus.name, this.source.currentStatus.icon);
                    }
                    generateHeaderNode(text) {
                        let node = $(`<div role="header">${text}</div>`);
                        let target = this.getAttachment();
                        node.css({
                            height: this.source.itemHeight,
                            fontSize: `${this.source.fontSize}px`,
                            lineHeight: `1.10`,
                            padding: "5px",
                            width: this.isHorizontalOrientation ? "100%" : null,
                            textAlign: this.isHorizontalOrientation ? "center" : "left"
                        });
                        target.headNode.append(node);
                    }
                    generateContentNode(text, icon) {
                        let node = $(`<div role="content"></div>`);
                        let target = this.getAttachment();
                        node.css({
                            height: this.source.itemHeight,
                            fontSize: `${this.source.fontSize}px`,
                            lineHeight: `1.10`,
                            padding: "5px",
                            width: this.isHorizontalOrientation ? "100%" : null,
                            textAlign: this.isHorizontalOrientation ? "center" : "left"
                        });
                        if (icon) {
                            node.append(`<img src="${this.getIcon(icon)}" style="vertical-align:text-top;margin-right:5px;"/>`);
                        }
                        node.append(`<span>${text}</span>`);
                        target.bodyNode.append(node);
                    }
                    getIcon(icon) {
                        let result = null;
                        let iconSize = this.getIconSize();
                        if (icon != null) {
                            result = Jade.IconSet.get("pd").resolve(icon, iconSize);
                        }
                        return result;
                    }
                    getIconSize() {
                        let result = Jade.IconSetSizeSpecificDirectory.x16;
                        switch (true) {
                            case this.source.fontSize >= 48:
                                result = Jade.IconSetSizeSpecificDirectory.x48;
                                break;
                            case this.source.fontSize >= 32:
                                result = Jade.IconSetSizeSpecificDirectory.x32;
                                break;
                            case this.source.fontSize >= 24:
                                result = Jade.IconSetSizeSpecificDirectory.x24;
                                break;
                        }
                        return result;
                    }
                }
                Process.ProcessStateLayout = ProcessStateLayout;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                let ProcessViewCss;
                (function (ProcessViewCss) {
                    ProcessViewCss["StageCurrent"] = "-pdjs-stage-current";
                    ProcessViewCss["StageVisited"] = "-pdjs-stage-visited";
                    ProcessViewCss["StageSelected"] = "-pdjs-stage-selected";
                    ProcessViewCss["KeyCurrent"] = "-pdjs-key-current";
                    ProcessViewCss["KeyVisited"] = "-pdjs-key-visited";
                })(ProcessViewCss = Process.ProcessViewCss || (Process.ProcessViewCss = {}));
                class ProcessView extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_componentHeights = [];
                        this.m_source = options.source;
                        this.state.unset("source", { silent: true });
                    }
                    get eventBus() {
                        return Jade.Application.instance.contexts.current.events;
                    }
                    get source() {
                        return this.m_source;
                    }
                    get componentHeights() {
                        return this.m_componentHeights;
                    }
                    get gridNode() {
                        return this.node.find("div[role=grid]");
                    }
                    get styles() {
                        if (this.m_styles == null) {
                            this.m_styles = new PDJS.Shared.UI.StyleInjector({ id: this.ID });
                        }
                        return this.m_styles;
                    }
                    get keysComponent() {
                        return this.m_keysComponent;
                    }
                    get stagesComponent() {
                        return this.m_stagesComponent;
                    }
                    get clientHeight() {
                        return this.node.get(0).clientHeight;
                    }
                    get clientWidth() {
                        return this.node.get(0).clientWidth;
                    }
                    template() {
                        return `<div class="-pdjs-canvas-process-view">
                        <div role="grid" data-controls></div>
                    </div>`;
                    }
                    load(source) {
                        this.controls.clear();
                        this.m_source = source;
                        if (this.source.showKeys) {
                            this.keysComponent_init();
                        }
                        if (this.source.showStages) {
                            this.stagesComponent_init();
                        }
                        this.navigationComponent_init();
                        this.setSectionHeights();
                        this.addStyles();
                        this.setBorders();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.subscriptions.add(Process.ProcessEvent.StageSelect, (e) => {
                            this.onStageSelect(e);
                        });
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        this.styles.remove();
                    }
                    keysComponent_init() {
                        this.m_keysComponent = new Process.ProcessViewKeys({
                            eventBus: this.eventBus,
                            source: this.source
                        });
                        this.controls.add(this.m_keysComponent);
                    }
                    stagesComponent_init() {
                        this.m_stagesComponent = new Process.ProcessViewStageColumns({
                            eventBus: this.eventBus,
                            source: this.source
                        });
                        this.controls.add(this.m_stagesComponent);
                    }
                    navigationComponent_init() {
                        if (this.source.showStages) {
                            this.controls.add(new Process.ProcessViewNavigation({
                                source: this.source,
                                parentNode: this.m_stagesComponent.node,
                                offsetTop: this.source.keyHeight,
                                navigate: () => {
                                    this.m_keysComponent.node.scrollLeft(this.m_stagesComponent.node.scrollLeft());
                                    this.setBorders();
                                }
                            }));
                        }
                        else {
                            this.controls.add(new Process.ProcessViewNavigation({
                                source: this.source,
                                parentNode: this.m_keysComponent.node
                            }));
                        }
                    }
                    setSectionHeights() {
                        let heights = [];
                        if (this.source.showKeys) {
                            heights[heights.length] = `${this.source.keyHeight}px`;
                        }
                        if (this.source.showStages) {
                            heights[heights.length] = `1fr`;
                        }
                        this.gridNode.css({
                            gridTemplateRows: heights.join(" ")
                        });
                    }
                    addStyles() {
                        if (this.source.showVisitedKeys) {
                            this.styles.addStyle(`div[role=key].${ProcessViewCss.KeyVisited}`, {
                                backgroundColor: this.source.visitedKeyBackColor || "none",
                                borderWidth: `${this.source.visitedKeyBorderWidth}px`,
                                borderColor: this.source.visitedKeyBorderColor || "none",
                                color: this.source.visitedKeyForeColor || "var(--visiv-theme-input-text-color)"
                            });
                        }
                        if (this.source.showCurrentKey) {
                            this.styles.addStyle(`div[role=key].${ProcessViewCss.KeyCurrent}`, {
                                backgroundColor: `${this.source.currentKeyBackColor || "none"} !important`,
                                borderWidth: `${this.source.currentKeyBorderWidth}px !important`,
                                borderColor: `${this.source.currentKeyBorderColor || "none"} !important`,
                                color: `${this.source.currentKeyForeColor || "var(--visiv-theme-input-text-color)"} !important`
                            });
                        }
                        if (this.source.showVisitedStages) {
                            this.styles.addStyle(`div[role=stage].${ProcessViewCss.StageVisited}`, {
                                backgroundColor: this.source.visitedStageBackColor || "none",
                                borderWidth: `${this.source.visitedStageBorderWidth}px`,
                                borderColor: this.source.visitedStageBorderColor || "none",
                                color: this.source.visitedStageForeColor || "var(--visiv-theme-input-text-color)"
                            });
                        }
                        if (this.source.showCurrentStage) {
                            this.styles.addStyle(`div[role=stage].${ProcessViewCss.StageCurrent}`, {
                                backgroundColor: this.source.currentStageBackColor || "none",
                                borderWidth: `${this.source.currentStageBorderWidth}px`,
                                borderColor: this.source.currentStageBorderColor || "none",
                                color: this.source.currentStageForeColor || "var(--visiv-theme-input-text-color)"
                            });
                        }
                        this.styles.addStyle(`div[role=stage].${ProcessViewCss.StageSelected}`, {
                            backgroundColor: this.source.selectedStageBackColor || "none",
                            borderWidth: `${this.source.selectedStageBorderWidth}px`,
                            borderColor: this.source.selectedStageBorderColor || "none",
                            color: this.source.selectedStageForeColor || "#000000"
                        });
                        this.styles.inject();
                        this.node.addClass(this.styles.rootClass);
                    }
                    onStageSelect(e) {
                        this.gridNode
                            .find(`.${ProcessViewCss.StageSelected}`)
                            .removeClass(`${ProcessViewCss.StageSelected}`);
                    }
                    setBorders() {
                        this.setRightBorder();
                        this.setBottomBorder();
                    }
                    setRightBorder() {
                        let columnCount = this.source.keys.length;
                        let columnWidth = this.source.gridColumnWidth;
                        let scrollX = this.stagesComponent != null ?
                            this.stagesComponent.scrollPositionX :
                            this.keysComponent.scrollPositionX;
                        let showRightBorder = this.clientWidth > (columnCount * columnWidth) || (this.clientWidth % columnWidth) != 0;
                        this.node.css({
                            borderRight: showRightBorder ? "1px solid var(--visiv-theme-input-border-color)" : "none"
                        });
                    }
                    setBottomBorder() {
                        let rowCount = this.source.rowCount;
                        let rowHeight = this.source.stageHeight;
                        let scrollY = this.stagesComponent != null ?
                            this.stagesComponent.scrollPositionY : 0;
                        let showBottomBorder = this.clientHeight > (rowCount * rowHeight) || (this.clientHeight % rowHeight) != 0;
                        this.node.css({
                            borderBottom: showBottomBorder ? "1px solid var(--visiv-theme-input-border-color)" : null
                        });
                    }
                }
                Process.ProcessView = ProcessView;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewComponent extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get eventBus() {
                        return Jade.Application.instance.contexts.current.events;
                    }
                    get source() {
                        return this.m_source;
                    }
                    template() {
                        return `<div></div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_source = this.state.get("source");
                        this.state.unset("source", { silent: true });
                    }
                }
                Process.ProcessViewComponent = ProcessViewComponent;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewDecisionMap extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get map() {
                        return this.state.get("map");
                    }
                    get maps() {
                        return this.m_maps;
                    }
                    template() {
                        return `<div role="decision-map"></div>`;
                    }
                    addMap(map) {
                        if (map != null) {
                            this.maps[this.maps.length] = map;
                            this.build();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_maps = [];
                        this.maps[this.maps.length] = this.map;
                        this.build();
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        PDJS.Shared.PopOver.remove(this.node);
                    }
                    build() {
                        this.maps.length === 1 ?
                            this.buildSingleView() : this.buildMultiView();
                    }
                    buildSingleView() {
                        let map = this.maps[0];
                        this.node.text(map.index + 1);
                        this.node.css({
                            borderColor: map.color.dark,
                            backgroundColor: map.color.light
                        });
                    }
                    buildMultiView() {
                        PDJS.Shared.PopOver.remove(this.node);
                        let tooltipNode = $(`<div class="-pdjs-canvas-process-view-map-tooltip"></div>`);
                        this.node.text("++");
                        this.node.css({
                            borderColor: "#CCCCCC",
                            backgroundColor: "#EEEEEE"
                        });
                        this.maps.forEach(map => {
                            let mapNode = $(`<div role="decision-map">${map.index + 1}</div>`);
                            mapNode.css({
                                borderColor: map.color.dark,
                                backgroundColor: map.color.light
                            });
                            tooltipNode.append(mapNode);
                        });
                        PDJS.Shared.PopOver.tooltip(this.node, tooltipNode);
                    }
                }
                Process.ProcessViewDecisionMap = ProcessViewDecisionMap;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewKey extends Process.ProcessViewComponent {
                    constructor(options) {
                        super(options);
                    }
                    get keySource() {
                        return this.state.get("keySource");
                    }
                    get labelNode() {
                        return this.node.find("label");
                    }
                    template() {
                        return `<div role="key">
                        <div>
                            <img src="${Jade.IconSet.get("pd").resolve(this.keySource.icon, Jade.IconSetSizeSpecificDirectory.x48)}" />
                        </div>
                        <label>${this.keySource.name}</label>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            height: `${this.source.keyHeight}px`
                        });
                        this.labelNode.css({
                            fontSize: `${this.source.keyFontSize}px`
                        });
                        if (this.source.showCurrentKey) {
                            this.enableCurrentCssClass(this.isKeyCurrent());
                        }
                        if (this.source.showVisitedKeys) {
                            this.enableVisitedCssClass(this.isKeyVisited());
                        }
                    }
                    enableCurrentCssClass(enabled) {
                        if (enabled) {
                            this.node.addClass(Process.ProcessViewCss.KeyCurrent);
                        }
                        else {
                            this.node.removeClass(Process.ProcessViewCss.KeyCurrent);
                        }
                    }
                    enableVisitedCssClass(enabled) {
                        if (enabled) {
                            this.node.addClass(Process.ProcessViewCss.KeyVisited);
                        }
                        else {
                            this.node.removeClass(Process.ProcessViewCss.KeyVisited);
                        }
                    }
                    isKeyVisited() {
                        return this.keySource.visited;
                    }
                    isKeyCurrent() {
                        let result = false;
                        if (this.source.currentStage != null) {
                            result = this.source.currentStage.keyId == this.keySource.id;
                        }
                        return result;
                    }
                }
                Process.ProcessViewKey = ProcessViewKey;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewKeys extends Process.ProcessViewComponent {
                    get scrollPositionX() {
                        return this.node.get(0).scrollLeft;
                    }
                    template() {
                        return `<div role="keys"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.createKeys();
                    }
                    createKeys() {
                        this.source.keys.forEach(key => {
                            this.controls.add(new Process.ProcessViewKey({
                                eventBus: this.eventBus,
                                keySource: key,
                                source: this.source
                            }));
                        });
                        this.node.css({
                            height: `${this.source.keyHeight}px`
                        });
                        this.node.append(`<div role="key-filler"></div>`);
                        this.setColumnWidths();
                    }
                    setColumnWidths() {
                        let widths = [];
                        let width = this.source.gridColumnWidth;
                        this.source.keys.forEach((key, index) => {
                            let isFirstOrLast = index == 0 || index == this.source.keys.length - 1;
                            let appliedWidth = isFirstOrLast ? width - 1 : width;
                            widths[widths.length] = `${width}px`;
                        });
                        widths[widths.length] = "1fr";
                        this.node.css({
                            gridTemplateColumns: widths.join(" ")
                        });
                    }
                }
                Process.ProcessViewKeys = ProcessViewKeys;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewNavigation extends Process.ProcessViewComponent {
                    constructor(options) {
                        super(options);
                    }
                    get parentNode() {
                        return this.state.get("parentNode");
                    }
                    get scrollHeight() {
                        return this.parentNode.get(0).scrollHeight;
                    }
                    get scrollWidth() {
                        return this.parentNode.get(0).scrollWidth;
                    }
                    get clientHeight() {
                        return this.parentNode.get(0).clientHeight;
                    }
                    get clientWidth() {
                        return this.parentNode.get(0).clientWidth;
                    }
                    get overflowedRight() {
                        return (this.scrollWidth - this.clientWidth) > 0;
                    }
                    get overflowedBottom() {
                        return (this.scrollHeight - this.clientHeight) > 0;
                    }
                    get scrollTop() {
                        return this.parentNode.get(0).scrollTop;
                    }
                    get scrollLeft() {
                        return this.parentNode.get(0).scrollLeft;
                    }
                    get canScrollTop() {
                        return this.vScroll &&
                            this.scrollTop > 0;
                    }
                    get canScrollRight() {
                        return this.hScroll &&
                            (this.scrollLeft + this.clientWidth) < this.scrollWidth - 1;
                    }
                    get canScrollBottom() {
                        return this.vScroll &&
                            (this.scrollTop + this.clientHeight) < this.scrollHeight - 1;
                    }
                    get canScrollLeft() {
                        return this.hScroll &&
                            this.scrollLeft > 0;
                    }
                    get topNode() {
                        return this.node.find("img[role=top]");
                    }
                    get bottomNode() {
                        return this.node.find("img[role=bottom]");
                    }
                    get rightNode() {
                        return this.node.find("img[role=right]");
                    }
                    get leftNode() {
                        return this.node.find("img[role=left]");
                    }
                    get hScroll() {
                        return this.state.get("hScroll", true);
                    }
                    get vScroll() {
                        return this.state.get("vScroll", true);
                    }
                    get shiftWidth() {
                        return this.source.gridColumnWidth;
                    }
                    get shiftHeight() {
                        return this.source.stageHeight;
                    }
                    get navNodes() {
                        return this.node.find("img");
                    }
                    get offsetTop() {
                        return this.state.get("offsetTop", 0);
                    }
                    get navigateCallback() {
                        return this.state.get("navigate", () => { });
                    }
                    template() {
                        return `<div class="-pdjs-canvas-process-view-nav">
                        <div style="top:${this.offsetTop}px;">
                            <img role="top" src="${Jade.IconSet.get("pdjs").resolve("nav_up.png", Jade.IconSetSizeSpecificDirectory.x24)}"/>     
                        </div>
                        <div style="top:${this.offsetTop}px;">
                            <img role="right" src="${Jade.IconSet.get("pdjs").resolve("nav_right.png", Jade.IconSetSizeSpecificDirectory.x24)}"/>
                        </div>
                        <div>
                            <img role="bottom" src="${Jade.IconSet.get("pdjs").resolve("nav_down.png", Jade.IconSetSizeSpecificDirectory.x24)}"/>
                        </div>
                        <div style="top:${this.offsetTop}px;">
                            <img role="left" src="${Jade.IconSet.get("pdjs").resolve("nav_left.png", Jade.IconSetSizeSpecificDirectory.x24)}"/>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.navNodes.on(Jade.BrowserEvent.MOUSEENTER, _.bind(this.showNavNodes, this));
                        this.navNodes.on(Jade.BrowserEvent.MOUSELEAVE, _.bind(this.hideNavNodes, this));
                        this.parentNode.on(Jade.BrowserEvent.MOUSEENTER, _.bind(this.showNavNodes, this));
                        this.parentNode.on(Jade.BrowserEvent.MOUSELEAVE, _.bind(this.hideNavNodes, this));
                        this.topNode.on(Jade.BrowserEvent.CLICK, _.bind(this.navTopNode_onClick, this));
                        this.rightNode.on(Jade.BrowserEvent.CLICK, _.bind(this.navRightNode_onClick, this));
                        this.bottomNode.on(Jade.BrowserEvent.CLICK, _.bind(this.navBottomNode_onClick, this));
                        this.leftNode.on(Jade.BrowserEvent.CLICK, _.bind(this.navLeftNode_onClick, this));
                        this.showNavNodes();
                    }
                    showNavNodes() {
                        this.canScrollBottom ? this.bottomNode.show() : this.bottomNode.hide();
                        this.canScrollLeft ? this.leftNode.show() : this.leftNode.hide();
                        this.canScrollRight ? this.rightNode.show() : this.rightNode.hide();
                        this.canScrollTop ? this.topNode.show() : this.topNode.hide();
                    }
                    hideNavNodes() {
                        this.bottomNode.hide();
                        this.leftNode.hide();
                        this.rightNode.hide();
                        this.topNode.hide();
                    }
                    navTopNode_onClick(e) {
                        if (this.canScrollTop) {
                            this.parentNode.scrollTop(this.scrollTop - this.shiftHeight);
                            this.showNavNodes();
                            this.navigateCallback();
                        }
                    }
                    navRightNode_onClick(e) {
                        if (this.canScrollRight) {
                            this.parentNode.scrollLeft(this.scrollLeft + this.shiftWidth);
                            this.showNavNodes();
                            this.navigateCallback();
                        }
                    }
                    navBottomNode_onClick(e) {
                        if (this.canScrollBottom) {
                            this.parentNode.scrollTop(this.scrollTop + this.shiftHeight);
                            this.showNavNodes();
                            this.navigateCallback();
                        }
                    }
                    navLeftNode_onClick(e) {
                        if (this.canScrollLeft) {
                            this.parentNode.scrollLeft(this.scrollLeft - this.shiftWidth);
                            this.showNavNodes();
                            this.navigateCallback();
                        }
                    }
                }
                Process.ProcessViewNavigation = ProcessViewNavigation;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewStage extends Process.ProcessViewComponent {
                    constructor(options) {
                        super(options);
                    }
                    get stageSource() {
                        return this.state.get("stageSource");
                    }
                    get labelNode() {
                        return this.node.find("label");
                    }
                    get map() {
                        return this.controls.getByType(Process.ProcessViewDecisionMap).first();
                    }
                    template() {
                        return `<div role="stage" style="position:relative;">
                        <label>${this.stageSource.name}</label>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let isCurrentStage = this.stageSource.id == this.source.currentStage.id;
                        let isVisitedStage = this.stageSource.visited;
                        if (this.source.showCurrentStage) {
                            this.enableCurrentCssClass(isCurrentStage);
                        }
                        if (this.source.showVisitedStages) {
                            this.enableVisitedCssClass(isVisitedStage);
                        }
                        this.labelNode.css({
                            fontSize: `${this.source.stageFontSize}px`
                        });
                        this.node.on(Jade.BrowserEvent.CLICK, () => {
                            this.eventBus.publish(Process.ProcessEvent.StageSelect, {
                                stage: this.stageSource,
                            });
                        });
                        this.subscriptions.add(Process.ProcessEvent.DecisionsMap, (e) => {
                            this.onDecisionsMap(e);
                        });
                        this.subscriptions.add(Process.ProcessEvent.StageSelect, (e) => {
                            this.onStageSelect(e);
                        });
                    }
                    enableCurrentCssClass(enabled) {
                        if (enabled) {
                            this.node.addClass("-pdjs-stage-current");
                        }
                    }
                    enableSelectedCssClass(enabled) {
                        if (enabled) {
                            this.node.addClass("-pdjs-stage-selected");
                        }
                    }
                    enableVisitedCssClass(enabled) {
                        if (enabled) {
                            this.node.addClass("-pdjs-stage-visited");
                        }
                    }
                    onStageSelect(e) {
                        this.enableSelectedCssClass(this.stageSource.id == e.stage.id);
                    }
                    onDecisionsMap(e) {
                        let filteredMaps = e.maps.filter(map => {
                            return map.stageId == this.stageSource.id;
                        });
                        if (this.map != null) {
                            this.controls.remove(this.map);
                        }
                        filteredMaps.forEach(map => {
                            if (this.map == null) {
                                this.controls.add(new Process.ProcessViewDecisionMap({
                                    map: map
                                }));
                            }
                            else {
                                this.map.addMap(map);
                            }
                        });
                    }
                }
                Process.ProcessViewStage = ProcessViewStage;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcesViewStageColumn extends Process.ProcessViewComponent {
                    constructor(options) {
                        super(options);
                    }
                    get keySource() {
                        return this.state.get("keySource");
                    }
                    get stages() {
                        return this.controls.getByType(Process.ProcessViewStage);
                    }
                    get isFirstOrLast() {
                        return this.state.get("isFirstOrLast");
                    }
                    template() {
                        return `<div role="stage-column" key-id="${this.keySource.id}"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let appliedWidth = this.isFirstOrLast ?
                            this.source.gridColumnWidth - 1 : this.source.gridColumnWidth;
                        this.generateStages();
                        this.calculateStageCounts();
                        this.node.css({
                            width: `${this.source.gridColumnWidth}px`,
                            minWidth: `${this.source.gridColumnWidth}px`,
                            minHeight: `${this.source.stageHeight * this.m_maxStageCount}px`,
                            gridTemplateRows: this.generateGridTemplateRowsStyle()
                        });
                    }
                    generateStages() {
                        this.m_stageCount = 0;
                        this.source.stages.forEach(stage => {
                            if (this.keySource.id === stage.keyId) {
                                this.controls.add(new Process.ProcessViewStage({
                                    eventBus: this.eventBus,
                                    stageSource: stage,
                                    source: this.source
                                }));
                                this.m_stageCount += 1;
                            }
                        });
                        this.node.append(`<div role="stage-filler"></div>`);
                    }
                    calculateStageCounts() {
                        this.m_maxStageCount = 0;
                        let keys = {};
                        this.source.stages.forEach(stage => {
                            let array = null;
                            if (keys[stage.keyId] === undefined) {
                                array = keys[stage.keyId] = [];
                            }
                            array = keys[stage.keyId];
                            array[array.length] = stage.id;
                        });
                        Object.keys(keys).forEach(key => {
                            if (keys[key].length > this.m_maxStageCount) {
                                this.m_maxStageCount = keys[key].length;
                            }
                        });
                    }
                    generateGridTemplateRowsStyle() {
                        let values = [];
                        let height = this.source.stageHeight;
                        for (let i = 0; i < this.m_stageCount; i++) {
                            let isFirstOrLast = i == 0 || i == this.m_stageCount - 1;
                            let appliedHeight = isFirstOrLast ? height - 1 : height;
                            values[i] = `${height}px`;
                        }
                        return `${values.join(" ")} 1fr`;
                    }
                }
                Process.ProcesViewStageColumn = ProcesViewStageColumn;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Process;
            (function (Process) {
                class ProcessViewStageColumns extends Process.ProcessViewComponent {
                    get scrollPositionX() {
                        return this.node.get(0).scrollLeft;
                    }
                    get scrollPositionY() {
                        return this.node.get(0).scrollTop;
                    }
                    template() {
                        return `<div role="stages"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.columns_init();
                    }
                    columns_init() {
                        this.source.keys.forEach((key, index) => {
                            this.controls.add(new Process.ProcesViewStageColumn({
                                source: this.source,
                                keySource: key,
                                eventBus: this.eventBus
                            }));
                        });
                        this.node.append(`<div role="stage-column-filler"></div>`);
                        this.setColumnWidths();
                    }
                    setColumnWidths() {
                        let widths = [];
                        let width = this.source.gridColumnWidth;
                        this.source.keys.forEach((key, index) => {
                            let isFirstOrLast = index == 0 || index == this.source.keys.length - 1;
                            let appliedWidth = isFirstOrLast ? width - 1 : width;
                            widths[widths.length] = `${width}px`;
                        });
                        widths[widths.length] = "1fr";
                        this.node.css({
                            gridTemplateColumns: widths.join(" ")
                        });
                    }
                }
                Process.ProcessViewStageColumns = ProcessViewStageColumns;
            })(Process = Shared.Process || (Shared.Process = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class Shape extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get nodeHeight() {
                        return this.node.outerHeight(true);
                    }
                    get nodeWidth() {
                        return this.node.outerWidth(true);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderStyle() {
                        return this.state.get("borderStyle");
                    }
                    set borderStyle(value) {
                        this.state.set("borderStyle", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                    template() {
                        return `<div role="shape" style="position:absolute;top:0;left:0;right:0;bottom:0;"></div>`;
                    }
                }
                Shapes.Shape = Shape;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class Ellipse extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.setStyles();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setStyles();
                    }
                    setStyles() {
                        this.node.css({
                            borderRadius: "50%",
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle
                        });
                        this.node.get(0).style.backgroundColor = this.backgroundColor;
                        this.node.get(0).style.borderColor = this.borderColor;
                    }
                }
                Shapes.Ellipse = Ellipse;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class LinePaths {
                    static line(l) {
                        let left = 0;
                        let right = l.width;
                        let top = (l.height - l.lineWeight) / 2;
                        let bottom = ((l.height - l.lineWeight) / 2) + l.lineWeight;
                        switch (l.startCapShape) {
                            case Canvas.Core.Shapes.LineCapShape.circle:
                                left = l.startCapWidth / 2;
                                break;
                            case Canvas.Core.Shapes.LineCapShape.triangle:
                                left = l.startCapWidth;
                        }
                        switch (l.endCapShape) {
                            case Canvas.Core.Shapes.LineCapShape.circle:
                                right = l.width - (l.endCapWidth / 2);
                                break;
                            case Canvas.Core.Shapes.LineCapShape.triangle:
                                right = l.width - l.endCapWidth;
                        }
                        return `M ${left},${top} L${right},${top} L${right},${bottom} L${left},${bottom} Z`;
                    }
                    static startCap(l) {
                        let result = "";
                        switch (l.startCapShape) {
                            case Canvas.Core.Shapes.LineCapShape.circle:
                                result = this.startCapCircle(l);
                                break;
                            case Canvas.Core.Shapes.LineCapShape.square:
                                result = this.startCapSquare(l);
                                break;
                            case Canvas.Core.Shapes.LineCapShape.triangle:
                                result = this.startCapTriangle(l);
                                break;
                        }
                        return result;
                    }
                    static endCap(l) {
                        let result = "";
                        switch (l.endCapShape) {
                            case Canvas.Core.Shapes.LineCapShape.circle:
                                result = this.endCapCircle(l);
                                break;
                            case Canvas.Core.Shapes.LineCapShape.square:
                                result = this.endCapSquare(l);
                                break;
                            case Canvas.Core.Shapes.LineCapShape.triangle:
                                result = this.endCapTriangle(l);
                                break;
                        }
                        return result;
                    }
                    static endCapTriangle(l) {
                        let x1 = (l.width - l.endCapWidth);
                        let y1 = (l.height - l.endCapHeight) / 2;
                        let x2 = l.width;
                        let y2 = (l.height / 2);
                        let x3 = (l.width - l.endCapWidth);
                        let y3 = ((l.height - l.endCapHeight) / 2) + l.endCapHeight;
                        return `M ${x1},${y1} L${x2},${y2} L${x3},${y3} Z`;
                    }
                    static startCapTriangle(l) {
                        let x1 = 0;
                        let y1 = (l.height / 2);
                        let x2 = l.startCapWidth;
                        let y2 = (l.height - l.startCapHeight) / 2;
                        let x3 = l.startCapWidth;
                        let y3 = ((l.height - l.startCapHeight) / 2) + l.startCapHeight;
                        return `M ${x1},${y1} L${x2},${y2} L${x3},${y3} Z`;
                    }
                    static endCapCircle(l) {
                        let xAxis = l.width - l.endCapWidth;
                        let yAxis = l.height / 2;
                        let xRadius = l.endCapWidth / 2;
                        let yRadius = l.endCapHeight / 2;
                        let height = l.endCapHeight;
                        let width = l.endCapWidth;
                        return `M ${xAxis}, ${yAxis} 
                    a ${xRadius},${yRadius} 0 1,0 ${width}, 0
                    a ${xRadius},${yRadius} 0 1,0 -${width},0 Z`;
                    }
                    static startCapCircle(l) {
                        let xAxis = 0;
                        let yAxis = l.height / 2;
                        let xRadius = l.startCapWidth / 2;
                        let yRadius = l.startCapHeight / 2;
                        let height = l.startCapHeight;
                        let width = l.startCapWidth;
                        return `M ${xAxis}, ${yAxis} 
                    a ${xRadius},${yRadius} 0 1,0 ${width}, 0
                    a ${xRadius},${yRadius} 0 1,0 -${width},0 Z`;
                    }
                    static endCapSquare(l) {
                        let topY = ((l.height - l.endCapHeight) / 2);
                        let bottomY = ((l.height - l.endCapHeight) / 2) + l.endCapHeight;
                        let x1 = (l.width - l.endCapWidth);
                        let y1 = topY;
                        let x2 = l.width;
                        let y2 = topY;
                        let x3 = l.width;
                        let y3 = bottomY;
                        let x4 = (l.width - l.endCapWidth);
                        let y4 = bottomY;
                        return `M ${x1},${y1} L${x2},${y2} L${x3},${y3} L${x4},${y4} Z`;
                    }
                    static startCapSquare(l) {
                        let topY = ((l.height - l.startCapHeight) / 2);
                        let bottomY = ((l.height - l.startCapHeight) / 2) + l.startCapHeight;
                        let x1 = 0;
                        let y1 = topY;
                        let x2 = l.startCapWidth;
                        let y2 = topY;
                        let x3 = l.startCapWidth;
                        let y3 = bottomY;
                        let x4 = 0;
                        let y4 = bottomY;
                        return `M ${x1},${y1} L${x2},${y2} L${x3},${y3} L${x4},${y4} Z`;
                    }
                }
                Shapes.LinePaths = LinePaths;
                class Line extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get height() {
                        return this.node.outerHeight(true);
                    }
                    get width() {
                        return this.node.outerWidth(true);
                    }
                    get lineColor() {
                        return this.state.get("lineColor");
                    }
                    set lineColor(value) {
                        this.state.set("lineColor", value);
                    }
                    get startCapShape() {
                        return this.state.get("startCapShape");
                    }
                    set startCapShape(value) {
                        this.state.set("startCapShape", value);
                    }
                    get startCapHeight() {
                        return this.state.get("startCapHeight");
                    }
                    set startCapHeight(value) {
                        this.state.set("startCapHeight", value);
                    }
                    get startCapWidth() {
                        return this.state.get("startCapWidth");
                    }
                    set startCapWidth(value) {
                        this.state.set("startCapWidth", value);
                    }
                    get startCapColor() {
                        return this.state.get("startCapColor");
                    }
                    set startCapColor(value) {
                        this.state.set("startCapColor", value);
                    }
                    get endCapShape() {
                        return this.state.get("endCapShape");
                    }
                    set endCapShape(value) {
                        this.state.set("endCapShape", value);
                    }
                    get endCapHeight() {
                        return this.state.get("endCapHeight");
                    }
                    set endCapHeight(value) {
                        this.state.set("endCapHeight", value);
                    }
                    get endCapWidth() {
                        return this.state.get("endCapWidth");
                    }
                    set endCapWidth(value) {
                        this.state.set("endCapWidth", value);
                    }
                    get endCapColor() {
                        return this.state.get("endCapColor");
                    }
                    set endCapColor(value) {
                        this.state.set("endCapColor", value);
                    }
                    get lineWeight() {
                        return this.state.get("lineWeight");
                    }
                    set lineWeight(value) {
                        this.state.set("lineWeight", value);
                    }
                    template() {
                        return `<div role="shape" style="position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;"></div>`;
                    }
                    redraw() {
                        if (this.node == null) {
                            return;
                        }
                        let line = this.node.find(`svg defs path[id=line${this.ID}]`);
                        let startCap = this.node.find(`svg defs path[id=startCap${this.ID}]`);
                        let endCap = this.node.find(`svg defs path[id=endCap${this.ID}]`);
                        let useLine = this.node.find("svg g use[data-id=line]");
                        let useStartCap = this.node.find("svg g use[data-id=startCap]");
                        let useEndCap = this.node.find("svg g use[data-id=endCap]");
                        let svg = this.node.find("svg");
                        useLine.attr("fill", this.lineColor);
                        useStartCap.attr("fill", this.startCapColor);
                        useEndCap.attr("fill", this.endCapColor);
                        svg.attr("height", this.height);
                        svg.attr("width", this.width);
                        line.attr("d", LinePaths.line(this));
                        startCap.attr("d", LinePaths.startCap(this));
                        endCap.attr("d", LinePaths.endCap(this));
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.empty();
                        this.node.append(this.content());
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.redraw();
                    }
                    content() {
                        return `
                <svg width="${this.width}" height="${this.height}">
	                <defs>
		                <path
			                id="line${this.ID}"
			                d="${LinePaths.line(this)}"/>
                        <path
			                id="startCap${this.ID}"
			                d="${LinePaths.startCap(this)}"/>
                        <path
			                id="endCap${this.ID}"
			                d="${LinePaths.endCap(this)}"/>
	                </defs>
	                <g>
		                <use
			                xlink:href="#line${this.ID}"
			                fill="${this.lineColor}" 
                            data-id="line" />
                        <use
			                xlink:href="#startCap${this.ID}"
			                fill="${this.startCapColor}" 
                            data-id="startCap" />
                        <use
			                xlink:href="#endCap${this.ID}"
			                fill="${this.endCapColor}" 
                            data-id="endCap" />
	                </g>
                </svg>
            `;
                    }
                }
                Shapes.Line = Line;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class Rectangle extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                    }
                    get borderRadius() {
                        return this.state.get("borderRadius");
                    }
                    set borderRadius(value) {
                        this.state.set("borderRadius", value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.setStyles();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setStyles();
                    }
                    setStyles() {
                        this.node.css({
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle,
                            borderRadius: this.borderRadius
                        });
                        this.node.get(0).style.backgroundColor = this.backgroundColor;
                        this.node.get(0).style.borderColor = this.borderColor;
                    }
                }
                Shapes.Rectangle = Rectangle;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class Triangle extends Shapes.Shape {
                    constructor(options) {
                        super(options);
                    }
                    get svgID() {
                        return `SVG-${this.ID}`;
                    }
                    get height() {
                        return this.state.get("height");
                    }
                    set height(value) {
                        this.state.set("height", value);
                    }
                    get width() {
                        return this.state.get("width");
                    }
                    set width(value) {
                        this.state.set("width", value);
                    }
                    get rotation() {
                        return this.state.get("rotation", Canvas.Core.Shapes.TriangleRotation.rotate0);
                    }
                    set rotation(value) {
                        this.state.set("rotation", value);
                    }
                    redraw() {
                        if (this.node == null) {
                            return;
                        }
                        let path = this.node.find("svg defs path");
                        let use = this.node.find("svg g use");
                        let svg = this.node.find("svg");
                        use.attr("stroke", this.borderColor);
                        use.attr("stroke-width", this.strokeWidth());
                        use.attr("stroke-dasharray", this.strokeStyle());
                        use.attr("fill", this.backgroundColor);
                        svg.attr("height", this.height);
                        svg.attr("width", this.width);
                        path.attr("d", this.getShapePath());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.empty();
                        this.node.append(this.content());
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.redraw();
                    }
                    getDefaultOptions() {
                        return {
                            rotation: Canvas.Core.Shapes.TriangleRotation.rotate0
                        };
                    }
                    getShapePath() {
                        return "";
                    }
                    content() {
                        return `<svg width="${this.width}" height="${this.height}">
                        <defs>
	                        <path
                                id="${this.svgID}" 
                                d="${this.getShapePath()}"/>
                            <clipPath
                                id="clip${this.svgID}">
		                        <use
                                    xlink:href="#${this.svgID}"/>
	                        </clipPath>
                        </defs>
                        <g>
	                        <use
                                xlink:href="#${this.svgID}" 
                                stroke="${this.borderColor}" 
                                stroke-width="${this.borderWidth * 2}" 
                                fill="${this.backgroundColor}" 
                                clip-path="url(#clip${this.svgID})"/>
                        </g>
                    </svg>`;
                    }
                    strokeWidth() {
                        let result = 0;
                        if (this.borderStyle == "none") {
                            result = 0;
                        }
                        else {
                            result = parseInt(this.borderWidth.toString()) * 2;
                        }
                        return result;
                    }
                    strokeStyle() {
                        let result = "";
                        switch (this.borderStyle) {
                            case "dashed":
                                result = "11 6";
                                break;
                            case "dotted":
                                result = "5 5";
                                break;
                        }
                        return result;
                    }
                }
                Shapes.Triangle = Triangle;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class IsoscelesTriangle extends Shapes.Triangle {
                    constructor(options) {
                        super(options);
                    }
                    getShapePath() {
                        let result = null;
                        let height = this.nodeHeight;
                        let width = this.nodeWidth;
                        switch (this.rotation) {
                            case Canvas.Core.Shapes.TriangleRotation.rotate0:
                                result = `M ${width / 2},0 L 0,${height} L ${width},${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate90:
                                result = `M 0,0 L ${width},${height / 2} L 0,${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate180:
                                result = `M 0,0 L ${width},0 L ${width / 2},${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate270:
                                result = `M 0,${height / 2} L ${width},0 L ${width},${height} Z`;
                                break;
                        }
                        return result;
                    }
                }
                Shapes.IsoscelesTriangle = IsoscelesTriangle;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Shapes;
            (function (Shapes) {
                class RightTriangle extends Shapes.Triangle {
                    constructor(options) {
                        super(options);
                    }
                    getShapePath() {
                        let result = "";
                        let height = this.nodeHeight;
                        let width = this.nodeWidth;
                        switch (this.rotation) {
                            case Canvas.Core.Shapes.TriangleRotation.rotate0:
                                result = `M 0,0 L${width},0 L${width},${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate90:
                                result = `M ${width},0 L${width},${height} L0,${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate180:
                                result = `M 0,0 L${width},${height} L0,${height} Z`;
                                break;
                            case Canvas.Core.Shapes.TriangleRotation.rotate270:
                                result = `M 0,0 L${width},0 L0,${height} Z`;
                                break;
                        }
                        return result;
                    }
                }
                Shapes.RightTriangle = RightTriangle;
            })(Shapes = Shared.Shapes || (Shared.Shapes = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Views;
            (function (Views) {
                class ViewCommandBase extends Jade.Command {
                    get view() {
                        return CanvasJS.Design.Environment.selection.first();
                    }
                    get component() {
                        return this.view;
                    }
                    get viewStateId() {
                        return this.component.viewStateId;
                    }
                    hasGrid() {
                        return Jade.InterfaceGuard.is(this.view, Views.IViewComponentGuard);
                    }
                    get grid() {
                        return this.view.grid;
                    }
                    getDefaultValuesForProps() {
                        return {
                            enabled: true,
                            display: "label icon",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = CanvasJS.Design.Environment.selection.count == 1
                            && Jade.InterfaceGuard.is(this.view, Views.IViewComponentGuard);
                    }
                    createContext() {
                        this.m_context = Jade.Application.instance.contexts.createContext({
                            name: "view-filters",
                            makeDefault: true
                        });
                    }
                    destroyContext() {
                        if (this.m_context != null) {
                            Jade.Application.instance.contexts.destroyContext({
                                id: this.m_context.ID
                            });
                        }
                    }
                }
                Views.ViewCommandBase = ViewCommandBase;
            })(Views = Shared.Views || (Shared.Views = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Views;
            (function (Views) {
                class ViewDesignerCommand extends Views.ViewCommandBase {
                    getDefaultValuesForProps() {
                        return _.extend(super.getDefaultValuesForProps(), {
                            id: "view/designer",
                            label: "Designer",
                            tooltip: "Edit the view of the selected element.",
                            icon: "pencil_and_square.png"
                        });
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.visible = this.enabled;
                    }
                    onExecute(e) {
                        PDJS.Manage.Views.ViewDesignerDialog.open({
                            viewStateId: this.viewStateId,
                            select: {
                                ok: (sender, e) => {
                                    if (this.grid != null) {
                                        this.grid.build();
                                    }
                                }
                            }
                        });
                    }
                }
                Views.ViewDesignerCommand = ViewDesignerCommand;
            })(Views = Shared.Views || (Shared.Views = {}));
        })(Shared = Canvas.Shared || (Canvas.Shared = {}));
    })(Canvas = PDJS.Canvas || (PDJS.Canvas = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Actions;
        (function (Actions) {
            let ActionParameterType;
            (function (ActionParameterType) {
                ActionParameterType[ActionParameterType["boolean"] = 1] = "boolean";
                ActionParameterType[ActionParameterType["date"] = 2] = "date";
                ActionParameterType[ActionParameterType["decimal"] = 3] = "decimal";
                ActionParameterType[ActionParameterType["integer"] = 4] = "integer";
                ActionParameterType[ActionParameterType["string"] = 5] = "string";
                ActionParameterType[ActionParameterType["report"] = 6] = "report";
                ActionParameterType[ActionParameterType["ruleScript"] = 7] = "ruleScript";
            })(ActionParameterType = Actions.ActionParameterType || (Actions.ActionParameterType = {}));
        })(Actions = Core.Actions || (Core.Actions = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Data;
        (function (Data) {
            var Hierarchical;
            (function (Hierarchical) {
                class ModelBase extends Core.Model {
                    constructor(options = {}) {
                        super(options);
                        this.onInitialize();
                        this.m_nodes = this.createNodeCollection({
                            bindings: this.bindings,
                            model: this,
                            nodes: JSON.parse(JSON.stringify((options.nodes || []))),
                            parent: null
                        });
                    }
                    get bindings() {
                        return _.extend({
                            id: "id",
                            hasNodes: "hasNodes",
                            nodes: "nodes"
                        }, this.state.get("bindings", {}));
                    }
                    set bindings(value) {
                        this.state.set("bindings", value);
                    }
                    get nodes() {
                        return this.m_nodes;
                    }
                    set nodes(value) {
                        this.m_nodes = value;
                    }
                    getNode(id, source = null) {
                        let result = null;
                        let nodes = null;
                        nodes = source == null ?
                            this.nodes : source.nodes;
                        if (source != null && source.id == id) {
                            result = source;
                        }
                        if (!result) {
                            nodes.each(child => {
                                if (!result) {
                                    result = this.getNode(id, child);
                                }
                            });
                        }
                        return result;
                    }
                    getPath(folder = null) {
                        let result = [];
                        let target = folder;
                        while (target) {
                            result.push(target.id);
                            target = target.parent;
                        }
                        result.reverse();
                        return result;
                    }
                    toJSON() {
                        return {
                            nodes: this.nodes.toJSON()
                        };
                    }
                    requestNodes(e) {
                        e = _.extend({
                            success: e.success || (() => { }),
                            error: e.error || (() => { })
                        }, e);
                        this.onNodesRequest(e);
                    }
                    populate(e) {
                        let nodes = e.nodeId != null ?
                            this.getNode(e.nodeId).nodes : this.nodes;
                        if (nodes == null) {
                            return;
                        }
                        if (e.clear !== false) {
                            nodes.clear();
                        }
                        nodes.populate(e.nodes);
                        _.isFunction(e.success) ?
                            e.success() : null;
                        this.onPopulated(e);
                    }
                    getExpandedNodeIds(nodeId = null) {
                        let result = [];
                        if (nodeId == null) {
                            result = this.getExpandedNodes();
                        }
                        let node = this.getNode(nodeId);
                        if (node) {
                            result = this.getExpandedNodes(node.nodes);
                            ;
                        }
                        return result.map(node => node.id);
                    }
                    getBindingName(name) {
                        return this.bindings[name];
                    }
                    setBindings(bindings) {
                        this.bindings = bindings;
                    }
                    onInitialize() {
                    }
                    onNodesRequest(e) {
                        _.isFunction(e.success) ? e.success([]) : null;
                    }
                    onPopulated(e) {
                    }
                    createNodeCollection(e) {
                        return new Hierarchical.ModelNodeCollectionBase(e);
                    }
                    getExpandedNodes(nodes = null, list = null) {
                        nodes = nodes || this.nodes;
                        list = list || [];
                        nodes.each(node => {
                            node.expanded ? list.push(node) : null;
                            this.getExpandedNodes(node.nodes, list);
                        });
                        return list;
                    }
                }
                Hierarchical.ModelBase = ModelBase;
                class Model extends ModelBase {
                    get nodes() {
                        return super.nodes;
                    }
                    getNode(id, source = null) {
                        return super.getNode(id, source);
                    }
                    getPath(node = null) {
                        return super.getPath(node);
                    }
                    getAllNodes() {
                        let result = [];
                        this.forEachNode(node => {
                            result.push(node);
                        });
                        return result;
                    }
                    forEachNode(callback, source = null) {
                        let nodes = source ? source.nodes : this.nodes;
                        nodes.each((item) => {
                            callback(item);
                            this.forEachNode(callback, item);
                        });
                    }
                }
                Hierarchical.Model = Model;
            })(Hierarchical = Data.Hierarchical || (Data.Hierarchical = {}));
        })(Data = Core.Data || (Core.Data = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Data;
        (function (Data) {
            var Hierarchical;
            (function (Hierarchical) {
                class ModelNodeBase extends Core.Model {
                    constructor(options) {
                        super(options);
                        this.ensureModel(options);
                        this.ensureNodes();
                    }
                    get id() {
                        return this.state.get(this.getBindingName("id"));
                    }
                    get bindings() {
                        return this.state.get("bindings", {});
                    }
                    set bindings(value) {
                        this.state.set("bindings", value);
                    }
                    get expanded() {
                        return this.state.get("expanded", false);
                    }
                    set expanded(value) {
                        this.state.set("expanded", value);
                    }
                    get model() {
                        return this.m_model;
                    }
                    set model(value) {
                        this.m_model = value;
                    }
                    get nodes() {
                        return this.m_nodes;
                    }
                    set nodes(value) {
                        this.m_nodes = value;
                    }
                    get parent() {
                        this.ensureParent();
                        return this.m_parent;
                    }
                    set parent(value) {
                        this.m_parent = value;
                    }
                    get parentId() {
                        return this.state.get("parentId");
                    }
                    set parentId(value) {
                        this.state.set("parentId", value);
                        this.m_parent = null;
                    }
                    get role() {
                        return this.state.get(this.getBindingName("role"));
                    }
                    set role(value) {
                        this.state.set(this.getBindingName("role"), value);
                    }
                    toJSON() {
                        return _.extend(this.state.toJSON(), {
                            id: this.id,
                            nodes: this.nodes.toJSON()
                        });
                    }
                    toKendoJSON() {
                        return _.extend({
                            hasChildren: this.nodes.count > 0
                        }, this.toJSON());
                    }
                    toMarkup() {
                        return null;
                    }
                    remove() {
                        this.parent.nodes.remove(this);
                    }
                    isParentSet() {
                        return this.m_parent != null;
                    }
                    ensureParent() {
                        if (!this.isParentSet() && !!this.parentId) {
                            this.parent = this.model.getNode(this.parentId);
                        }
                    }
                    ensureNodes() {
                        let name = this.getBindingName("nodes");
                        let items = this.state.get(name, []);
                        this.m_nodes =
                            this.createNodeCollection(items);
                        this.state.unset(name);
                    }
                    ensureModel(options) {
                        this.model = options.model;
                        this.state.unset("model");
                    }
                    createNodeCollection(nodes) {
                        return new Hierarchical.ModelNodeCollectionBase({
                            bindings: this.bindings,
                            model: this.model,
                            parent: this,
                            nodes: nodes
                        });
                    }
                    getBindingName(name) {
                        return this.bindings[name];
                    }
                }
                Hierarchical.ModelNodeBase = ModelNodeBase;
                class ModelNode extends ModelNodeBase {
                    get model() {
                        return super.model;
                    }
                    set model(value) {
                        super.model = value;
                    }
                    get nodes() {
                        return super.nodes;
                    }
                    set nodes(value) {
                        super.nodes = value;
                    }
                    get parent() {
                        return super.parent;
                    }
                    set parent(value) {
                        super.parent = value;
                    }
                }
                Hierarchical.ModelNode = ModelNode;
            })(Hierarchical = Data.Hierarchical || (Data.Hierarchical = {}));
        })(Data = Core.Data || (Core.Data = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Data;
        (function (Data) {
            var Hierarchical;
            (function (Hierarchical) {
                class ModelNodeCollectionBase extends Jade.Collection {
                    constructor(options) {
                        super();
                        this.model = options.model;
                        this.parent = options.parent;
                        this.bindings = options.bindings;
                        this.populate((options.nodes || []));
                    }
                    get bindings() {
                        return this.m_bindings || {};
                    }
                    set bindings(value) {
                        this.m_bindings = value;
                    }
                    get model() {
                        return this.m_model;
                    }
                    set model(value) {
                        this.m_model = value;
                    }
                    get parent() {
                        return this.m_parent;
                    }
                    set parent(value) {
                        this.m_parent = value;
                    }
                    toJSON() {
                        return this.transform((item) => {
                            return item.toJSON();
                        });
                    }
                    populate(nodes) {
                        nodes.forEach(item => {
                            var _a;
                            let data = _.extend(item, {
                                bindings: this.bindings,
                                parent: (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id,
                                model: this.model
                            });
                            let node = this.createNode(data);
                            if (node) {
                                this.add(node);
                            }
                        });
                    }
                    createNode(item) {
                        return new Hierarchical.ModelNodeBase(item);
                    }
                }
                Hierarchical.ModelNodeCollectionBase = ModelNodeCollectionBase;
                class ModelNodeCollection extends ModelNodeCollectionBase {
                    constructor(options) {
                        super(options);
                    }
                    get parent() {
                        return super.parent;
                    }
                    set parent(value) {
                        super.parent = value;
                    }
                    get model() {
                        return super.model;
                    }
                    set model(value) {
                        super.model = value;
                    }
                    add(item) {
                        var _a;
                        item.parentId = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id;
                        item.model = this.model;
                        return super.add(item);
                    }
                    remove(item) {
                        item.parentId = null;
                        super.remove(item);
                        return item;
                    }
                    createNode(item) {
                        return null;
                    }
                }
                Hierarchical.ModelNodeCollection = ModelNodeCollection;
            })(Hierarchical = Data.Hierarchical || (Data.Hierarchical = {}));
        })(Data = Core.Data || (Core.Data = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var EntityTypes;
        (function (EntityTypes) {
            var ExplorerModel;
            (function (ExplorerModel) {
                let CssClass;
                (function (CssClass) {
                    CssClass["Node"] = "-pdjs-entity-types-explorer-model-folder";
                })(CssClass = ExplorerModel.CssClass || (ExplorerModel.CssClass = {}));
            })(ExplorerModel = EntityTypes.ExplorerModel || (EntityTypes.ExplorerModel = {}));
        })(EntityTypes = Core.EntityTypes || (Core.EntityTypes = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var EntityTypes;
        (function (EntityTypes) {
            var ExplorerModel;
            (function (ExplorerModel_1) {
                class ExplorerModelBase extends Core.Model {
                    constructor(options = {}) {
                        super(options);
                        this.m_nodes = this.createNodeCollection(options.nodes || []);
                    }
                    get nodes() {
                        return this.m_nodes;
                    }
                    set nodes(value) {
                        this.m_nodes = value;
                    }
                    getNode(id, source = null) {
                        let result = null;
                        let nodes = null;
                        nodes = source == null ?
                            this.nodes : source.nodes;
                        if (source != null && source.id == id) {
                            result = source;
                        }
                        if (!result) {
                            nodes.each(child => {
                                if (!result) {
                                    result = this.getNode(id, child);
                                }
                            });
                        }
                        return result;
                    }
                    getPath(folder = null) {
                        let result = [];
                        let target = folder;
                        while (target) {
                            result.push(target.id);
                            target = target.parent;
                        }
                        result.reverse();
                        return result;
                    }
                    toJSON() {
                        return {
                            nodes: this.nodes.toJSON()
                        };
                    }
                    createNodeCollection(nodes) {
                        return new ExplorerModel_1.NodeCollectionBase({
                            explorerModel: this,
                            parent: null,
                            nodes: nodes
                        });
                    }
                }
                ExplorerModel_1.ExplorerModelBase = ExplorerModelBase;
                class ExplorerModel extends ExplorerModelBase {
                    get nodes() {
                        return super.nodes;
                    }
                    getNode(id, source = null) {
                        return super.getNode(id, source);
                    }
                    getPath(node = null) {
                        return super.getPath(node);
                    }
                    getAllNodes() {
                        let result = [];
                        this.forEachNode(node => {
                            result.push(node);
                        });
                        return result;
                    }
                    forEachNode(callback, source = null) {
                        let nodes = source ? source.nodes : this.nodes;
                        nodes.each((item) => {
                            callback(item);
                            this.forEachNode(callback, item);
                        });
                    }
                }
                ExplorerModel_1.ExplorerModel = ExplorerModel;
            })(ExplorerModel = EntityTypes.ExplorerModel || (EntityTypes.ExplorerModel = {}));
        })(EntityTypes = Core.EntityTypes || (Core.EntityTypes = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var EntityTypes;
        (function (EntityTypes) {
            var ExplorerModel;
            (function (ExplorerModel) {
                class NodeBase extends Core.Model {
                    constructor(options) {
                        super(options);
                        this.ensureExplorerModel();
                        this.ensureNodes();
                    }
                    get explorerModel() {
                        return this.m_explorerModel;
                    }
                    set explorerModel(value) {
                        this.m_explorerModel = value;
                    }
                    get cssClass() {
                        return this.state.get("cssClass");
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    set icon(value) {
                        this.state.set("icon", value);
                    }
                    get id() {
                        return this.state.get("id");
                    }
                    set id(value) {
                        this.state.set("id", value);
                    }
                    get name() {
                        return this.state.get("name");
                    }
                    set name(value) {
                        this.state.set("name", value);
                    }
                    get parent() {
                        this.ensureParent();
                        return this.m_parent;
                    }
                    set parent(value) {
                        this.m_parent = value;
                    }
                    get parentId() {
                        return this.state.get("parentId");
                    }
                    set parentId(value) {
                        this.state.set("parentId", value);
                        this.m_parent = null;
                    }
                    get nodes() {
                        return this.m_nodes;
                    }
                    set nodes(value) {
                        this.m_nodes = value;
                    }
                    get type() {
                        return this.state.get("type");
                    }
                    set type(value) {
                        this.state.set("type", value);
                    }
                    toJSON() {
                        return _.extend(this.state.toJSON(), {
                            nodes: this.nodes.toJSON()
                        });
                    }
                    toMarkup() {
                        return `<div class="${this.cssClass || ExplorerModel.CssClass.Node}">
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                    }
                    remove() {
                        this.parent.nodes.remove(this);
                    }
                    isParentSet() {
                        return this.m_parent != null;
                    }
                    ensureParent() {
                        if (!this.isParentSet() && !!this.parentId) {
                            this.parent = this.explorerModel.getNode(this.parentId);
                        }
                    }
                    ensureNodes() {
                        let items = this.state.get("nodes", []);
                        this.m_nodes =
                            this.createNodeCollection(items);
                        this.state.unset("nodes");
                    }
                    ensureExplorerModel() {
                        this.explorerModel = this.state.get("explorerModel");
                        this.state.unset("explorerModel");
                    }
                    createNodeCollection(nodes) {
                        return new ExplorerModel.NodeCollectionBase({
                            explorerModel: this.explorerModel,
                            parent: this,
                            nodes: nodes
                        });
                    }
                }
                ExplorerModel.NodeBase = NodeBase;
                class Node extends NodeBase {
                    get explorerModel() {
                        return super.explorerModel;
                    }
                    set explorerModel(value) {
                        super.explorerModel = value;
                    }
                    get nodes() {
                        return super.nodes;
                    }
                    set nodes(value) {
                        super.nodes = value;
                    }
                    get parent() {
                        return super.parent;
                    }
                    set parent(value) {
                        super.parent = value;
                    }
                }
                ExplorerModel.Node = Node;
            })(ExplorerModel = EntityTypes.ExplorerModel || (EntityTypes.ExplorerModel = {}));
        })(EntityTypes = Core.EntityTypes || (Core.EntityTypes = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var EntityTypes;
        (function (EntityTypes) {
            var ExplorerModel;
            (function (ExplorerModel) {
                class NodeCollectionBase extends Jade.Collection {
                    constructor(options) {
                        super();
                        this.explorerModel = options.explorerModel;
                        this.parent = options.parent;
                        this.populate((options.nodes || []));
                    }
                    get parent() {
                        return this.m_parent;
                    }
                    set parent(value) {
                        this.m_parent = value;
                    }
                    get explorerModel() {
                        return this.m_explorerModel;
                    }
                    set explorerModel(value) {
                        this.m_explorerModel = value;
                    }
                    toJSON() {
                        return this.transform((item) => {
                            return item.toJSON();
                        });
                    }
                    populate(folders) {
                        folders.forEach(item => {
                            let data = _.extend(item, {
                                explorerModel: this.explorerModel
                            });
                            let node = this.createNode(data);
                            if (node) {
                                this.add(node);
                            }
                        });
                    }
                    createNode(item) {
                        return new ExplorerModel.NodeBase(item);
                    }
                }
                ExplorerModel.NodeCollectionBase = NodeCollectionBase;
                class NodeCollection extends NodeCollectionBase {
                    constructor(options) {
                        super(options);
                    }
                    get parent() {
                        return super.parent;
                    }
                    set parent(value) {
                        super.parent = value;
                    }
                    get explorerModel() {
                        return super.explorerModel;
                    }
                    set explorerModel(value) {
                        super.explorerModel = value;
                    }
                    add(item) {
                        var _a;
                        item.parentId = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id;
                        item.explorerModel = this.explorerModel;
                        return super.add(item);
                    }
                    remove(item) {
                        item.parentId = null;
                        super.remove(item);
                        return item;
                    }
                    createNode(item) {
                        return null;
                    }
                }
                ExplorerModel.NodeCollection = NodeCollection;
            })(ExplorerModel = EntityTypes.ExplorerModel || (EntityTypes.ExplorerModel = {}));
        })(EntityTypes = Core.EntityTypes || (Core.EntityTypes = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Explorer;
        (function (Explorer) {
            let CssClass;
            (function (CssClass) {
                CssClass["Model"] = "-pdjs-hub-explorer-model";
                CssClass["ModelNode"] = "-pdjs-hub-explorer-model-node";
                CssClass["ModelNodeNotFileFolder"] = "-not-file-folder";
            })(CssClass = Explorer.CssClass || (Explorer.CssClass = {}));
        })(Explorer = Core.Explorer || (Core.Explorer = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Explorer;
        (function (Explorer) {
            class Model extends Core.Data.Hierarchical.Model {
                constructor(options) {
                    super(options);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                get includeTabs() {
                    return this.state.get("includeTabs");
                }
                onInitialize() {
                    this.setBindings({
                        id: "folderId"
                    });
                }
                onNodesRequest(e) {
                    let service = new PDJS.Services.Explorer.ExplorerService();
                    if (e.nodeId == null) {
                        service.getExplorer({
                            entityId: this.entityId,
                            folderId: this.folderId,
                            expanded: e.expanded,
                            includeTabs: this.includeTabs,
                            success: (e2) => {
                                this.populate({
                                    nodes: e2.data.nodes,
                                    success: e.success
                                });
                                PDJS.Hub.Explorer.ExplorerContext.current.load(e2.data.nodes);
                            }
                        });
                    }
                    else {
                        let model = this.getNode(e.nodeId);
                        service.getExplorerNodes({
                            entityId: model.entityId,
                            folderId: e.nodeId,
                            includeTabs: this.includeTabs,
                            success: (e2) => {
                                this.populate({
                                    nodeId: e.nodeId,
                                    nodes: e2.data,
                                    success: e.success
                                });
                            }
                        });
                    }
                }
                createNodeCollection(e) {
                    return new Explorer.ModelNodeCollection(e);
                }
            }
            Explorer.Model = Model;
        })(Explorer = Core.Explorer || (Core.Explorer = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Explorer;
        (function (Explorer) {
            class ModelNode extends Core.Data.Hierarchical.ModelNode {
                get model() {
                    return super.model;
                }
                set model(value) {
                    super.model = value;
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                set entityId(value) {
                    this.state.set("entityId", value);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                set entityTypeId(value) {
                    this.state.set("entityTypeId", value);
                }
                get fileCount() {
                    return this.state.get("fileCount");
                }
                set fileCount(value) {
                    this.state.set("fileCount", value);
                }
                get folderIcon() {
                    return this.state.get("folderIcon");
                }
                set folderIcon(value) {
                    this.state.set("folderIcon", value);
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                set folderId(value) {
                    this.state.set("folderId", value);
                }
                get folderName() {
                    return this.state.get("folderName");
                }
                set folderName(value) {
                    this.state.set("folderName", value);
                }
                get isFileFolder() {
                    return this.state.get("isFileFolder");
                }
                set isFileFolder(value) {
                    this.state.set("isFileFolder", value);
                }
                get isHidden() {
                    return this.state.get("isHidden");
                }
                set isHidden(value) {
                    this.state.set("isHidden", value);
                }
                get isMoveable() {
                    return this.state.get("isMoveable");
                }
                set isMoveable(value) {
                    this.state.set("isMoveable", value);
                }
                get isSelectable() {
                    return this.state.get("isSelectable");
                }
                set isSelectable(value) {
                    this.state.set("isSelectable", value);
                }
                get isTab() {
                    return this.state.get("isTab");
                }
                set isTab(value) {
                    this.state.set("isTab", value);
                }
                get role() {
                    return this.state.get("role");
                }
                set role(value) {
                    this.state.set("role", value);
                }
                toMarkup() {
                    let count = this.fileCount > 0 ? `&nbsp;<b>(${this.fileCount})</b>` : "";
                    let cssClass = !this.isFileFolder && this.model.includeTabs ?
                        Explorer.CssClass.ModelNodeNotFileFolder : "";
                    return `<div class="${Explorer.CssClass.ModelNode} ${cssClass}">
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.folderIcon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.folderName}${count}</div>
                    </div>`;
                }
                createNodeCollection(nodes) {
                    return new Explorer.ModelNodeCollection({
                        bindings: this.bindings,
                        model: this.model,
                        parent: this,
                        nodes: nodes
                    });
                }
            }
            Explorer.ModelNode = ModelNode;
        })(Explorer = Core.Explorer || (Core.Explorer = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Explorer;
        (function (Explorer) {
            class ModelNodeCollection extends Core.Data.Hierarchical.ModelNodeCollection {
                createNode(item) {
                    return new Explorer.ModelNode(item);
                }
            }
            Explorer.ModelNodeCollection = ModelNodeCollection;
        })(Explorer = Core.Explorer || (Core.Explorer = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Files;
        (function (Files) {
            class File extends Core.Model {
                get id() {
                    return this.state.get("id");
                }
                set id(value) {
                    this.state.set("id", value);
                }
                get documentType() {
                    return this.state.get("documentType");
                }
                set documentType(value) {
                    this.state.set("documentType", value);
                }
                get extension() {
                    return this.state.get("extension");
                }
                set extension(value) {
                    this.state.set("extension", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get size() {
                    return this.state.get("size");
                }
                set size(value) {
                    this.state.set("size", value);
                }
                get sizeText() {
                    return Jade.Convert.BytesToUnits(this.size, Jade.DiskUnits.MB);
                }
            }
            Files.File = File;
        })(Files = Core.Files || (Core.Files = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Files;
        (function (Files) {
            let FileAlertType;
            (function (FileAlertType) {
                FileAlertType[FileAlertType["Validation"] = 0] = "Validation";
                FileAlertType[FileAlertType["Error"] = 1] = "Error";
            })(FileAlertType = Files.FileAlertType || (Files.FileAlertType = {}));
            class FileAlert extends Core.Model {
                constructor(options) {
                    super(options);
                }
                get message() {
                    return this.state.get("message", "");
                }
                set message(value) {
                    this.state.set("message", value);
                }
                get type() {
                    return this.state.get("type", FileAlertType.Error);
                }
            }
            Files.FileAlert = FileAlert;
            class FileAlertCollection extends Jade.ObservableCollection {
                getByAlertType(type) {
                    let result = new Jade.Collection();
                    this.each((item) => {
                        if (item.type === type) {
                            result.add(item);
                        }
                    });
                    return result;
                }
                get validationErrors() {
                    return this.getByAlertType(Core.Files.FileAlertType.Validation);
                }
                get errors() {
                    return this.getByAlertType(Core.Files.FileAlertType.Error);
                }
            }
            Files.FileAlertCollection = FileAlertCollection;
        })(Files = Core.Files || (Core.Files = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Files;
        (function (Files) {
            let FileStatus;
            (function (FileStatus) {
                FileStatus[FileStatus["PENDING"] = 1] = "PENDING";
                FileStatus[FileStatus["VALIDATED"] = 2] = "VALIDATED";
                FileStatus[FileStatus["READY"] = 3] = "READY";
                FileStatus[FileStatus["COMMITTED"] = 4] = "COMMITTED";
                FileStatus[FileStatus["ERROR"] = 5] = "ERROR";
            })(FileStatus = Files.FileStatus || (Files.FileStatus = {}));
            class StoredFile extends Files.File {
                constructor(state) {
                    super(state);
                    this.m_alerts = new Files.FileAlertCollection([], {
                        onAfterChange: (e) => {
                            this.state.trigger("change");
                        }
                    });
                    this.setStatusProperties();
                }
                get canvasDocument() {
                    return this.state.get("canvasDocument");
                }
                set canvasDocument(value) {
                    this.state.set("canvasDocument", value);
                }
                get selected() {
                    return this.state.get("selected", false);
                }
                set selected(value) {
                    this.state.set("selected", value);
                }
                get status() {
                    return this.state.get("status");
                }
                set status(value) {
                    this.state.set("status", value);
                }
                get alerts() {
                    return this.m_alerts;
                }
                get statusIcon() {
                    return this.state.get("statusIcon");
                }
                set statusIcon(value) {
                    this.state.set("statusIcon", value);
                }
                get statusColor() {
                    return this.state.get("statusColor");
                }
                set statusColor(value) {
                    this.state.set("statusColor", value);
                }
                get statusIconPath() {
                    return Jade.IconSet.get("pdjs")
                        .resolve(this.statusIcon, Jade.IconSetSizeSpecificDirectory.x24);
                }
                get statusText() {
                    return this.state.get("statusText");
                }
                set statusText(value) {
                    this.state.set("statusText", value);
                }
                get lastCommitResponse() {
                    return this.state.get("lastCommitResponse");
                }
                set lastCommitResponse(value) {
                    this.state.set("lastCommitResponse", value);
                }
                setCanvasDocument() {
                    let oldCanvasDocument = null;
                    let service = new PDJS.Services.Canvas.Files.FileService();
                    if (this.canvasDocument != null) {
                        oldCanvasDocument = this.canvasDocument.clone();
                    }
                    service.getCanvasDocument({
                        documentId: this.documentType.canvasId,
                        fileId: this.id,
                        success: (e) => {
                            this.status = Core.Files.FileStatus.PENDING;
                            this.canvasDocument = new PDJS.Canvas.Core.Documents.DocumentModel(e.data.document);
                            if (oldCanvasDocument != null) {
                                PDJS.Canvas.Core.Forms.FormFields.map(oldCanvasDocument, this.canvasDocument);
                            }
                            this.alerts.clear();
                            this.setEntityNameFieldValue(e.data.validateResponse);
                            this.lastCommitResponse = null;
                            this.lastCommitResponse = e.data.validateResponse;
                            if (this.lastCommitResponse.hasValidationErrors) {
                                PDJS.Canvas.Core.Forms.FormFields.iterateRequiredFields(this.canvasDocument, (field) => {
                                    if (field.hasValue()) {
                                        delete this.lastCommitResponse.validationErrors[field.id];
                                    }
                                });
                                this.processFormSubmitResponse(this.lastCommitResponse);
                            }
                            this.status = this.alerts.validationErrors.count > 0 ? Core.Files.FileStatus.ERROR : Core.Files.FileStatus.VALIDATED;
                        }
                    });
                }
                commit(entityId, folder, success) {
                    if (this.status == FileStatus.COMMITTED) {
                        return;
                    }
                    this.status = FileStatus.PENDING;
                    this.alerts.clear();
                    let service = new PDJS.Services.Canvas.Files.FileService();
                    service.edit({
                        document: this.canvasDocument.toJSON(),
                        fileId: this.id,
                        documentTypeId: this.documentType.id,
                        success: (e) => {
                            this.lastCommitResponse = e.data;
                            if (this.lastCommitResponse.hasValidationErrors || this.lastCommitResponse.hasScriptErrors) {
                                this.processFormSubmitResponse(this.lastCommitResponse);
                                this.status = FileStatus.ERROR;
                            }
                            else {
                                this.id = e.data.fileId;
                                this.status = FileStatus.COMMITTED;
                                if (_.isFunction(success)) {
                                    success();
                                }
                            }
                        },
                        error: (e) => {
                            this.status = FileStatus.ERROR;
                            this.alerts.add(new Files.FileAlert({
                                type: Files.FileAlertType.Error,
                                message: "Unknown Error"
                            }));
                            e.errorHandled = true;
                            if (_.isFunction(success)) {
                                success();
                            }
                        }
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    if (this.state.hasChanged("status")) {
                        this.setStatusProperties();
                    }
                    if (this.state.hasChanged("canvasDocument")) {
                        this.onCanvasChanged();
                    }
                }
                setStatusProperties() {
                    let isInspecting = this.status === Core.Files.FileStatus.PENDING;
                    let isValidated = this.status === Core.Files.FileStatus.VALIDATED;
                    let hasErrors = this.alerts.count > 0;
                    let isReady = this.alerts.count > 0
                        && this.status === Core.Files.FileStatus.READY;
                    let alertCount = this.alerts.count;
                    switch (true) {
                        case isInspecting:
                            this.statusIcon = "magnifying_glass.png";
                            this.statusColor = "blue";
                            this.statusText = "Inspecting...";
                            break;
                        case hasErrors:
                            this.statusIcon = "sign_warning.png";
                            this.statusColor = "red";
                            this.statusText = `${alertCount} ${alertCount === 1 ? "Error" : "Errors"}`;
                            break;
                        case isReady || isValidated:
                            this.statusIcon = "ok.png";
                            this.statusColor = "darkgreen";
                            this.statusText = "Ready";
                            break;
                    }
                }
                onCanvasChanged() {
                    let name = PDJS.Canvas.Core.Forms.FormFields.getValue({
                        document: this.canvasDocument,
                        type: PDJS.Canvas.Core.Forms.EntityNameField
                    });
                    if (!Jade.String.isNullOrWhiteSpace(name)) {
                        this.name = name;
                    }
                }
                processFormSubmitResponse(response) {
                    if (response.hasValidationErrors) {
                        _.each(response.validationErrors, (error) => {
                            this.alerts.add(new Files.FileAlert({
                                type: Files.FileAlertType.Validation,
                                message: error
                            }));
                        });
                    }
                    if (response.hasScriptErrors) {
                        _.each(response.scriptErrors, (error) => {
                            this.alerts.add(new Files.FileAlert({
                                type: Files.FileAlertType.Error,
                                message: error
                            }));
                        });
                    }
                }
                setEntityNameFieldValue(response) {
                    let isEmptyObject = (obj) => {
                        let result = true;
                        for (let key in obj) {
                            if (obj.hasOwnProperty(key))
                                result = false;
                            break;
                        }
                        return result;
                    };
                    PDJS.Canvas.Core.Forms.FormFields.getFields({
                        type: PDJS.Canvas.Core.Forms.EntityNameField,
                        document: this.canvasDocument
                    }).each((field) => {
                        field.value = this.name;
                        delete response.validationErrors[field.id];
                        if (isEmptyObject(response.validationErrors)) {
                            response.hasValidationErrors = false;
                        }
                    });
                }
            }
            Files.StoredFile = StoredFile;
        })(Files = Core.Files || (Core.Files = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Files;
        (function (Files) {
            class Upload extends Core.Model {
                get id() {
                    return this.state.get("id");
                }
                set id(value) {
                    this.state.set("id", value);
                }
                get percent() {
                    return this.state.get("percent");
                }
                set percent(value) {
                    this.state.set("percent", value);
                }
                get status() {
                    return this.state.get("status");
                }
                set status(value) {
                    this.state.set("status", value);
                }
            }
            Files.Upload = Upload;
        })(Files = Core.Files || (Core.Files = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Files;
        (function (Files) {
            class UploadFile extends Files.StoredFile {
                constructor(state) {
                    super(state);
                    this.m_upload = new Files.Upload(state.upload);
                    this.upload.onStateChangeCallback = () => {
                        this.onStateChanged();
                        this.onStateChangeCallback();
                        this.setStatusProperties();
                    };
                    this.setStatusProperties();
                }
                get upload() {
                    return this.m_upload;
                }
                commit(entityId, folderId, success) {
                    if (this.status == Files.FileStatus.COMMITTED) {
                        if (_.isFunction(success)) {
                            success();
                        }
                        return;
                    }
                    this.alerts.clear();
                    let service = new PDJS.Services.Canvas.Files.FileService();
                    service.create({
                        document: this.canvasDocument.toJSON(),
                        parentId: entityId,
                        folderId: folderId,
                        documentTypeId: this.documentType.id,
                        documentName: this.name,
                        uploadName: `${this.upload.id}${this.extension}`,
                        success: (e) => {
                            if (e.data.hasScriptErrors) {
                                this.status = Files.FileStatus.ERROR;
                                _.each(e.data.scriptErrors, (error) => {
                                    this.alerts.add(new Files.FileAlert({
                                        type: Files.FileAlertType.Error,
                                        message: error
                                    }));
                                });
                            }
                            else {
                                this.id = e.data.fileId;
                                this.status = Files.FileStatus.COMMITTED;
                            }
                            if (_.isFunction(success)) {
                                success();
                            }
                        },
                        error: (e) => {
                            var _a;
                            this.alerts.add(new Files.FileAlert({
                                type: Files.FileAlertType.Error,
                                message: ((_a = _.first(e.xhr.responseJSON)) === null || _a === void 0 ? void 0 : _a.message) || "Unknown Error"
                            }));
                            e.errorHandled = true;
                            if (_.isFunction(success)) {
                                success();
                            }
                        }
                    });
                }
                setStatusProperties() {
                    if (this.upload == null) {
                        return;
                    }
                    let isQueued = this.upload.percent == 0
                        && this.upload.status === plupload.FileStatus.QUEUED;
                    let isUploading = this.upload.percent < 100
                        && this.upload.status === plupload.FileStatus.UPLOADING;
                    let uploadFailed = this.upload.percent < 100
                        && this.upload.status === plupload.FileStatus.FAILED;
                    let isInspecting = this.upload.status === plupload.FileStatus.DONE
                        && this.status === Core.Files.FileStatus.PENDING;
                    let isValidated = this.upload.status === plupload.FileStatus.DONE
                        && this.status === Core.Files.FileStatus.VALIDATED;
                    let hasErrors = this.alerts.count > 0
                        && this.upload.status === plupload.FileStatus.DONE;
                    let isReady = this.alerts.count > 0
                        && this.upload.status === plupload.FileStatus.DONE
                        && this.status === Core.Files.FileStatus.READY;
                    let isCommitted = this.alerts.count > 0
                        && this.upload.status === plupload.FileStatus.DONE
                        && this.status === Core.Files.FileStatus.COMMITTED;
                    let alertCount = this.alerts.count;
                    switch (true) {
                        case isQueued:
                            this.statusIcon = "cloud_upload.png";
                            this.statusColor = "var(--visiv-theme-base-1-text-color)";
                            this.statusText = "Pending Upload";
                            break;
                        case isUploading:
                            this.statusIcon = "hourglass.png";
                            this.statusColor = "var(--visiv-system-blue)";
                            this.statusText = "Uploading...";
                            break;
                        case uploadFailed:
                            this.statusIcon = "error.png";
                            this.statusColor = "var(--visiv-system-red)";
                            this.statusText = "Upload Failed";
                            break;
                        case isInspecting:
                            this.statusIcon = "magnifying_glass.png";
                            this.statusColor = "var(--visiv-system-blue)";
                            this.statusText = "Inspecting...";
                            break;
                        case hasErrors:
                            this.statusIcon = "sign_warning.png";
                            this.statusColor = "var(--visiv-system-red)";
                            this.statusText = `${alertCount} ${alertCount === 1 ? "Warning" : "Warnings"}`;
                            break;
                        case isReady || isValidated:
                            this.statusIcon = "ok.png";
                            this.statusColor = "var(--visiv-system-green)";
                            this.statusText = "Ready";
                            break;
                    }
                }
            }
            Files.UploadFile = UploadFile;
        })(Files = Core.Files || (Core.Files = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            let CssClass;
            (function (CssClass) {
                CssClass["ProcessNode"] = "-pdjs-manage-process-node";
            })(CssClass = Process.CssClass || (Process.CssClass = {}));
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            let ProcessNodeType;
            (function (ProcessNodeType) {
                ProcessNodeType["process"] = "process";
                ProcessNodeType["key"] = "key";
                ProcessNodeType["stage"] = "stage";
                ProcessNodeType["decision"] = "decision";
            })(ProcessNodeType = Process.ProcessNodeType || (Process.ProcessNodeType = {}));
            class ProcessNode extends Core.Model {
                constructor(options) {
                    super(_.extend({
                        id: Jade.Guid.new()
                    }, options));
                    this.m_nodes = new Process.ProcessNodeCollection({
                        nodes: options.nodes,
                        parent: this
                    });
                }
                get id() {
                    return this.state.get("id");
                }
                get objectId() {
                    return this.state.get("objectId");
                }
                get parent() {
                    return this.m_parent;
                }
                set parent(value) {
                    this.m_parent = value;
                }
                get parentObjectId() {
                    return this.state.get("parentId");
                }
                set parentObjectId(value) {
                    this.state.set("parentId", value);
                }
                get icon() {
                    return this.state.get("icon");
                }
                set icon(value) {
                    this.state.set("icon", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get type() {
                    return this.state.get("type");
                }
                get nodes() {
                    return this.m_nodes;
                }
                setParent(parent) {
                    var _a;
                    this.parent = parent;
                    this.parentObjectId = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.objectId;
                }
                move(target, insertAt) {
                    this.remove();
                    if (insertAt != null) {
                        target.nodes.insert(this, insertAt);
                    }
                    else {
                        target.nodes.add(this);
                    }
                    this.parent = target;
                }
                remove() {
                    if (this.parent != null) {
                        this.parent.nodes.remove(this);
                    }
                }
                update(state) {
                    if (state != null) {
                        this.state.set(state);
                    }
                }
                toJSON() {
                    return _.extend(this.state.toJSON(), {
                        nodes: this.nodes.toJSON(),
                        hasChildren: this.nodes.count > 0
                    });
                }
                toMarkup() {
                    return `<div class="${Process.CssClass.ProcessNode}" data-id="${this.id}" data-type="${this.type}">
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                }
            }
            Process.ProcessNode = ProcessNode;
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            class ProcessNodeCollection extends Jade.Collection {
                constructor(options) {
                    super();
                    this.m_parent = options.parent;
                    (options.nodes || []).forEach(item => {
                        this.add(new Process.ProcessNode(item));
                    });
                }
                get parent() {
                    return this.m_parent;
                }
                toJSON() {
                    return this.transform((node) => {
                        return node.toJSON();
                    });
                }
                add(item) {
                    item.setParent(this.parent);
                    return super.add(item);
                }
                remove(item) {
                    item.setParent(null);
                    super.remove(item);
                    return item;
                }
            }
            Process.ProcessNodeCollection = ProcessNodeCollection;
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            class ProcessNodeTree extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_node = new Process.ProcessNode(options.node);
                }
                get node() {
                    return this.m_node;
                }
                getNode(id, source = null) {
                    let result = null;
                    if (source == null) {
                        source = this.node;
                    }
                    if (source.id == id) {
                        result = source;
                    }
                    if (!result) {
                        source.nodes.each(child => {
                            if (!result) {
                                result = this.getNode(id, child);
                            }
                        });
                    }
                    return result;
                }
                remove(guid) {
                    let node = this.getNode(guid);
                    if (node != null) {
                        node.remove();
                    }
                }
                toJSON() {
                    return this.node.toJSON();
                }
            }
            Process.ProcessNodeTree = ProcessNodeTree;
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            class ProcessStatus extends Core.Model {
                constructor(options) {
                    super(options);
                }
                get id() {
                    return this.state.get("id");
                }
                set id(value) {
                    this.state.set("id", value);
                }
                get customId() {
                    return this.state.get("customId");
                }
                set customId(value) {
                    this.state.set("customId", value);
                }
                get icon() {
                    return this.state.get("icon");
                }
                set icon(value) {
                    this.state.set("icon", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get inUse() {
                    return this.state.get("inUse");
                }
                set inUse(value) {
                    this.state.set("inUse", value);
                }
                update(state) {
                    this.state.set(state);
                }
                toJSON() {
                    return this.state.toJSON();
                }
            }
            Process.ProcessStatus = ProcessStatus;
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            class ProcessStatusCollection extends Jade.Collection {
                constructor(data) {
                    super();
                    (data || []).forEach(item => {
                        this.add(new Process.ProcessStatus(item));
                    });
                }
                toJSON() {
                    return this.transform(item => {
                        return item.toJSON();
                    });
                }
                getById(id) {
                    let result = null;
                    this.each(item => {
                        if (item.id === id) {
                            result = item;
                        }
                    });
                    return result;
                }
            }
            Process.ProcessStatusCollection = ProcessStatusCollection;
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            var ExplorerModel;
            (function (ExplorerModel) {
                let CssClass;
                (function (CssClass) {
                    CssClass["Model"] = "-pdjs-process-explorer-model";
                    CssClass["Node"] = "-pdjs-process-explorer-model-node";
                })(CssClass = ExplorerModel.CssClass || (ExplorerModel.CssClass = {}));
            })(ExplorerModel = Process.ExplorerModel || (Process.ExplorerModel = {}));
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            var Explorer;
            (function (Explorer) {
                let IModelMode;
                (function (IModelMode) {
                    IModelMode[IModelMode["Explore"] = 0] = "Explore";
                    IModelMode[IModelMode["StageSelect"] = 1] = "StageSelect";
                })(IModelMode = Explorer.IModelMode || (Explorer.IModelMode = {}));
                class Model extends Core.Data.Hierarchical.Model {
                    constructor(options) {
                        super(options);
                    }
                    get expandAll() {
                        return this.state.get("expandAll");
                    }
                    set expandAll(value) {
                        this.state.set("expandAll", value);
                    }
                    get processId() {
                        return this.state.get("processId");
                    }
                    get mode() {
                        return this.state.get("mode");
                    }
                    onInitialize() {
                        this.setBindings({
                            id: "id",
                        });
                        this.expandAll = this.mode == IModelMode.StageSelect;
                    }
                    onNodesRequest(e) {
                        if (e.nodeId != null) {
                            return;
                        }
                        let service = new PDJS.Services.Process.ProcessService();
                        service.getTree({
                            processId: this.processId,
                            success: (e2) => {
                                if (this.expandAll) {
                                    e2.data.expanded = true;
                                    e2.data.nodes.forEach(node => {
                                        node.expanded = true;
                                    });
                                }
                                this.populate({
                                    nodes: e2.data.nodes,
                                    success: e.success
                                });
                            }
                        });
                    }
                    createNodeCollection(e) {
                        return new Explorer.ModelNodeCollection(e);
                    }
                }
                Explorer.Model = Model;
            })(Explorer = Process.Explorer || (Process.Explorer = {}));
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            var Explorer;
            (function (Explorer) {
                class ModelNode extends Core.Data.Hierarchical.ModelNode {
                    get model() {
                        return super.model;
                    }
                    set model(value) {
                        super.model = value;
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    set icon(value) {
                        this.state.set("icon", value);
                    }
                    get name() {
                        return this.state.get("name");
                    }
                    set name(value) {
                        this.state.set("name", value);
                    }
                    get objectId() {
                        return this.state.get("objectId");
                    }
                    set objectId(value) {
                        this.state.set("objectId", value);
                    }
                    get type() {
                        return this.state.get("type");
                    }
                    set type(value) {
                        this.state.set("type", value);
                    }
                    get isSelectable() {
                        return (this.model.mode != Explorer.IModelMode.StageSelect)
                            || (this.model.mode == Explorer.IModelMode.StageSelect && this.type === "stage");
                    }
                    toMarkup() {
                        return `<div class="${Process.CssClass.ProcessNode}" data-id="${this.id}" data-type="${this.type}">
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                    }
                    createNodeCollection(nodes) {
                        let isStageSelect = this.model.mode == Explorer.IModelMode.StageSelect
                            && this.type === "stage";
                        if (this.model.expandAll) {
                            nodes.forEach(node => {
                                node.expanded = true;
                            });
                        }
                        return new Explorer.ModelNodeCollection({
                            bindings: this.bindings,
                            model: this.model,
                            parent: this,
                            nodes: isStageSelect ? [] : nodes
                        });
                    }
                }
                Explorer.ModelNode = ModelNode;
            })(Explorer = Process.Explorer || (Process.Explorer = {}));
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Process;
        (function (Process) {
            var Explorer;
            (function (Explorer) {
                class ModelNodeCollection extends Core.Data.Hierarchical.ModelNodeCollection {
                    createNode(item) {
                        return new Explorer.ModelNode(item);
                    }
                }
                Explorer.ModelNodeCollection = ModelNodeCollection;
            })(Explorer = Process.Explorer || (Process.Explorer = {}));
        })(Process = Core.Process || (Core.Process = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class History extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_items = [];
                }
                get addCallback() {
                    return this.state.get("add", () => { });
                }
                get moveCallback() {
                    return this.state.get("move", () => { });
                }
                get suspendRecording() {
                    return this.state.get("suspendRecording", false);
                }
                set suspendRecording(value) {
                    this.state.get("suspendRecording", value);
                }
                get items() {
                    return this.m_items;
                }
                set items(value) {
                    this.m_items = value;
                }
                get index() {
                    return this.state.get("index", 0);
                }
                set index(value) {
                    this.state.set("index", value);
                }
                add(item) {
                    this.trim();
                    if (!this.allowAdd(item.folderId)) {
                        return;
                    }
                    ;
                    let historyItem = new PDJS.Core.Resources.HistoryItem(item);
                    this.items.push(historyItem);
                    this.index += 1;
                    this.addCallback(new PDJS.Core.Resources.HistoryEventArgs({
                        event: "add",
                        history: this,
                        index: this.index,
                        item: historyItem,
                        items: this.items.slice(0)
                    }));
                    this.suspendRecording = false;
                }
                get(folderId) {
                    let result = null;
                    this.items.forEach(item => {
                        if (result == null && item.folderId == folderId) {
                            result = item;
                        }
                    });
                    return result;
                }
                next() {
                    if (this.canMoveNext()) {
                        this.index += 1;
                        this.suspendRecording = true;
                        this.moveCallback(new PDJS.Core.Resources.HistoryEventArgs({
                            event: "next",
                            history: this,
                            index: this.index,
                            item: this.items[this.index],
                            items: this.items.slice(0)
                        }));
                    }
                }
                prev() {
                    if (this.canMovePrev()) {
                        this.index = this.index == this.items.length ?
                            this.index - 2 :
                            this.index - 1;
                        this.suspendRecording = true;
                        this.moveCallback(new PDJS.Core.Resources.HistoryEventArgs({
                            event: "prev",
                            history: this,
                            index: this.index,
                            item: this.items[this.index],
                            items: this.items.slice(0)
                        }));
                    }
                }
                canMovePrev() {
                    return this.index > 0;
                }
                canMoveNext() {
                    return this.index < this.items.length - 1;
                }
                trim() {
                    let result = this.items.slice(0);
                    if (this.index > -1 && this.index < result.length - 1) {
                        result = result.slice(0, this.index + 1);
                    }
                    this.items = result;
                }
                peek() {
                    return this.items[this.index - 1];
                }
                canAdd(folderId) {
                    let lastItem = _.last(this.items);
                    return lastItem != null && lastItem.folderId != folderId;
                }
                allowAdd(folderId) {
                    return this.suspendRecording === false
                        && (this.index < 1 || this.canAdd(folderId));
                }
            }
            Resources.History = History;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class HistoryEventArgs {
                constructor(options) {
                    this.m_event = options.event;
                    this.m_history = options.history;
                    this.m_index = options.index;
                    this.m_item = options.item;
                    this.m_items = (options.items || []).slice(0);
                }
                get event() {
                    return this.m_event;
                }
                get history() {
                    return this.m_history;
                }
                get index() {
                    return this.m_index;
                }
                get item() {
                    return this.m_item;
                }
                get items() {
                    return this.m_items;
                }
                get canMovePrev() {
                    return this.history.canMovePrev();
                }
                get canMoveNext() {
                    return this.history.canMoveNext();
                }
            }
            Resources.HistoryEventArgs = HistoryEventArgs;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class HistoryItem {
                constructor(options) {
                    this.m_id = options.folderId;
                    this.m_path = options.folderPath;
                }
                get folderId() {
                    return this.m_id;
                }
                get folderPath() {
                    return this.m_path || [];
                }
            }
            Resources.HistoryItem = HistoryItem;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class ResourceTree extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_root = {
                        id: Jade.Guid.empty(),
                        parentId: null,
                        name: "Resources",
                        icon: "folder.png",
                        expanded: true,
                        hasNodes: true,
                        items: null,
                        type: "folder"
                    };
                    this.root.items = options.items;
                    this.m_nodes = new Resources.ResourceTreeNodeCollection({
                        nodes: [this.root],
                        parent: null
                    });
                }
                get nodes() {
                    return this.m_nodes;
                }
                get root() {
                    return this.m_root;
                }
                getNode(id, source = null) {
                    let match = null;
                    let nodes = source == null ?
                        this.nodes : source.nodes;
                    let isSourceNodeMatch = source != null && source.id == id;
                    if (isSourceNodeMatch) {
                        return source;
                    }
                    nodes.each(child => {
                        if (!match) {
                            match = this.getNode(id, child);
                        }
                    });
                    return match;
                }
                remove(guid) {
                    let node = this.getNode(guid);
                    if (node != null) {
                        node.remove();
                    }
                }
                toJSON() {
                    return this.nodes.toJSON();
                }
            }
            Resources.ResourceTree = ResourceTree;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class ResourceTreeNodeCollection extends Jade.Collection {
                constructor(options) {
                    super();
                    this.m_parent = options.parent;
                    (options.nodes || []).forEach(item => {
                        this.add(new Resources.ResourceTreeNode(item));
                    });
                }
                get parent() {
                    return this.m_parent;
                }
                toJSON() {
                    return this.transform((node) => {
                        return node.toJSON();
                    });
                }
                add(item) {
                    item.setParent(this.parent);
                    return super.add(item);
                }
                remove(item) {
                    item.setParent(null);
                    super.remove(item);
                    return item;
                }
            }
            Resources.ResourceTreeNodeCollection = ResourceTreeNodeCollection;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Resources;
        (function (Resources) {
            class ResourceTreeNode extends Core.Model {
                constructor(options) {
                    super(_.extend({
                        id: Jade.Guid.new()
                    }, options));
                    this.m_nodes = new Resources.ResourceTreeNodeCollection({
                        nodes: options.items,
                        parent: this
                    });
                }
                get id() {
                    return this.state.get("id");
                }
                get parent() {
                    return this.m_parent;
                }
                set parent(value) {
                    this.m_parent = value;
                }
                get parentId() {
                    return this.state.get("parentId");
                }
                set parentId(value) {
                    this.state.set("parentId", value);
                }
                get icon() {
                    return this.state.get("icon");
                }
                set icon(value) {
                    this.state.set("icon", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get role() {
                    return this.state.get("role");
                }
                get nodes() {
                    return this.m_nodes;
                }
                setParent(parent) {
                    var _a;
                    this.parent = parent;
                    this.parentId = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.id;
                }
                move(target, insertAt) {
                    this.remove();
                    if (insertAt != null) {
                        target.nodes.insert(this, insertAt);
                    }
                    else {
                        target.nodes.add(this);
                    }
                    this.parent = target;
                }
                remove() {
                    if (this.parent != null) {
                        this.parent.nodes.remove(this);
                    }
                }
                update(state) {
                    if (state != null) {
                        this.state.set(state);
                    }
                }
                toJSON() {
                    return _.extend(this.state.toJSON(), {
                        nodes: this.nodes.toJSON(),
                        hasChildren: this.nodes.count > 0
                    });
                }
                toMarkup() {
                    return `<div class="-pdjs-manage-resources-tree-node">
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                }
            }
            Resources.ResourceTreeNode = ResourceTreeNode;
        })(Resources = Core.Resources || (Core.Resources = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Security;
        (function (Security) {
            class AccessControlList extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_aces =
                        new Security.AceCollection(options.aces);
                    this.m_permissions =
                        new Security.PermissionCollection(options.permissions);
                }
                get aces() {
                    return this.m_aces;
                }
                get permissions() {
                    return this.m_permissions;
                }
                get commitCallback() {
                    return this.state.get("commit", () => { });
                }
                commit() {
                    this.aces.resetAcesChanged();
                    this.commitCallback();
                }
                toJSON() {
                    return {
                        aces: this.aces.toArray(),
                        permissions: this.permissions.toArray()
                    };
                }
            }
            Security.AccessControlList = AccessControlList;
        })(Security = Core.Security || (Core.Security = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Security;
        (function (Security) {
            class Ace extends Core.Model {
                constructor(options) {
                    super(options);
                }
                get id() {
                    return this.state.get("id");
                }
                set id(value) {
                    this.state.set("id", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get type() {
                    return this.state.get("type");
                }
                set type(value) {
                    this.state.set("type", value);
                }
                get allow() {
                    return this.state.get("allow", 0);
                }
                set allow(value) {
                    this.m_hasChanged = true;
                    this.state.set("allow", value);
                }
                get deny() {
                    return this.state.get("deny", 0);
                }
                set deny(value) {
                    this.m_hasChanged = true;
                    this.state.set("deny", value);
                }
                get inherited() {
                    return this.state.get("inherited");
                }
                get isInherited() {
                    return this.inherited !== undefined
                        && this.inherited !== null;
                }
                get hasChanged() {
                    return this.m_hasChanged;
                }
                toJSON() {
                    return {
                        id: this.id,
                        name: this.name,
                        type: this.type,
                        allow: this.allow,
                        deny: this.deny,
                        inherited: this.inherited
                    };
                }
                revertToInherited() {
                    this.allow = this.inherited ?
                        this.inherited.allow : this.allow;
                    this.deny = this.inherited ?
                        this.inherited.deny : this.deny;
                }
                addAllow(permission) {
                    this.allow = this.allow | permission;
                    this.deny = this.deny & ~permission;
                }
                addDeny(permission) {
                    this.deny = this.deny | permission;
                    this.allow = this.allow & ~permission;
                }
                clearAllow(permission) {
                    this.allow = this.allow & ~permission;
                }
                clearDeny(permission) {
                    this.deny = this.deny & ~permission;
                }
                isAllowed(permission) {
                    return ((this.allow & permission) === permission);
                }
                isDenied(permission) {
                    return ((this.deny & permission) === permission);
                }
                isAllowedPartial(permission) {
                    return ((this.allow & permission) !== permission)
                        && ((this.allow & permission) !== 0);
                }
                isDeniedPartial(permission) {
                    return ((this.deny & permission) !== permission)
                        && ((this.deny & permission) !== 0);
                }
                resetHasChanged() {
                    this.m_hasChanged = false;
                }
            }
            Security.Ace = Ace;
        })(Security = Core.Security || (Core.Security = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Security;
        (function (Security) {
            class AceCollection extends Jade.Collection {
                constructor(data = []) {
                    super([]);
                    data.forEach(ace => {
                        this.add(new Security.Ace(ace));
                    });
                }
                add(ace) {
                    if (this.contains(ace)) {
                        return this.update(ace);
                    }
                    else {
                        this.m_hasChanged = true;
                        return super.add(ace);
                    }
                }
                contains(ace) {
                    var result = false;
                    if (ace) {
                        this.each((item) => {
                            if (item.id === ace.id) {
                                result = true;
                                return false;
                            }
                        });
                    }
                    return result;
                }
                remove(ace) {
                    if (!ace) {
                        return;
                    }
                    this.m_hasChanged = true;
                    return super.remove(ace);
                }
                toJSON() {
                    return this.transform(item => {
                        return item.toJSON();
                    });
                }
                update(ace) {
                    let existing = this.getById(ace.id);
                    if (existing) {
                        this.m_hasChanged = true;
                        existing.state.set(ace.toJSON(), { silent: true });
                    }
                    return true;
                }
                getById(id) {
                    let result = null;
                    this.each(item => {
                        item.id == id ?
                            result = item : null;
                    });
                    return result;
                }
                haveAcesChanged() {
                    let result = this.m_hasChanged;
                    if (!result) {
                        this.each(ace => {
                            ace.hasChanged ?
                                result = true : null;
                        });
                    }
                    return result;
                }
                resetAcesChanged() {
                    this.m_hasChanged = false;
                    this.each(ace => {
                        ace.resetHasChanged();
                    });
                }
            }
            Security.AceCollection = AceCollection;
        })(Security = Core.Security || (Core.Security = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Security;
        (function (Security) {
            class Permission extends Core.Model {
                constructor(options) {
                    super(options);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get value() {
                    return this.state.get("value");
                }
                set value(value) {
                    this.state.set("value", value);
                }
                get isBasic() {
                    return this.state.get("isBasic");
                }
                set isBasic(value) {
                    this.state.set("isBasic", value);
                }
                toJSON() {
                    return {
                        name: this.name,
                        value: this.value,
                        isBasic: this.isBasic
                    };
                }
            }
            Security.Permission = Permission;
        })(Security = Core.Security || (Core.Security = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Security;
        (function (Security) {
            class PermissionCollection extends Jade.Collection {
                constructor(data = []) {
                    super([]);
                    data.forEach(permission => {
                        this.add(new Security.Permission(permission));
                    });
                }
                hasExpandPermissions() {
                    let result = false;
                    this.each(item => {
                        !item.isBasic ? result = true : null;
                    });
                    return result;
                }
                getBasicPermissions() {
                    let result = [];
                    this.each((item) => {
                        if (item.isBasic) {
                            result.push(item.toJSON());
                        }
                    });
                    return result;
                }
                getExpandedPermissions() {
                    let result = [];
                    this.each((item) => {
                        if (!item.isBasic) {
                            result.push(item.toJSON());
                        }
                    });
                    return result;
                }
                toJSON() {
                    return this.transform((permission) => {
                        return permission.toJSON();
                    });
                }
            }
            Security.PermissionCollection = PermissionCollection;
        })(Security = Core.Security || (Core.Security = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Upload;
        (function (Upload) {
            let DuplicateFileMode;
            (function (DuplicateFileMode) {
                DuplicateFileMode[DuplicateFileMode["Fail"] = 0] = "Fail";
                DuplicateFileMode[DuplicateFileMode["Skip"] = 1] = "Skip";
                DuplicateFileMode[DuplicateFileMode["Replace"] = 2] = "Replace";
            })(DuplicateFileMode = Upload.DuplicateFileMode || (Upload.DuplicateFileMode = {}));
        })(Upload = Core.Upload || (Core.Upload = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Upload;
        (function (Upload) {
            class UploadFileBase extends Core.Model {
                constructor(options) {
                    super(options);
                }
                get id() {
                    return this.state.get("id");
                }
                set id(value) {
                    this.state.set("id", value);
                }
                get loaded() {
                    return this.state.get("loaded");
                }
                set loaded(value) {
                    this.state.set("loaded", value);
                }
                get name() {
                    return this.state.get("name");
                }
                set name(value) {
                    this.state.set("name", value);
                }
                get percent() {
                    return this.state.get("percent");
                }
                set percent(value) {
                    this.state.set("percent", value);
                }
                get size() {
                    return this.state.get("size");
                }
                set size(value) {
                    this.state.set("size", value);
                }
                get status() {
                    return this.state.get("status");
                }
                set status(value) {
                    this.state.set("status", value);
                }
                get type() {
                    return this.state.get("type");
                }
                set type(value) {
                    this.state.set("type", value);
                }
                toJSON() {
                    return this.state.toJSON();
                }
            }
            Upload.UploadFileBase = UploadFileBase;
        })(Upload = Core.Upload || (Core.Upload = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Upload;
        (function (Upload) {
            class UploadFile extends Upload.UploadFileBase {
                constructor(options) {
                    super(options);
                    this.extension =
                        Jade.Path.getFileExtension(options.name);
                }
                get extension() {
                    return this.state.get("extension");
                }
                set extension(value) {
                    this.state.set("extension", value);
                }
                get sizeText() {
                    return Jade.Convert.BytesToUnits(this.size, Jade.DiskUnits.MB);
                }
                toJSON() {
                    return this.state.toJSON();
                }
            }
            Upload.UploadFile = UploadFile;
        })(Upload = Core.Upload || (Core.Upload = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Upload;
        (function (Upload) {
            class UploadFileCollection extends Jade.Collection {
            }
            Upload.UploadFileCollection = UploadFileCollection;
        })(Upload = Core.Upload || (Core.Upload = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class ColorGenerator {
                constructor() {
                    this.m_index = -1;
                    this.m_colors = ["#bdfff9",
                        "#f82200",
                        "#007be4",
                        "#d2ff07",
                        "#e668ff",
                        "#5ba400",
                        "#825ece",
                        "#daffa4",
                        "#00b07d",
                        "#c8445c",
                        "#03c3cb",
                        "#ff7963",
                        "#9b5ca0",
                        "#78c2ff",
                        "#ae7100",
                        "#e1b3ff",
                        "#358244",
                        "#ffe84f",
                        "#7f7251",
                        "#56788d"];
                }
                static get instance() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                get colors() {
                    return this.m_colors;
                }
                get index() {
                    return this.m_index;
                }
                set index(value) {
                    this.m_index = value;
                }
                get shouldReset() {
                    return this.index ===
                        this.colors.length - 1;
                }
                getColor() {
                    if (this.shouldReset) {
                        this.reset();
                    }
                    this.index += 1;
                    return `${this.colors[this.index]}`;
                }
                reset() {
                    this.index = -1;
                }
                static ensureInstance() {
                    if (!this.m_instance) {
                        this.m_instance = new ColorGenerator();
                    }
                }
            }
            Views.ColorGenerator = ColorGenerator;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class Constraint extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_parent = options.parent;
                    this.state.unset("parent");
                }
                get id() {
                    return this.state.get("id");
                }
                get role() {
                    return this.state.get("role");
                }
                get parent() {
                    return this.m_parent;
                }
                set parent(value) {
                    this.m_parent = value;
                }
                get isEnabled() {
                    return this.state.get("isEnabled");
                }
                set isEnabled(value) {
                    this.state.set("isEnabled", value);
                    this.onEnabledChanged();
                }
                toJSON() {
                }
                toMarkup() {
                    return "";
                }
                getDepth() {
                    let result = 0;
                    let target = this;
                    while (target.parent != null) {
                        target = target.parent;
                        result += 1;
                    }
                    return result;
                }
                move(target) {
                }
                remove() {
                }
                onEnabledChanged() {
                }
            }
            Views.Constraint = Constraint;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class Condition extends Views.Constraint {
                constructor(options) {
                    super(_.extend({
                        id: Jade.Guid.new(),
                        isEnabled: true,
                        role: "condition",
                        color: Views.ColorGenerator.instance.getColor()
                    }, options));
                    this.m_conditions = this.generateConditionsCollection(options.conditions);
                    this.m_filters = this.generateFiltersCollection(options.filters);
                }
                get conditions() {
                    return this.m_conditions;
                }
                get filters() {
                    return this.m_filters;
                }
                get operatorName() {
                    return this.state.get("operatorName");
                }
                set operatorName(value) {
                    this.state.set("operatorName", value);
                }
                get isFirst() {
                    var _a, _b;
                    return ((_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.conditions.first()) === null || _b === void 0 ? void 0 : _b.id) == this.id;
                }
                get isLast() {
                    var _a, _b;
                    return ((_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.conditions.last()) === null || _b === void 0 ? void 0 : _b.id) == this.id;
                }
                get parentColor() {
                    var _a;
                    return ((_a = this.parent) === null || _a === void 0 ? void 0 : _a.color) || this.color;
                }
                get color() {
                    return this.state.get("color");
                }
                get hasConditionsOrFilters() {
                    return this.conditions.count > 0
                        || this.filters.count > 0;
                }
                toJSON() {
                    let result = _.extend(this.state.toJSON(), {
                        filters: this.filters.toJSON(),
                        conditions: this.conditions.toJSON()
                    });
                    delete result["parent"];
                    return result;
                }
                remove() {
                    if (this.parent != null) {
                        this.parent.conditions.remove(this);
                    }
                }
                move(target) {
                    this.remove();
                    target.conditions.add(this);
                    this.parent = target;
                }
                getFilter(id) {
                    let result = null;
                    this.filters.each(filter => {
                        if (filter.id === id) {
                            result = filter;
                        }
                    });
                    if (!result) {
                        this.conditions.each(condition => {
                            if (result == null) {
                                result = condition.getFilter(id);
                            }
                        });
                    }
                    return result;
                }
                getCondition(id) {
                    let result = null;
                    if (this.id === id) {
                        result = this;
                    }
                    if (!result) {
                        this.conditions.each(condition => {
                            if (result == null) {
                                result = condition.getCondition(id);
                            }
                        });
                    }
                    return result;
                }
                getCounts() {
                    let conditionCounts = 0;
                    let filterCounts = 0;
                    this.conditions.each(condition => {
                        let counts = condition.getCounts();
                        conditionCounts += counts.conditions;
                        filterCounts += counts.filters;
                    });
                    return {
                        filters: this.filters.count + filterCounts,
                        conditions: this.conditions.count + conditionCounts
                    };
                }
                toKendoData() {
                    let result = this.toJSON();
                    let items = [];
                    items = items.concat(this.filters.toKendoData());
                    items = items.concat(this.conditions.toKendoData());
                    result["items"] = items;
                    result["expanded"] = true;
                    result["hasChildren"] = items.length > 0;
                    result["checked"] = this.isEnabled;
                    delete result.conditions;
                    delete result.filters;
                    return result;
                }
                toMarkup() {
                    let prefix = this.parent == null ?
                        "Select records where" :
                        `<span role="condition">${this.parent.operatorName.toLowerCase()}</span>`;
                    let suffix = "of the following apply";
                    return `<div class="${Views.CssClass.Constraint} ${Views.CssClass.Condition}">
                        <span role="text">
                            ${prefix}
                            <span role="action">${this.operatorName == "AND" ? "ALL" : "ANY"}</span>
                            ${suffix}
                        </span>
                        <span role="color">
                            <span style="background-color:${this.parentColor}"></span>
                            <span style="background-color:${this.hasConditionsOrFilters ? this.color : this.parentColor}"></span>
                        </span>
                    </div>`;
                }
                generateFiltersCollection(items) {
                    let filters = [];
                    (items || []).forEach(item => {
                        filters.push(new Views.Filter(_.extend(item, {
                            parent: this
                        })));
                    });
                    return new Views.FilterCollection(filters);
                }
                generateConditionsCollection(items) {
                    let conditions = [];
                    (items || []).forEach(item => {
                        conditions.push(new Condition(_.extend(item, {
                            parent: this
                        })));
                    });
                    return new Views.ConditionCollection(conditions);
                }
            }
            Views.Condition = Condition;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class ConditionCollection extends Jade.Collection {
                toJSON() {
                    let result = [];
                    this.each(item => {
                        result.push(item.toJSON());
                    });
                    return result;
                }
                toKendoData() {
                    let result = [];
                    this.each(item => {
                        result.push(item.toKendoData());
                    });
                    return result;
                }
            }
            Views.ConditionCollection = ConditionCollection;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class Constraints extends Core.Model {
                constructor(options) {
                    super(options);
                    this.m_condition = options.condition !== null ?
                        new Views.Condition(options.condition) :
                        new Views.Condition({
                            id: Jade.Guid.new(),
                            operatorName: "AND",
                            isEnabled: true,
                            role: "condition"
                        });
                }
                get condition() {
                    return this.m_condition;
                }
                get commitCallback() {
                    return this.state.get("commit", () => { });
                }
                addCondition(condition, parentId) {
                    let parent = parentId != null ?
                        this.getCondition(parentId) :
                        this.condition;
                    let result = new Views.Condition(_.extend(condition, {
                        parent: parent
                    }));
                    parent.conditions.add(result);
                    return result;
                }
                addFilter(filter, parentId) {
                    let parent = parentId != null ?
                        this.getCondition(parentId) :
                        this.condition;
                    let result = new Views.Filter(_.extend(filter, {
                        parent: parent
                    }));
                    parent.filters.add(result);
                    return result;
                }
                getFilter(id, condition = null) {
                    let result = null;
                    if (condition == null) {
                        condition = this.condition;
                    }
                    condition.filters.each(filter => {
                        if (filter.id === id) {
                            result = filter;
                        }
                    });
                    if (!result) {
                        condition.conditions.each(condition => {
                            if (result == null) {
                                result = this.getFilter(id, condition);
                            }
                        });
                    }
                    return result;
                }
                getCondition(id) {
                    let result = null;
                    if (this.condition == null) {
                        return null;
                    }
                    if (this.condition.id === id) {
                        result = this.condition;
                    }
                    if (!result) {
                        this.condition.conditions.each(condition => {
                            if (result == null) {
                                result = condition.getCondition(id);
                            }
                        });
                    }
                    return result;
                }
                getConstraint(id) {
                    let result = null;
                    result = this.getCondition(id);
                    if (result == null) {
                        result = this.getFilter(id);
                    }
                    return result;
                }
                move(srcId, dstId) {
                    let srcConstraint = this.getConstraint(srcId);
                    let dstConstraint = this.getConstraint(dstId);
                    if (srcConstraint == null || dstConstraint == null) {
                        return false;
                    }
                    if (dstConstraint instanceof Views.Condition) {
                        srcConstraint.move(dstConstraint);
                    }
                }
                remove(id) {
                    let constraint = this.getConstraint(id);
                    if (constraint != null) {
                        constraint.remove();
                    }
                }
                clear() {
                    this.condition.conditions.clear();
                    this.condition.filters.clear();
                }
                toJSON() {
                    return this.condition ? this.condition.toJSON() : {};
                }
                toKendoData() {
                    return [this.condition.toKendoData()];
                }
                commit() {
                    this.commitCallback(this.toJSON());
                }
                getTotalDepth() {
                    let result = 0;
                    let depthFunc = (condition) => {
                        let depth = condition.getDepth();
                        result = result < depth ?
                            depth : result;
                        condition.conditions.each(item => {
                            depthFunc(item);
                        });
                    };
                    depthFunc(this.condition);
                    return result;
                }
            }
            Views.Constraints = Constraints;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class ContextFilter {
                constructor(id, params) {
                    this.m_id = id;
                    this.m_params = params;
                }
                get id() {
                    return this.m_id;
                }
                get params() {
                    return this.m_params;
                }
                toJSON() {
                    let result = {
                        id: this.id
                    };
                    if (this.params != null) {
                        result.params = this.params;
                    }
                    return result;
                }
                ;
            }
            Views.ContextFilter = ContextFilter;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class EntityFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static parentFilter(childTypeIds) {
                    return new EntityFilter("ParentFilter", {
                        childTypeIds: childTypeIds.join(",")
                    });
                }
                static descendantsOnly(entityId) {
                    return new EntityFilter("DescendantsOnly", {
                        entityId: entityId
                    });
                }
            }
            Views.EntityFilter = EntityFilter;
            class IdentityFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static activeOnly() {
                    return new IdentityFilter("ActiveOnly");
                }
                static usersOnly() {
                    return new IdentityFilter("UsersOnly");
                }
                static groupsOnly() {
                    return new IdentityFilter("GroupsOnly");
                }
                static excludeAllAdmins() {
                    return new IdentityFilter("ExcludeAllAdmins");
                }
                static excludeSysAdmins() {
                    return new IdentityFilter("ExcludeSysAdmins");
                }
                static excludeBuiltIns() {
                    return new IdentityFilter("ExcludeBuiltIns");
                }
                static excludeEveryone() {
                    return new IdentityFilter("ExcludeEveryone");
                }
            }
            Views.IdentityFilter = IdentityFilter;
            class FormFieldFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static listData(isList) {
                    return new IdentityFilter("ListData", {
                        isList: isList ? 1 : 0
                    });
                }
                static fileBased() {
                    return new IdentityFilter("FileBased");
                }
                static extension(extensionId) {
                    return new IdentityFilter("Extension", {
                        extID: extensionId
                    });
                }
            }
            Views.FormFieldFilter = FormFieldFilter;
            class RuleFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static auditHistory(scriptId) {
                    return new RulesFilter("Script", {
                        id: scriptId
                    });
                }
            }
            Views.RuleFilter = RuleFilter;
            class ExtensionsFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static search(e) {
                    var _a;
                    return new RulesFilter("Search", {
                        entTypes: _.isArray(e.entTypes) ? e.entTypes.join(" ") : null,
                        match: (_a = e.match) !== null && _a !== void 0 ? _a : 1,
                        text: e.term
                    });
                }
            }
            Views.ExtensionsFilter = ExtensionsFilter;
            class RulesFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static content(searchTerm) {
                    return new RulesFilter("Content", {
                        text: searchTerm
                    });
                }
                static expression(expression) {
                    return new RulesFilter("Expression", {
                        text: expression
                    });
                }
            }
            Views.RulesFilter = RulesFilter;
            class DocumentTypeFilter extends Views.ContextFilter {
                constructor(id, params) {
                    super(id, params);
                }
                static AssignableOnly() {
                    return new IdentityFilter("AssignableOnly");
                }
                static entityOnly(entityId) {
                    return new IdentityFilter("EntityOnly", {
                        entityId: entityId
                    });
                }
                static entityTypeOnly(entityTypeId) {
                    return new IdentityFilter("EntityTypeOnly", {
                        entityTypeId: entityTypeId
                    });
                }
            }
            Views.DocumentTypeFilter = DocumentTypeFilter;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            let CssClass;
            (function (CssClass) {
                CssClass["Constraint"] = "-pdjs-view-filter-tree-constraint";
                CssClass["Condition"] = "-pdjs-view-filter-tree-condition";
                CssClass["Filter"] = "-pdjs-view-filter-tree-filter";
            })(CssClass = Views.CssClass || (Views.CssClass = {}));
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class Filter extends Views.Constraint {
                constructor(options) {
                    super(_.extend({
                        id: Jade.Guid.new(),
                        autoValueId: null,
                        autoValueName: null,
                        columnId: null,
                        columnName: null,
                        isEnabled: true,
                        role: "filter",
                        scalarFunctionId: null,
                        scalarFunctionName: null,
                        operatorId: 0,
                        operatorName: "Not Set",
                        useAutoValue: false,
                        value: null,
                        verse: null
                    }, options));
                }
                get autoValueId() {
                    return this.state.get("autoValueId");
                }
                get autoValueName() {
                    return this.state.get("autoValueName");
                }
                get columnId() {
                    return this.state.get("columnId");
                }
                get columnName() {
                    return this.state.get("columnName");
                }
                get operatorId() {
                    return this.state.get("operatorId");
                }
                get operatorName() {
                    return this.state.get("operatorName");
                }
                get scalarFunctionId() {
                    return this.state.get("scalarFunctionId");
                }
                get scalarFunctionName() {
                    return this.state.get("scalarFunctionName");
                }
                get useAutoValue() {
                    return this.state.get("useAutoValue");
                }
                get value() {
                    return this.state.get("value");
                }
                get verse() {
                    return this.state.get("verse");
                }
                get isFirst() {
                    var _a, _b;
                    return ((_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.filters.first()) === null || _b === void 0 ? void 0 : _b.id) == this.id;
                }
                get isLast() {
                    var _a, _b;
                    return ((_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.filters.last()) === null || _b === void 0 ? void 0 : _b.id) == this.id;
                }
                get color() {
                    return this.parent.color;
                }
                toJSON() {
                    let result = _.extend(this.state.toJSON(), {
                        useAutoValue: this.autoValueId != null
                    });
                    delete result["parent"];
                    return result;
                }
                remove() {
                    if (this.parent != null) {
                        this.parent.filters.remove(this);
                    }
                }
                update(state) {
                    if (state != null) {
                        this.state.set(state);
                    }
                }
                toKendoData() {
                    return _.extend({
                        checked: this.isEnabled
                    }, this.toJSON());
                }
                move(target, insertAt) {
                    this.remove();
                    if (insertAt != null) {
                        target.filters.insert(this, insertAt);
                    }
                    else {
                        target.filters.add(this);
                    }
                    this.parent = target;
                }
                toMarkup() {
                    let useVerse = !Jade.String.isNullOrWhiteSpace(this.verse);
                    let useValue = !Jade.String.isNullOrWhiteSpace(this.value);
                    let value = useVerse ? this.verse : (useValue ? this.value : "");
                    let conditionName = this.isLast ?
                        "" : this.parent.operatorName.toLowerCase();
                    return `
                <div class="${Views.CssClass.Constraint} ${Views.CssClass.Filter}" state="${this.operatorId == 0 ? "not-set" : "set"}">
                    <span role="text">
                        <span role="scalar">${this.scalarFunctionName ? `${this.scalarFunctionName} of` : ""}</span>
                        <span role="name">${this.columnName}</span>
                        <span role="operator">${this.operatorId == 0 ? "Not Set" : this.operatorName}</span>
                        <span role="value" ${this.autoValueId ? "is-auto" : ""}>${this.autoValueId ? this.autoValueName : value}</span>
                        <span role="condition">${conditionName}</span>
                    </span>
                    <span role="color">
                        <span style="background-color:${this.color}"></span>
                    </span>
                </div>`;
                }
            }
            Views.Filter = Filter;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Core;
    (function (Core) {
        var Views;
        (function (Views) {
            class FilterCollection extends Jade.Collection {
                toJSON() {
                    let result = [];
                    this.each(item => {
                        result.push(item.toJSON());
                    });
                    return result;
                }
                toKendoData() {
                    let result = [];
                    this.each(item => {
                        result.push(item.toKendoData());
                    });
                    return result;
                }
            }
            Views.FilterCollection = FilterCollection;
        })(Views = Core.Views || (Core.Views = {}));
    })(Core = PDJS.Core || (PDJS.Core = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class ApplicationBar extends Jade.UI.Control {
            get titleNode() {
                return this.node.children("div[role=title]");
            }
            get rightDockNode() {
                return this.node.find("div[role=dock-r]");
            }
            get leftDockNode() {
                return this.node.find("div[role=dock-l]");
            }
            get env() {
                return PDJS.System.Environment.current;
            }
            template() {
                return `
                <div class="-pdjs-application-bar">
                    <div role="dock-l"></div>
                    <div role="title"></div>
                    <div role="dock-r" data-controls></div>
                </div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.populate();
            }
            populate() {
                this.controls.add(new Hub.ApplicationBarItem({
                    icon: "font:fa-home fa-sharp",
                    url: Jade.Path.resolve("~/Hub/Home")
                }));
                if (this.env.settings.shortcutEntityTypes.length > 0) {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "font:fa-sharp fa-add",
                        onClick: (e) => {
                            this.m_createPanel.toggle();
                        }
                    }));
                }
                if (this.env.settings.shortcutViews.length == 0) {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "font:fa-sharp fa-binoculars",
                        url: Jade.Path.resolve("~/Hub/ViewBrowser/Global")
                    }));
                }
                else {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "font:fa-sharp fa-binoculars",
                        onClick: (e) => {
                            this.m_viewPanel.toggle();
                        }
                    }));
                }
                this.controls.add(new Hub.GlobalSearch({
                    width: 200
                }));
                this.controls.add(new Hub.ApplicationBarItem({
                    backgroundColor: "var(--visiv-theme-application-bar-back-color-dark)",
                    icon: "font: fa-solid fa-user-circle",
                    fontSize: 22,
                    cssClass: "-pdjs-application-bar-user-item",
                    onClick: (e) => {
                        this.m_userPanel.toggle();
                    }
                }));
                let width = 0;
                this.controls.each((control) => {
                    if (control instanceof Hub.ApplicationBarItem) {
                        width += control.width;
                    }
                });
                this.titleNode.css({
                    right: `${width + 10}px`,
                    color: "var(--visiv-theme-application-bar-text-color)"
                });
                this.titleNode.text(this.env.settings.applicationName);
                this.createPanel_init();
                this.userPanel_init();
                this.viewPanel_init();
            }
            createPanel_init() {
                this.m_createPanel = new Hub.CreatePanel({
                    anchor: this.rightDockNode,
                    top: 41
                });
                this.controls.add(this.m_createPanel);
            }
            userPanel_init() {
                this.m_userPanel = new Hub.UserPanel({
                    anchor: this.rightDockNode,
                    top: 41
                });
                this.controls.add(this.m_userPanel);
            }
            viewPanel_init() {
                this.m_viewPanel = new Hub.ViewPanel({
                    anchor: this.rightDockNode,
                    top: 41
                });
                this.controls.add(this.m_viewPanel);
            }
        }
        Hub.ApplicationBar = ApplicationBar;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class ApplicationBarItem extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get backgroundColor() {
                return this.state.get("backgroundColor", null);
            }
            get cssClass() {
                return this.state.get("cssClass", null);
            }
            get fontSize() {
                return this.state.get("fontSize", 20);
            }
            get icon() {
                return this.state.get("icon");
            }
            get isClickCallback() {
                return this.onClickCallback != null;
            }
            get isUrl() {
                return !Jade.String.isNullOrWhiteSpace(this.url);
            }
            get onClickCallback() {
                return this.state.get("onClick");
            }
            get target() {
                return this.state.get("target");
            }
            get url() {
                return this.state.get("url", "#");
            }
            get width() {
                return this.state.get("width", 40);
            }
            template() {
                if (this.isUrl) {
                    return `<a></a>`;
                }
                return `<a href="${Jade.Path.resolve(this.url)}"></a>`;
            }
            onActivate(e) {
                super.onActivate(e);
                let icon = Jade.Path.resolve(this.icon);
                this.node.css({
                    position: "relative",
                    display: "inline-block",
                    height: "40px",
                    width: `${this.width}px`,
                    backgroundPosition: "center center",
                    backgroundRepeat: "no-repeat",
                    backgroundColor: this.backgroundColor || "",
                    textDecoration: "none"
                });
                if (this.icon != null) {
                    if (this.icon.startsWith("font:")) {
                        this.node.append(`<i class="${this.icon.substr("font:".length)}" style="font-size:${this.fontSize}px;padding-top:1px;"></i>`);
                        this.node.css({
                            display: "inline-flex",
                            verticalAlign: "top",
                            alignItems: "center",
                            justifyContent: "space-around",
                            color: "var(--visiv-theme-application-bar-icon-color, var(--visiv-theme-application-bar-text-color))"
                        });
                    }
                    else {
                        this.node.css({
                            backgroundImage: `url(${icon})`,
                            color: "var(--visiv-theme-application-bar-text-color)"
                        });
                    }
                }
                if (this.isUrl) {
                    this.node.attr("href", Jade.Path.resolve(this.url));
                }
                if (this.isClickCallback) {
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.onClickCallback(e);
                        e.preventDefault();
                        e.cancelBubble = true;
                        e.returnValue = false;
                        return false;
                    });
                }
                if (this.target != null) {
                    this.node.attr("target", this.target);
                }
                if (this.cssClass) {
                    this.node.addClass(this.cssClass);
                }
                this.node.addClass("-pdjs-application-bar-item");
            }
        }
        Hub.ApplicationBarItem = ApplicationBarItem;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuPopUp extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get anchor() {
                        return this.state.get("anchor", $());
                    }
                    get hideOnMoueLeave() {
                        return this.state.get("hideOnMoueLeave", true);
                    }
                    get hideOnClickOutside() {
                        return this.state.get("hideOnClickOutside", true);
                    }
                    get hideOthers() {
                        return this.state.get("hideOthers", true);
                    }
                    get top() {
                        return this.state.get("top", 0);
                    }
                    get visible() {
                        return this.node.is(":visible");
                    }
                    template(content = "") {
                        return `<div class="-pdjs-ui-panel-menu">${content || ""}</div>`;
                    }
                    hide() {
                        this.node.hide();
                        this.hideOnClickEventOff();
                    }
                    show() {
                        if (this.hideOthers) {
                            this.hideOtherPanels();
                        }
                        this.node.show();
                        this.hideOnClickEventOn();
                    }
                    toggle() {
                        if (this.visible) {
                            this.hide();
                        }
                        else {
                            this.show();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            top: this.top == 0 ? "" : `${this.top}px`,
                            display: "none"
                        });
                        this.node.detach();
                        $("body").append(this.node);
                        this.anchor.on(Jade.BrowserEvent.CLICK, (e) => {
                            if (this.visible) {
                                this.hide();
                            }
                            else {
                                this.show();
                            }
                        });
                    }
                    hideOtherPanels() {
                        $(`.-pdjs-ui-panel-menu`).hide();
                    }
                    hideOnClickEventOn() {
                        if (this.hideOnClickOutside) {
                            $("body").on(`${Jade.BrowserEvent.CLICK}.PanelMenuHideOnClick`, (e) => {
                                let target = $(e.target);
                                if (document.contains(e.target) && target.closest(`#${this.ID}`).length === 0) {
                                    this.hide();
                                }
                            });
                        }
                    }
                    hideOnClickEventOff() {
                        if (this.hideOnClickOutside) {
                            $("body").off(`${Jade.BrowserEvent.CLICK}.PanelMenuHideOnClick`);
                        }
                    }
                }
                Controls.PanelMenuPopUp = PanelMenuPopUp;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class CreatePanel extends PDJS.Shared.UI.Controls.PanelMenuPopUp {
            constructor(options) {
                super(options);
            }
            get entityTypes() {
                return PDJS.System.Environment.current.settings.shortcutEntityTypes;
            }
            onActivate(e) {
                super.onActivate(e);
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: "Create New"
                }));
                this.entityTypes.forEach((entry) => {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuAction({
                        label: entry.name,
                        icon: entry.icon,
                        description: entry.description,
                        click: (e) => {
                            this.hide();
                            PDJS.Entities.EntityDialogs.showCreate({
                                entityTypeId: entry.id,
                                entityTypeName: entry.name
                            });
                        }
                    }));
                });
            }
        }
        Hub.CreatePanel = CreatePanel;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class GlobalSearch extends Hub.ApplicationBarItem {
            get searchBox() {
                return this.m_searchBox;
            }
            template() {
                return `<div class="--pdjs-application-bar-global-search"></div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                    onSearch: (e) => {
                        PDJS.Shared.PopOver.remove(this.searchBox.node);
                        let searchTerm = this.searchBox.textValue;
                        let isValidSearch = searchTerm.length > 1;
                        if (!isValidSearch) {
                            this.searchBox.clear();
                            this.searchBox.maskValue = searchTerm;
                            this.searchBox.textValue = searchTerm;
                            this.searchBox.focus();
                            this.showSearchTermErrorMessage();
                            return;
                        }
                        PDJS.Hub.Explorer.Navigator.navigate(Jade.Path.resolve(`~/hub/search`, { term: searchTerm }));
                    }
                });
                this.controls.add(this.searchBox);
            }
            showSearchTermErrorMessage() {
                PDJS.Shared.PopOver.validation(this.searchBox.node, "<div>Search term must be at least 2 characters in length.</div>");
                PDJS.Shared.PopOver.show(this.searchBox.node);
            }
        }
        Hub.GlobalSearch = GlobalSearch;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuList extends Jade.UI.Control {
                    constructor(options = {}) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get items() {
                        return this.state.get("items", []);
                    }
                    clear() {
                        this.node.empty();
                    }
                    populate(items) {
                        items.forEach(item => {
                            this.node.append(`<option value="${item.value}">${item.name}</option>`);
                        });
                    }
                    template() {
                        return `<select style="margin-bottom:10px;box-sizing:border-box;width:100%;"></select>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.onChange(this.getSelection());
                        });
                        this.populate(this.items);
                    }
                    onChange(item) {
                        this.changeCallback(item);
                    }
                    getSelection() {
                        let option = this.node.find('option:selected');
                        let result = null;
                        if (option.length == 1) {
                            result = {
                                name: option.text(),
                                value: option.attr("value")
                            };
                        }
                        return result;
                    }
                }
                Controls.PanelMenuList = PanelMenuList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class ThemesList extends PDJS.Shared.UI.Controls.PanelMenuList {
            constructor(options = {}) {
                super();
                this.m_debounce = _.debounce(_.bind(this.onSelectionChange, this), 300);
                this.m_broadcaster = new PDJS.Shared.Themes.ThemeBroadcaster();
                this.m_broadcaster.subscribeSwitchTheme((e) => {
                    if (e.themeScope == PDJS.Services.Themes.ThemeScope.Hub) {
                        this.node.val(e.themeId);
                    }
                });
            }
            onChange(item) {
                this.m_debounce(item);
            }
            onActivate(e) {
                super.onActivate(e);
                this.populateThemes();
                this.subscriptions.add(PDJS.Shared.Themes.EventsHub.themeListChangedSubscribe(() => {
                    this.populateThemes();
                }));
            }
            populateThemes() {
                let service = new PDJS.Services.Themes.ThemeService();
                service.list({
                    enabledOnly: true,
                    success: (e) => {
                        let items = [
                            { name: "- Default Theme -", value: "" }
                        ];
                        e.data.forEach(t => {
                            items.push({ name: t.name, value: t.id });
                        });
                        this.populate(items);
                        this.setSelectedTheme(e.data);
                    }
                });
            }
            onSelectionChange(item) {
                PDJS.Shared.Themes.Theme.hub.switchTheme(item.value);
            }
            setSelectedTheme(themes) {
                let themeIsActive = themes.find((theme) => {
                    return theme.id == PDJS.Application.profile.themes.hub;
                }) != null;
                if (!PDJS.Application.profile.themes.isHubUsingDefault && themeIsActive) {
                    this.node.val(PDJS.Application.profile.themes.hub);
                }
            }
        }
        Hub.ThemesList = ThemesList;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class UserPanel extends PDJS.Shared.UI.Controls.PanelMenuPopUp {
            constructor(options) {
                super(options);
            }
            get env() {
                return PDJS.System.Environment.current;
            }
            get profile() {
                return PDJS.System.Environment.current.profile;
            }
            get entities() {
                return PDJS.System.Environment.current.profile.recent.entities;
            }
            get views() {
                return PDJS.System.Environment.current.profile.recent.views;
            }
            template() {
                let content = `
                <div data-controls></div>
                <div role="brand-and-version"></div>`;
                return super.template(content);
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.css({
                    top: `${this.top}px`
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: this.profile.identity.displayName
                }));
                this.addRecentEntities();
                this.addRecentViews();
                this.addPersonalization();
                this.addAdministration();
                this.addHelp();
                this.addLogout();
                this.addVersion();
                this.node.addClass("-pdjs-hub-user-panel");
            }
            addRecentEntities() {
                if (this.entities.length == 0) {
                    return;
                }
                this.controls.add(new Hub.RecentEntities());
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addRecentViews() {
                if (this.views.length == 0) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Recent Views"
                }));
                this.views.forEach((entry) => {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: entry.name,
                        description: entry.description,
                        url: Jade.Path.resolve("~/viewbrowser?viewid=" + entry.id)
                    }));
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addPersonalization() {
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Personalization"
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Views",
                    url: Jade.Path.resolve("~/Hub/ViewBrowser/Personal")
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Preferences",
                    click: (e) => {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "Preferences",
                            args: {
                                targetType: "ProspectDirector.Web.Shared.Modules.Personalization.PreferencesUIO",
                                arbiterType: "ProspectDirector.Web.Shared.Modules.Personalization.PreferencesArbiter"
                            },
                            select: {
                                "ok": (sender, e) => {
                                    PDJS.System.Environment.current.profile.preferences.update(e.target);
                                    PDJS.System.Environment.setScrollBarSize();
                                }
                            }
                        });
                        this.hide();
                    }
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Theme"
                }));
                this.controls.add(new Hub.ThemesList());
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addAdministration() {
                if (!this.profile.identity.isAdmin) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Administration"
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Launch Management",
                    url: Jade.Path.resolve("~/manage#/module/overview"),
                    target: PDJS.System.Settings.current.manageWindowId
                }));
            }
            addHelp() {
                if (Jade.String.isNullOrWhiteSpace(this.env.settings.supportUrl)) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Help",
                    url: Jade.Path.resolve(this.env.settings.supportUrl),
                    largeText: true
                }));
            }
            addLogout() {
                if (!this.env.settings.isLocalAuthMode) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Sign Out",
                    url: Jade.Path.resolve("~/Shared/Account/Logout"),
                    largeText: true
                }));
            }
            addVersion() {
                this.controls.add(new PDJS.Shared.BrandAndVersion({
                    insertAt: "[role=brand-and-version]"
                }));
            }
        }
        Hub.UserPanel = UserPanel;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class ViewPanel extends PDJS.Shared.UI.Controls.PanelMenuPopUp {
            constructor(options) {
                super(options);
            }
            get views() {
                return PDJS.System.Environment.current.settings.shortcutViews;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.css({
                    top: `${this.top}px`
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: "Global Views"
                }));
                this.addViews();
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "More...",
                    largeText: true,
                    url: "~/hub/viewbrowser/global"
                }));
            }
            addViews() {
                if (this.views.length < 0) {
                    return;
                }
                this.views.forEach((entry) => {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuAction({
                        label: entry.name,
                        description: entry.description,
                        url: Jade.Path.resolve("~/viewbrowser?viewid=" + entry.id)
                    }));
                });
            }
        }
        Hub.ViewPanel = ViewPanel;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class RecentEntities extends Jade.UI.Control {
            constructor(options = {}) {
                super(options);
            }
            get entities() {
                return PDJS.System.Environment.current.profile.recent.entities;
            }
            get items() {
                return this.controls.getByType(PDJS.Shared.UI.Controls.PanelMenuLink).toArray();
            }
            template() {
                return `<div class="-pdjs-hub-recent-entities">
                        <div role="header"></div>
                        <div data-controls></div>
                    </div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    insertAt: "div[role=header]",
                    label: "Recent"
                }));
                this.addEntities();
                this.subscriptions.add(PDJS.Hub.Explorer.EventsHub.entityChangedSubscribe((e) => {
                    e.forEach(src => {
                        this.items.forEach(dst => {
                            if (src.id.toString() === dst.dataId) {
                                dst.label = src.name;
                            }
                        });
                    });
                }));
            }
            addEntities() {
                if (this.entities.length == 0) {
                    this.node.hide();
                    return;
                }
                this.node.show();
                this.entities.forEach((entry) => {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: entry.name,
                        dataId: entry.id.toString(),
                        description: entry.description,
                        url: Jade.Path.resolve("~/explore/" + entry.id)
                    }));
                });
            }
        }
        Hub.RecentEntities = RecentEntities;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Routing;
        (function (Routing) {
            class Route {
                get event() {
                    return this.m_event;
                }
                set event(value) {
                    this.m_event = value;
                }
                get extendedState() {
                    return this.event.extendedState;
                }
                get requestId() {
                    return this.state.requestId;
                }
                get state() {
                    var _a, _b;
                    return ((_b = (_a = this.event) === null || _a === void 0 ? void 0 : _a.destination) === null || _b === void 0 ? void 0 : _b.getState()) || {};
                }
                canHandle(e) {
                    this.init(e);
                    return true;
                }
                execute(event) {
                    if (this.canHandle(event)) {
                        return () => {
                            return new Promise((resolve, reject) => {
                                this.handle({
                                    event: event,
                                    reject: reject,
                                    resolve: resolve
                                });
                            });
                        };
                    }
                    return null;
                }
                init(e) {
                    this.event = e;
                }
                handle(e) {
                    e.resolve();
                }
            }
            Routing.Route = Route;
        })(Routing = Shared.Routing || (Shared.Routing = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class ExplorerRoute extends PDJS.Shared.Routing.Route {
            get isInitiatedByNavigator() {
                return this.state.navigator === true;
            }
            canHandle(e) {
                return super.canHandle(e)
                    && this.isInitiatedByNavigator
                    && this.parsePath(e.destination.url) != null;
            }
            handle(e) {
                var _a;
                let result = this.parsePath(e.event.destination.url);
                if (result.folderId == null) {
                    result.folderId = (_a = this.state.folderId) === null || _a === void 0 ? void 0 : _a.toString();
                }
                PDJS.Hub.Explorer.EventsHub.contentRequestedPublish({
                    entityId: result.entityId,
                    folderId: result.folderId,
                    record: false,
                    requestId: Jade.Guid.new()
                });
                e.resolve();
            }
            parsePath(path) {
                let result = this.parseFolderPath(path);
                if (result != null) {
                    return result;
                }
                return this.parseEntityPath(path);
            }
            parseFolderPath(path) {
                let regex = /(\/explore\/)([0-9]+)(\/folder\/)([0-9]+)/i;
                if (!regex.test(path)) {
                    return;
                }
                let matches = path.match(regex);
                if (matches != null) {
                    return {
                        entityId: matches[2],
                        folderId: matches[4]
                    };
                }
            }
            parseEntityPath(path) {
                let regex = /(\/explore\/)([0-9]+)/i;
                if (!regex.test(path)) {
                    return;
                }
                let matches = path.match(regex);
                if (matches != null) {
                    return {
                        entityId: matches[2],
                        folderId: null
                    };
                }
            }
        }
        Hub.ExplorerRoute = ExplorerRoute;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        PDJS.Application.onStart(() => {
            PDJS.Shared.Routing.Routes.current.add(new Hub.ExplorerRoute());
        });
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let ContentPageCss;
                (function (ContentPageCss) {
                    ContentPageCss["ContentPageContent"] = "-pdjs-explorer-content";
                    ContentPageCss["ContentPageHead"] = "-pdjs-explorer-content-head";
                    ContentPageCss["ContentPageTabs"] = "-pdjs-explorer-content-tabs";
                    ContentPageCss["ContentPageMenu"] = "-pdjs-explorer-content-menu";
                    ContentPageCss["ContentPageMain"] = "-pdjs-explorer-content-main";
                })(ContentPageCss = Controls.ContentPageCss || (Controls.ContentPageCss = {}));
                class ContentPage extends Jade.UI.Control {
                    get headNode() {
                        return this.node.children(`.${ContentPageCss.ContentPageHead}`);
                    }
                    get headNodeClass() {
                        return ContentPageCss.ContentPageHead;
                    }
                    get tabsNode() {
                        return this.node.children(`.${ContentPageCss.ContentPageTabs}`);
                    }
                    get tabsNodeClass() {
                        return ContentPageCss.ContentPageTabs;
                    }
                    get menuNode() {
                        return this.node.children(`.${ContentPageCss.ContentPageMenu}`);
                    }
                    get menuNodeClass() {
                        return ContentPageCss.ContentPageMenu;
                    }
                    get bodyNode() {
                        return this.node.children(`.${ContentPageCss.ContentPageMain}`);
                    }
                    get bodyNodeClass() {
                        return ContentPageCss.ContentPageMain;
                    }
                    template() {
                        return `<div class="${ContentPageCss.ContentPageContent}">
                        <div class="${ContentPageCss.ContentPageHead}"></div>
                        <div class="${ContentPageCss.ContentPageTabs}"></div>
                        <div class="${ContentPageCss.ContentPageMenu}"></div>
                        <div class="${ContentPageCss.ContentPageMain}" data-controls></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addHead();
                        this.addTabs();
                        this.addMenu();
                    }
                    addHead() {
                    }
                    addTabs() {
                    }
                    addMenu() {
                    }
                }
                Controls.ContentPage = ContentPage;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ContentPage extends PDJS.Shared.UI.Controls.ContentPage {
                constructor(options) {
                    super(options);
                    this.subscriptions.add(Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("Explorer:Content:Unload", () => {
                        this.destroy();
                    }));
                }
                get entityId() {
                    return this.state.get("data.entityId");
                }
                get entityName() {
                    return this.state.get("data.entityName");
                }
                get entityTypeId() {
                    return this.state.get("data.entityTypeId");
                }
                get folderId() {
                    return this.state.get("data.folderId");
                }
                get folderIcon() {
                    return this.state.get("data.folderIcon");
                }
                get folderName() {
                    return this.state.get("data.folderName");
                }
                get allowUploads() {
                    return this.getProperty("allowUploads");
                }
                get allowAddChildren() {
                    return this.getProperty("allowAddChildren");
                }
                get allowAddFiles() {
                    return this.getProperty("allowAddFiles");
                }
                get allowReplaceFiles() {
                    return this.getProperty("allowReplaceFile");
                }
                get allowEdit() {
                    return this.getProperty("allowEdit");
                }
                get allowDeleteListData() {
                    return this.getProperty("allowDeleteListData");
                }
                get allowUpdateListData() {
                    return this.getProperty("allowUpdateListData");
                }
                get allowDeleteFile() {
                    return this.getProperty("allowDeleteFiles");
                }
                get allowCreateEntity() {
                    return this.getProperty("allowCreateEntity");
                }
                get head() {
                    return this.m_head;
                }
                get tabs() {
                    return this.state.get("data.tabs", []);
                }
                set tabs(value) {
                    this.state.set("data.tabs", value);
                }
                get viewStateId() {
                    return this.getProperty("viewStateID");
                }
                get contextualFilters() {
                    return this.getProperty("contextFilters");
                }
                get documentId() {
                    return this.getProperty("canvasID");
                }
                get extensionId() {
                    return this.getProperty("extensionID");
                }
                get entityTypes() {
                    return this.getProperty("entityTypes");
                }
                get promptAfterCreate() {
                    return this.getProperty("promptAfterCreate");
                }
                get doubleClickMode() {
                    return this.getProperty("doubleClickMode");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addMenu();
                    this.addAdminMenu();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .clear();
                    if (this.m_refreshExplorerTabsSubscription != null) {
                        this.m_refreshExplorerTabsSubscription.unsubscribe();
                    }
                }
                addHead() {
                    this.m_head = new Explorer.ContentPageHeader({
                        insertAt: `.${this.headNodeClass}`,
                        entityId: this.entityId,
                        entityName: this.entityName,
                        folderIcon: this.folderIcon,
                        folderName: this.folderName
                    });
                    this.controls.add(this.m_head);
                }
                addTabs() {
                    if (this.tabs.length == 0) {
                        return;
                    }
                    if (this.m_tabs != null) {
                        this.m_tabs.destroy();
                    }
                    let tabs = this.tabs.map(tab => {
                        return {
                            text: tab.fileCount > 0 ? `${tab.folderName}&nbsp<b>(${tab.fileCount})</b>` : tab.folderName,
                            icon: tab.folderIcon,
                            value: tab.folderId,
                            entityId: tab.entityId,
                            folderId: tab.folderId,
                            selected: this.folderId == tab.folderId
                        };
                    });
                    ;
                    this.m_tabs = new PDJS.Shared.UI.Controls.TabStrip({
                        insertAt: `.${this.tabsNodeClass}`,
                        tabsData: tabs,
                        binding: {
                            value: "folderId",
                            icon: "icon",
                            text: "text"
                        },
                        click: (e) => {
                            let item = e.item.state.toJSON();
                            Explorer.Navigator.navigate({
                                entityId: item.entityId,
                                folderId: item.folderId,
                                record: true,
                                reject: () => {
                                    e.cancel = true;
                                }
                            });
                        }
                    });
                    this.controls.add(this.m_tabs);
                    this.m_refreshExplorerTabsSubscription =
                        Explorer.EventsHub.reloadExplorerTabsSubscribe(() => {
                            this.reloadTabs();
                        });
                }
                getProperty(id) {
                    return this.state.get(`data.properties.${id}`);
                }
                addAdminMenu() {
                    if (!PDJS.Profiles.Profile.current.identity.isAdmin) {
                        return;
                    }
                    let node = $(`<div class="-pdjs-context-page-button"><i class="icofont-gear"></i></div>`);
                    this.head.actionsNode.append(node);
                    this.m_adminMenu =
                        new PDJS.Shared.UI.Controls.ContextMenu({
                            anchor: node,
                            segments: [new PDJS.Hub.Explorer.Canvas.ContentPageMenu()],
                            width: 200,
                            show: (e) => {
                                return {
                                    target: e.target,
                                    canvasId: this.getProperty("canvasID"),
                                    entityTypeId: this.entityTypeId
                                };
                            },
                            options: {
                                showOn: "click",
                                position: {
                                    target: "bottomright",
                                    tooltip: "topright"
                                },
                                offset: {
                                    y: 5,
                                    x: 5
                                }
                            }
                        });
                    this.controls.add(this.m_adminMenu);
                }
                reloadTabs() {
                    let service = new PDJS.Services.Explorer.ExplorerService();
                    service.getContent({
                        entityId: PDJS.Hub.Explorer.ExplorerContext.current.entityId,
                        folderId: PDJS.Hub.Explorer.ExplorerContext.current.folderId,
                        success: (e) => {
                            this.tabs = e.data.tabs;
                            this.addTabs();
                        },
                        error: (e) => {
                            e.errorHandled = true;
                        }
                    });
                }
            }
            Explorer.ContentPage = ContentPage;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ContentErrorPage extends Explorer.ContentPage {
                constructor(options) {
                    super(options);
                }
                get contentError() {
                    return this.state.get("data.error");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.loadContentErrorMessage();
                }
                loadContentErrorMessage() {
                    var _a;
                    let errorMessage = ((_a = this.contentError) === null || _a === void 0 ? void 0 : _a.message) || "Error accessing content.";
                    this.controls.add(new PDJS.Shared.UI.Controls.Message({
                        fontSize: "20px",
                        backgroundColor: "var(--visiv-theme-base-1-back-color)",
                        icon: Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x48),
                        message: `${this.getIcon()}${errorMessage}`
                    }));
                }
                getIcon() {
                    return `<i class="icofont-ban" style="font-size: 200px;vertical-align: middle;color:var(--visiv-system-red);padding-right: 10px;"></i><br/><br/>`;
                }
            }
            Explorer.ContentErrorPage = ContentErrorPage;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            let CssClass;
            (function (CssClass) {
                CssClass["ExplorerTree"] = "-pdjs-explorer-tree";
                CssClass["ExplorerTreeNode"] = "";
            })(CssClass = Explorer.CssClass || (Explorer.CssClass = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            let Events;
            (function (Events) {
                Events["CanvasLoaded"] = "CanvasLoaded";
                Events["ContentLoaded"] = "ContentLoaded";
                Events["ContentRequested"] = "ContentRequested";
                Events["EntityChanged"] = "EntityChanged";
                Events["ReloadExplorer"] = "ReloadExplorer";
                Events["ReloadExplorerTabs"] = "ReloadExplorerTabs";
                Events["FilesMoved"] = "FilesMoved";
            })(Events = Explorer.Events || (Explorer.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static contentLoadedPublish(args) {
                    this.global.publish(Events.ContentLoaded, args);
                }
                static contentRequestedPublish(args) {
                    this.global.publish(Events.ContentRequested, args);
                }
                static entityChangedPublish(args) {
                    this.global.publish(Events.EntityChanged, args);
                }
                static reloadExplorerPublish(args = {}) {
                    this.global.publish(Events.ReloadExplorer, args);
                }
                static reloadExplorerTabsPublish() {
                    this.global.publish(Events.ReloadExplorerTabs);
                }
                static contentLoadedSubscribe(handler) {
                    return this.global.subscribe(Events.ContentLoaded, handler);
                }
                static contentRequestedSubscribe(handler) {
                    return this.global.subscribe(Events.ContentRequested, handler);
                }
                static entityChangedSubscribe(handler) {
                    return this.global.subscribe(Events.EntityChanged, handler);
                }
                static reloadExplorerSubscribe(handler) {
                    return this.global.subscribe(Events.ReloadExplorer, handler);
                }
                static reloadExplorerTabsSubscribe(handler) {
                    return this.global.subscribe(Events.ReloadExplorerTabs, handler);
                }
            }
            Explorer.EventsHub = EventsHub;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ExplorerContent extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_formTypeMap = {
                        "canvas": PDJS.Hub.Explorer.Canvas.CanvasPage,
                        "content.list": PDJS.Hub.Explorer.ContentList.ContentListPage,
                        "file.folder": PDJS.Hub.Explorer.FileFolder.FileFolderPage,
                        "file.explorer": PDJS.Hub.Explorer.FileExplorer.FileExplorerPage,
                        "list.data": PDJS.Hub.Explorer.DesignableList.DesignableListPage,
                        "custom": PDJS.Hub.Explorer.CustomUrl.CustomUrlPage,
                        "html.template": PDJS.Hub.Explorer.HtmlTemplate.HtmlTemplatePage
                    };
                    Explorer.EventsHub.contentRequestedSubscribe((e) => {
                        this.requestId = e.requestId;
                        let load = () => {
                            this.load({
                                entityId: e.entityId,
                                folderId: e.folderId,
                                record: e.record
                            });
                        };
                        if (!document.startViewTransition) {
                            load();
                            return;
                        }
                        setTimeout(() => {
                            if (e.requestId == this.requestId) {
                                document.startViewTransition(() => load());
                            }
                        }, 200);
                    });
                }
                get requestId() {
                    return this.m_requestId;
                }
                set requestId(value) {
                    this.m_requestId = value;
                }
                template() {
                    return `<div style="height:100%;width:100%;"></div>`;
                }
                load(args) {
                    let service = new PDJS.Services.Explorer.ExplorerService();
                    service.getContent({
                        entityId: args.entityId,
                        folderId: args.folderId,
                        success: (e) => {
                            this.controls.clear();
                            if (this.loadContentError(args, e.data)) {
                                return;
                            }
                            this.loadContent(args, e.data);
                        },
                        error: (e) => {
                            let data = _.first(e.xhr.responseJSON);
                            if (this.loadContentError(args, data)) {
                                e.errorHandled = true;
                            }
                        }
                    });
                }
                loadContent(args, data) {
                    let page = this.m_formTypeMap[data.formTypeId];
                    if (page == null) {
                        return;
                    }
                    let contentPage = new page({
                        data: data
                    });
                    this.controls.add(contentPage);
                    Explorer.EventsHub.contentLoadedPublish({
                        entityId: args.entityId,
                        folderId: args.folderId,
                        isHistory: !args.record
                    });
                }
                loadContentError(args, data) {
                    if ((data === null || data === void 0 ? void 0 : data.error) == null) {
                        return false;
                    }
                    let contentPage = new Explorer.ContentErrorPage({
                        data: data
                    });
                    this.controls.add(contentPage);
                    Explorer.EventsHub.contentLoadedPublish({
                        entityId: args.entityId,
                        folderId: args.folderId,
                        isHistory: !args.record
                    });
                    return true;
                }
            }
            Explorer.ExplorerContent = ExplorerContent;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            let Events;
            (function (Events) {
                Events["FileChangeEvent"] = "File:Change";
            })(Events = Explorer.Events || (Explorer.Events = {}));
            class ExplorerContext {
                static get current() {
                    this.ensureCurrent();
                    return this.m_current;
                }
                get isCanvasFormChanged() {
                    return this.m_isCanvasFormChanged;
                }
                set isCanvasFormChanged(value) {
                    this.m_isCanvasFormChanged = value;
                }
                get entityId() {
                    return this.m_entityId;
                }
                set entityId(value) {
                    this.m_entityId = value;
                }
                get folderId() {
                    return this.m_folderId;
                }
                set folderId(value) {
                    this.m_folderId = value;
                }
                get entityIds() {
                    return this.m_entityIds || [];
                }
                set entityIds(value) {
                    this.m_entityIds = value;
                }
                static init() {
                    let events = Jade.Application
                        .instance
                        .contexts
                        .current
                        .events;
                    events.subscribe("canvas/form/changed", (e) => {
                        this.current.isCanvasFormChanged = true;
                    });
                    events.subscribe("canvas/form/reset", (e) => {
                        this.current.isCanvasFormChanged = false;
                    });
                    events.subscribe("canvas/destroyed", (e) => {
                        this.current.isCanvasFormChanged = false;
                    });
                    Explorer.EventsHub.contentLoadedSubscribe((e) => {
                        if (e.isHistory) {
                            this.current.entityId = e.entityId;
                            this.current.folderId = e.folderId;
                        }
                    });
                }
                load(nodes) {
                    this.entityIds = [];
                    nodes.forEach(node => {
                        this.entityIds.push(node.entityId);
                    });
                }
                unload() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("Explorer:Content:Unload");
                }
                static ensureCurrent() {
                    if (this.m_current == null) {
                        this.m_current = new ExplorerContext();
                    }
                }
            }
            Explorer.ExplorerContext = ExplorerContext;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ExplorerNav extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                template() {
                    return `<div class="-pdjs-hub-explorer-nav">
                        <div role="header">Explorer</div>
                        <div role="tree"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.context_menu_init();
                }
                tree_init() {
                    this.m_tree = new Explorer.ExplorerTree({
                        insertAt: "div[role=tree]",
                        entityId: this.entityId,
                        folderId: this.folderId
                    });
                    this.controls.add(this.m_tree);
                }
                context_menu_init() {
                    this.m_contextMenu = new PDJS.Shared.UI.Controls.ContextMenu({
                        anchor: ".-pdjs-hub-explorer-model",
                        segments: [new Explorer.ExplorerTreeContextMenu()],
                        width: 250,
                        show: (e) => {
                            return {
                                target: e.target,
                                node: this.m_tree.getNodeModel(e.target),
                                tree: this.m_tree
                            };
                        },
                        rightClick: {
                            container: ".-pdjs-hub-explorer-model",
                            target: ".-pdjs-hub-explorer-model-node"
                        }
                    });
                    this.controls.add(this.m_contextMenu);
                }
            }
            Explorer.ExplorerNav = ExplorerNav;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ExplorerPage extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get options() {
                    return this.state.attributes;
                }
                get explorerNav() {
                    return this.m_explorerNav;
                }
                get explorerContent() {
                    return this.m_explorerContent;
                }
                get explorerSplitter() {
                    return this.m_explorerSplitter;
                }
                get explorerSplitterNode() {
                    return this.node;
                }
                template() {
                    return `<div class="-pd-explorer-splitter">
                        <div class="-pd-explorer-pane-nav"></div>
                        <div class="-pd-explorer-pane-content"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.explorerSplitter_init();
                    this.explorerNav_init();
                    this.explorerContent_init();
                    this.isBrowserResizeAware = true;
                    this.explorerContent.load({
                        entityId: this.options.data.entityId,
                        folderId: this.options.data.folderId,
                        record: false
                    });
                    navigation.updateCurrentEntry({ state: { navigator: true, folderId: this.options.data.selectedId } });
                }
                onBrowserResize() {
                    this.explorerSplitter_windowResize();
                }
                explorerNav_init() {
                    this.m_explorerNav = new Explorer.ExplorerNav({
                        insertAt: ".-pd-explorer-pane-nav",
                        entityId: this.options.data.entityId,
                        folderId: this.options.data.selectedId
                    });
                    this.controls.add(this.m_explorerNav);
                }
                explorerContent_init() {
                    this.m_explorerContent = new Explorer.ExplorerContent({
                        insertAt: ".-pd-explorer-pane-content",
                        entityId: this.options.data.entityId
                    });
                    this.controls.add(this.m_explorerContent);
                }
                explorerSplitter_init() {
                    this.m_explorerSplitter = this.node.kendoSplitter({
                        orientation: "horizontal",
                        panes: [
                            {
                                size: "300px",
                                scrollable: false
                            },
                            {
                                scrollable: false
                            }
                        ],
                        resize: (e) => { this.explorerSplitter_resize(e); }
                    }).data("kendoSplitter");
                    setTimeout(() => {
                        this.explorerSplitter.resize();
                    }, 100);
                }
                explorerSplitter_resize(e) {
                    Jade.Application
                        .instance
                        .contexts
                        .global
                        .events
                        .publish("Browser:Resized");
                }
                explorerSplitter_windowResize() {
                    setTimeout(() => {
                        if (this.explorerSplitter != null) {
                            this.explorerSplitter.resize();
                        }
                    }, 100);
                }
            }
            Explorer.ExplorerPage = ExplorerPage;
            PDJS.Application.onStart(() => {
                Explorer.ExplorerContext.init();
            });
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ExplorerTree extends PDJS.Shared.UI.Controls.TreeView {
                constructor(options) {
                    super(options);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                get model() {
                    return super.model;
                }
                createModel() {
                    return new PDJS.Core.Explorer.Model({
                        entityId: this.entityId,
                        folderId: this.folderId,
                        includeTabs: false
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass(PDJS.Core.Explorer.CssClass.Model);
                    Explorer.EventsHub.reloadExplorerSubscribe((e) => {
                        this.refresh({
                            nodeId: e.folderId,
                            expanded: this.getExpandedNodeIds(e.folderId)
                        });
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.subscriptions.add(Explorer.EventsHub.contentLoadedSubscribe((e) => {
                        if (e.isHistory) {
                            this.select(e.folderId);
                        }
                    }));
                }
                onDblClick(e) {
                    e.model.expanded ?
                        this.tree.collapse(e.node) :
                        this.tree.expand(e.node);
                }
                onSelect(e) {
                    super.onSelect(e);
                    let model = e.model;
                    if (!model.isSelectable) {
                        e.preventDefault();
                        return;
                    }
                    Explorer.Navigator.navigate({
                        entityId: model.entityId,
                        folderId: model.folderId,
                        record: true,
                        reject: () => {
                            e.preventDefault();
                        }
                    });
                }
                onNodeRequestComplete(e) {
                    if (this.folderId == null) {
                        return;
                    }
                    if (e.initialize) {
                        this.select(this.folderId);
                    }
                }
            }
            Explorer.ExplorerTree = ExplorerTree;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuItemBase extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    set menu(value) {
                        this.m_menu = value;
                    }
                    get selectCallback() {
                        return this.state.get("select");
                    }
                    get showCallback() {
                        return this.state.get("show");
                    }
                    get menuShowCallback() {
                        return this.m_menuShowCallback;
                    }
                    set menuShowCallback(value) {
                        this.m_menuShowCallback = value;
                    }
                    get menuSelectCallback() {
                        return this.m_menuClickCallback;
                    }
                    set menuSelectCallback(value) {
                        this.m_menuClickCallback = value;
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    mount(args) {
                        this.menu = args.menu;
                        this.menuSelectCallback = args.select;
                        this.menuShowCallback = args.show;
                    }
                    show() {
                        this.onShow();
                    }
                    template(content = "") {
                        return `<div class="-pdjs-context-menu-item-base">${content}</div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, () => {
                            this.onSelect();
                            this.menu.hide();
                        });
                    }
                    onShow() {
                        if (this.showCallback != null) {
                            this.showCallback({
                                menu: this.menu,
                                item: this
                            });
                            this.onStateChanged();
                            return;
                        }
                    }
                    onSelect() {
                        if (!this.enabled) {
                            return;
                        }
                        if (this.selectCallback != null) {
                            this.selectCallback(this);
                            return;
                        }
                        this.menuSelectCallback(this);
                    }
                }
                Controls.ContextMenuItemBase = ContextMenuItemBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuSegment {
                    constructor() {
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    set menu(value) {
                        this.m_menu = value;
                    }
                    mount(args) {
                        this.menu = args.menu;
                    }
                    show(e) {
                        this.onMenuShow(e);
                        this.menu.items.forEach(item => item.show());
                        this.menu.controls.getByType(Controls.ContextMenuSeparator).each(item => item.show());
                    }
                    onMenuShow(e) {
                    }
                    onAddMenuItems(e) {
                    }
                }
                Controls.ContextMenuSegment = ContextMenuSegment;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ExplorerTreeContextMenu extends PDJS.Shared.UI.Controls.ContextMenuSegment {
                get node() {
                    return this.m_node;
                }
                onMenuShow(e) {
                    this.m_node = e.data.node;
                }
                onAddMenuItems(e) {
                    super.onAddMenuItems(e);
                    e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                        value: "open",
                        label: "Open",
                        icon: "folder_into.png",
                        select: (item) => {
                            window.location.href = Jade.Path.resolve(this.getUrl());
                        }
                    }));
                    e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                        value: "open-in-new-window",
                        label: "Open In New Window",
                        icon: "window_new.png",
                        select: (item) => {
                            window.open(Jade.Path.resolve(this.getUrl()));
                        }
                    }));
                    e.addSeparator({
                        show: (e) => {
                            var _a;
                            e.item.visible = ((_a = this.node) === null || _a === void 0 ? void 0 : _a.role) == "entity";
                        }
                    });
                    e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                        value: "move",
                        label: "Move",
                        icon: "folder_into.png",
                        iconSet: "pdjs",
                        show: (e) => {
                            var _a;
                            e.item.visible = (_a = this.node) === null || _a === void 0 ? void 0 : _a.isMoveable;
                        },
                        select: (item) => {
                            PDJS.Shared.Entities.EntityBrowserDialog.open({
                                dialogTitle: "Move | Select Parent",
                                dialogMessage: "From the list below, select an entity to assign as the new parent.",
                                filters: [PDJS.Core.Views.EntityFilter.parentFilter([this.node.entityTypeId])],
                                select: {
                                    ok: (sender, e) => {
                                        this.executeMoveTask(e.entityId);
                                    }
                                }
                            });
                        }
                    }));
                    e.addSeparator({
                        show: (e) => {
                            var _a;
                            e.item.visible = ((_a = this.node) === null || _a === void 0 ? void 0 : _a.role) == "entity";
                        }
                    });
                    e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                        value: "properties",
                        label: "Properties",
                        icon: "pencil.png",
                        iconSet: "pdjs",
                        show: (e) => {
                            var _a;
                            e.item.visible = ((_a = this.node) === null || _a === void 0 ? void 0 : _a.role) == "entity";
                        },
                        select: (item) => {
                            PDJS.Entities.EntityDialogs.showProperties({
                                entityId: this.node.entityId,
                                allowRedirect: false,
                                onSave: (sender, e) => {
                                    Explorer.EventsHub.entityChangedPublish([{
                                            isEntity: true,
                                            isExplorer: false,
                                            icon: null,
                                            id: this.node.entityId,
                                            name: e.target.entityName
                                        }]);
                                    Explorer.EventsHub.reloadExplorerPublish();
                                }
                            });
                        }
                    }));
                }
                getUrl() {
                    let result = "";
                    this.node.folderId != null ?
                        result = `~/Explore/${this.node.entityId}/Folder/${this.node.folderId}` :
                        result = `~/Explore/${this.node.entityId}`;
                    return result;
                }
                executeMoveTask(parentId) {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Entity | Move",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.move({
                                ids: [this.node.entityId],
                                parentId: parentId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            Explorer.EventsHub.reloadExplorerPublish();
                            PDJS.Shared.MessageStack.instance.success(`${this.node.folderName} has been moved.`);
                        }
                    });
                }
            }
            Explorer.ExplorerTreeContextMenu = ExplorerTreeContextMenu;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class Navigator {
                static get internal() {
                    this.ensureNavigator();
                    return this.m_internal;
                }
                static navigate(arg1) {
                    let url = typeof arg1 === "string" ?
                        arg1 : this.generateStateUrl(arg1.entityId, arg1.folderId);
                    let reject = typeof arg1 === "string" ?
                        () => { } : arg1.reject;
                    this.internal.go({
                        directive: () => {
                            typeof arg1 === "string" ?
                                window.location.href = url :
                                PDJS.Shared.Routing.Router.navigate(url, { navigator: true });
                        },
                        error: reject
                    });
                }
                static execute(args) {
                    let reject = _.isFunction(args.reject) ?
                        args.reject : () => { };
                    let success = _.isFunction(args.success) ?
                        args.success : () => { };
                    this.internal.go({
                        directive: () => { success(); },
                        error: () => { reject(); }
                    });
                }
                static ensureNavigator() {
                    if (this.m_internal == null) {
                        this.m_internal = new PDJS.Shared.Navigate.ChangeMonitor({
                            captureAnchorNavigation: true
                        });
                        this.m_internal.validators.add(new PDJS.Shared.Navigate.ChangeMonitorValidator({
                            changes: () => {
                                return Explorer.ExplorerContext.current.isCanvasFormChanged;
                            },
                            reset: () => {
                                Explorer.ExplorerContext.current.isCanvasFormChanged = false;
                            }
                        }));
                    }
                }
                static generateStateUrl(entityId, folderId) {
                    return Jade.Path.resolve(`~/explore/${entityId}/folder/${folderId}`);
                }
            }
            Explorer.Navigator = Navigator;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var Canvas;
            (function (Canvas) {
                class CanvasPage extends Explorer.ContentPage {
                    onActivate(e) {
                        super.onActivate(e);
                        this.controls.add(new PDJS.Canvas.Actual.CanvasViewBox({
                            documentId: this.documentId,
                            entityId: this.entityId,
                            createContext: false
                        }));
                    }
                }
                Canvas.CanvasPage = CanvasPage;
            })(Canvas = Explorer.Canvas || (Explorer.Canvas = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ContentListCommandBase extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            $grid: null,
                            entityId: null,
                            folderId: null,
                            allowCreateEntity: null,
                            allowAddChildren: null
                        });
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get entities() {
                        return this.grid.getSelections().toArray();
                    }
                    get ids() {
                        return this.entities.map(e => {
                            return e.id;
                        });
                    }
                    get currentProfile() {
                        return PDJS.Profiles.Profile.current;
                    }
                }
                ContentList.ContentListCommandBase = ContentListCommandBase;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ContentListCommands extends Jade.CommandGroup {
                    constructor() {
                        super("explorer/content-list");
                    }
                    registerCommands(e) {
                        e.commands.add(new ContentList.NewCommand({}));
                        e.commands.add(new ContentList.OpenCommand({}));
                        e.commands.add(new ContentList.OpenInNewWindowCommand({}));
                        e.commands.add(new ContentList.PropertiesCommand({}));
                        e.commands.add(new ContentList.MoveCommand({}));
                        e.commands.add(new ContentList.DeleteCommand({}));
                    }
                }
                ContentList.ContentListCommands = ContentListCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(ContentListCommands);
                });
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ContentListPage extends Explorer.ContentPage {
                    constructor(options) {
                        super(options);
                    }
                    onTemplate() {
                        let template = `<div class="-pdjs-hub-explorer-content-list-page">
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                        this.bodyNode.append($(template));
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.menu_init();
                        this.setCommandState();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.node.find("[role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.id,
                                            name: item.ObjectName,
                                            typeName: item.ObjectType,
                                            typeId: item.ObjectTypeId
                                        };
                                    });
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            dblclick: (e) => {
                                if (this.doubleClickMode === 0) {
                                    PDJS.System.Environment.current.profile.preferences.onOpenBehavior == 1 ?
                                        this.openEntityInNewWindow() :
                                        this.openEntityInCurrentWindow();
                                }
                                else {
                                    this.openProperties();
                                }
                                this.setCommandState();
                            },
                            needContext: (e) => {
                                e.filters = this.contextualFilters ? this.contextualFilters : [];
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=menu]",
                            segments: [new ContentList.ToolbarSegment()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Explorer.ContentList.ContextMenuSegment",
                                    context: () => {
                                        return {
                                            entityId: this.entityId,
                                            folderId: this.folderId,
                                            entities: this.m_grid.getSelections().toArray()
                                        };
                                    }
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    setCommandState() {
                        if (this.m_grid == null) {
                            return;
                        }
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/content-list": {
                                $grid: this.m_grid,
                                entityTypes: this.entityTypes,
                                entityId: this.entityId,
                                folderId: this.folderId,
                                promptAfterCreate: this.promptAfterCreate,
                                allowAddChildren: this.allowAddChildren,
                                allowCreateEntity: this.allowCreateEntity
                            }
                        }, { force: true });
                    }
                    openProperties() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("explorer/content-list:entity/properties");
                    }
                    openEntityInCurrentWindow() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("explorer/content-list:entity/open");
                    }
                    openEntityInNewWindow() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("explorer/content-list:entity/open-in-new-window");
                    }
                }
                ContentList.ContentListPage = ContentListPage;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ContextMenuSegment extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/properties"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/move"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/delete"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/open"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/open-in-new-window"
                        }));
                    }
                }
                ContentList.ContextMenuSegment = ContextMenuSegment;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/new"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/move"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/delete"
                        }));
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/open"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/open-in-new-window"
                        }));
                    }
                }
                ContentList.ToolbarSegment = ToolbarSegment;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class AddToFavortiesCommand extends ContentList.ContentListCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.entities.length > 0;
                    }
                    onExecute(e) {
                        PDJS.JS.ProspectDirector.Modules.Personalization.AddToFavoritesDialog.Dialog.show({
                            params: {
                                ids: JSON.stringify(this.ids)
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/add-to-favorites",
                            tooltip: "Add To Favorites",
                            label: "Add To Favorites",
                            icon: "star_yellow_add.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                ContentList.AddToFavortiesCommand = AddToFavortiesCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class DeleteCommand extends ContentList.ContentListCommandBase {
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Send to Recycle Bin",
                            message: `Send the selected items to the Recycle Bin?`,
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.deleteEntities();
                                }
                            }
                        });
                    }
                    onStateChanged(e) {
                        this.enabled = this.entities.length > 0;
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    deleteEntities() {
                        let ids = this.ids.slice(0);
                        let loadedIds = PDJS.Hub.Explorer.ExplorerContext.current.entityIds;
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Send to Recycle Bin",
                            enableClose: false,
                            taskStart: (args) => {
                                PDJS.Ajax.call({
                                    type: "POST",
                                    url: Jade.Path.resolve("~/Shared/RecycleBin/Send"),
                                    data: {
                                        ids: this.ids,
                                        status: 4
                                    },
                                    success: function (e) {
                                        args.startPolling(e);
                                    },
                                    error: function (e) {
                                        args.abort(e.responseJSON);
                                        e.errorHandled = true;
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                let found = false;
                                ids.forEach(id => {
                                    if (loadedIds.indexOf(id) > -1) {
                                        found = true;
                                    }
                                });
                                if (found) {
                                    window.location.href = window.location.href;
                                }
                                else {
                                    this.grid.refresh({
                                        clear: true
                                    });
                                }
                            }
                        });
                    }
                }
                ContentList.DeleteCommand = DeleteCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class MoveCommand extends ContentList.ContentListCommandBase {
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.entities.length > 0;
                    }
                    onExecute(e) {
                        super.onExecute(e);
                        let entityTypeIds = [...new Set(this.entities.map(item => item.typeId))];
                        PDJS.Shared.Entities.EntityBrowserDialog.open({
                            dialogTitle: "Move | Select Parent",
                            dialogMessage: "From the list below, select an entity to assign as the new parent.",
                            filters: [PDJS.Core.Views.EntityFilter.parentFilter(entityTypeIds)],
                            select: {
                                ok: (sender, e) => {
                                    this.executeTask(e.entityId);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/move",
                            tooltip: "Move the selected entities to a new parent.",
                            label: "Move",
                            icon: "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    executeTask(parentId) {
                        let service = new PDJS.Services.Entities.EntitiesService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Entities | Move",
                            enableClose: false,
                            autoCloseOnSuccess: true,
                            taskStart: (e) => {
                                service.move({
                                    ids: this.entities.map(item => item.id),
                                    parentId: parentId,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                this.grid.refresh();
                                Explorer.EventsHub.reloadExplorerPublish();
                                PDJS.Shared.MessageStack.instance.success("Selected entities have been moved.");
                            }
                        });
                    }
                }
                ContentList.MoveCommand = MoveCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class NewCommand extends ContentList.ContentListCommandBase {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            entityTypes: null,
                            promptAfterCreate: null
                        });
                    }
                    get buttonNode() {
                        return $(`[command-id=${this.UID}]`);
                    }
                    get entityTypes() {
                        return this.state.get("entityTypes", []);
                    }
                    get promptAfterCreate() {
                        return this.state.get("promptAfterCreate", true);
                    }
                    get allowAddChildren() {
                        return this.state.get("allowAddChildren", false);
                    }
                    get allowCreateEntity() {
                        return this.state.get("allowCreateEntity", false);
                    }
                    onExecute(e) {
                        if (this.buttonNode == null) {
                            return;
                        }
                        if (this.entityTypes.length == 1) {
                            this.showCreateEntityDialog(this.entityTypes[0].id);
                        }
                        if (this.entityTypes.length > 1) {
                            this.triggerPopUp();
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/new",
                            tooltip: "New",
                            label: "New",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.entityTypes.length > 0 && this.allowAddChildren;
                        this.visible = this.allowCreateEntity;
                    }
                    triggerPopUp() {
                        if (this.m_popUp == null) {
                            this.createPopUp();
                        }
                        if (this.m_popUp != null) {
                            this.m_popUp.show();
                        }
                    }
                    createPopUp() {
                        this.m_popUp = new PDJS.Shared.UI.Controls.PopUp({
                            container: this.buttonNode,
                            anchor: this.buttonNode,
                            tipped: {
                                skin: "themed",
                                offset: { y: 3 }
                            }
                        });
                        this.entityTypes.forEach(data => {
                            let item = new PDJS.Shared.UI.Controls.PopUpItem({
                                click: () => {
                                    this.m_popUp.hide();
                                    this.showCreateEntityDialog(data.id);
                                },
                                data: {
                                    id: data.id,
                                    label: data.name,
                                    icon: data.icon
                                }
                            });
                            this.m_popUp.controls.add(item);
                            item.node.css({
                                width: "100%",
                                minWidth: "150px"
                            });
                        });
                    }
                    showCreateEntityDialog(entityTypeId) {
                        PDJS.Entities.EntityDialogs.showCreate({
                            entityTypeId: entityTypeId,
                            parentId: this.entityId,
                            onCreate: (sender, e) => {
                                this.grid.refresh({
                                    selections: [e.target.entityId],
                                    clear: true
                                });
                            }
                        });
                    }
                }
                ContentList.NewCommand = NewCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class OpenCommand extends ContentList.ContentListCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.entities.length == 1;
                    }
                    onExecute(e) {
                        let entity = this.entities[0];
                        window.location.href = Jade.Path.resolve(`~/explore/${entity.id}`);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/open",
                            tooltip: "Open",
                            label: "Open",
                            icon: "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                ContentList.OpenCommand = OpenCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class OpenInNewWindowCommand extends ContentList.ContentListCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.entities.length == 1;
                    }
                    onExecute(e) {
                        let entity = this.entities[0];
                        window.open(Jade.Path.resolve(`~/explore/${entity.id}`));
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/open-in-new-window",
                            tooltip: "Open In New Window",
                            label: "Open In New Window",
                            icon: "window_new.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                ContentList.OpenInNewWindowCommand = OpenInNewWindowCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class PropertiesCommand extends ContentList.ContentListCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.entities.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Entities.EntityDialogs.showProperties({
                            entityId: this.ids[0],
                            onSave: (sender, e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/properties",
                            tooltip: "Properties",
                            label: "Properties",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                ContentList.PropertiesCommand = PropertiesCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var ContentList;
            (function (ContentList) {
                class ReportsCommand extends ContentList.ContentListCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.entities.length == 1;
                    }
                    onExecute(e) {
                        let entity = this.entities[0];
                        PDJS.JS.ProspectDirector.Modules.Reports.ReportSelectorDialog.Dialog.show({
                            params: {
                                entityId: entity.id,
                                entityTypeId: entity.typeId
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/reports",
                            tooltip: "Reports...",
                            label: "Reports...",
                            icon: "document_text.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                ContentList.ReportsCommand = ReportsCommand;
            })(ContentList = Explorer.ContentList || (Explorer.ContentList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class ContentPageHeader extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get entityName() {
                    return this.state.get("entityName");
                }
                get entityNameNode() {
                    return this.node.find("span[role=entity-name]");
                }
                get folderIcon() {
                    return this.state.get("folderIcon");
                }
                get folderName() {
                    return this.state.get("folderName");
                }
                get actionsNode() {
                    return this.node.find("div[role=actions]");
                }
                template() {
                    return `
            <div class="-pdjs-explorer-content-header">
                <div>
                    <img src="${Jade.IconSet.get("pd").resolve(this.folderIcon, Jade.IconSetSizeSpecificDirectory.x32)}"/>
                </div>
                <div>${this.folderName}</div>
                <div>
                    <span role="entity-name">
                        ${this.entityName}
                    </span>
                </div>
                <div role="actions">
                    
                </div>
            </div>
            `;
                }
                onActivate(e) {
                    super.onActivate(e);
                    Hub.Explorer.EventsHub.entityChangedSubscribe((e) => {
                        let changes = e.find(i => i.id === this.entityId);
                        if (changes) {
                            this.entityNameNode.text(changes.name);
                        }
                    });
                }
            }
            Explorer.ContentPageHeader = ContentPageHeader;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var Canvas;
            (function (Canvas) {
                class ContentPageMenu extends PDJS.Shared.UI.Controls.ContextMenuSegment {
                    get canvasId() {
                        return this.m_canvasId;
                    }
                    set canvasId(value) {
                        this.m_canvasId = value;
                    }
                    get entityTypeId() {
                        return this.m_entityTypeId;
                    }
                    set entityTypeId(value) {
                        this.m_entityTypeId = value;
                    }
                    onMenuShow(e) {
                        this.canvasId = e.data.canvasId;
                        this.entityTypeId = e.data.entityTypeId;
                    }
                    onAddMenuItems(e) {
                        super.onAddMenuItems(e);
                        e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                            value: "open-entity-type",
                            label: "Open Entity Type",
                            select: (item) => {
                                window.open(PDJS.Manage.ManageUrl.createEntityTypeUrl(this.entityTypeId), PDJS.Manage.ManageUrl.target);
                            }
                        }));
                        e.addSeparator({
                            show: (e) => {
                                e.item.visible = !Jade.String.isNullOrWhiteSpace(this.canvasId);
                            }
                        });
                        e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                            value: "open-canvas",
                            label: "Open Canvas",
                            show: (e) => {
                                e.item.visible = !Jade.String.isNullOrWhiteSpace(this.canvasId);
                            },
                            select: (item) => {
                                window.open(PDJS.Manage.ManageUrl.createCanvasUrl(this.canvasId), PDJS.Manage.ManageUrl.target);
                            }
                        }));
                    }
                }
                Canvas.ContentPageMenu = ContentPageMenu;
                class ContextMenuTextItem extends PDJS.Shared.UI.Controls.ContextMenuItemBase {
                    constructor(options) {
                        super(options);
                    }
                    get label() {
                        return this.state.get("label", true);
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    template() {
                        return `<div class="-pdjs-context-menu-item-header">${this.label}</div>`;
                    }
                }
            })(Canvas = Explorer.Canvas || (Explorer.Canvas = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var CustomUrl;
            (function (CustomUrl) {
                class CustomUrlPage extends Explorer.ContentPage {
                    get url() {
                        return this.getProperty("url");
                    }
                    get hideNavigation() {
                        return this.getProperty("hideNavigation");
                    }
                    onTemplate() {
                        let template = `<iframe src="${this.url}" style="box-sizing:border-box;height:100%;width:100%;border:0;" />`;
                        this.bodyNode.append($(template));
                    }
                    addMenu() {
                        if (this.hideNavigation) {
                            return;
                        }
                        super.addMenu();
                    }
                }
                CustomUrl.CustomUrlPage = CustomUrlPage;
            })(CustomUrl = Explorer.CustomUrl || (Explorer.CustomUrl = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class ContextMenuSegment extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "designable-list/list-items:list-item/edit"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "designable-list/list-items:list-item/copy"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "designable-list/list-items:list-item/delete"
                        }));
                    }
                }
                DesignableList.ContextMenuSegment = ContextMenuSegment;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class DesignableListCommandBase extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            entityId: null,
                            folderId: null,
                            entities: null,
                            enableCreateListData: null,
                            enableDeleteListData: null,
                            enableUpdateListData: null,
                            allowDeleteListData: null,
                            allowUpdateListData: null,
                            extensionId: null,
                            documentId: null,
                            items: null
                        });
                    }
                    get enableCreateListData() {
                        return this.state.get("enableCreateListData");
                    }
                    get enableDeleteListData() {
                        return this.state.get("enableDeleteListData");
                    }
                    get enableUpdateListData() {
                        return this.state.get("enableUpdateListData");
                    }
                    get allowDeleteListData() {
                        return this.state.get("allowDeleteListData");
                    }
                    get allowUpdateListData() {
                        return this.state.get("allowUpdateListData");
                    }
                    get documentId() {
                        return this.state.get("documentId", null);
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get extensionId() {
                        return this.state.get("extensionId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get items() {
                        return this.state.get("items", []);
                    }
                    get itemIds() {
                        return this.items.map(item => item.id);
                    }
                }
                DesignableList.DesignableListCommandBase = DesignableListCommandBase;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class DesignableListDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get okButton() {
                        return this.node.find("button[data-role=ok-button]");
                    }
                    get cancelButton() {
                        return this.node.find("button[data-role=cancel-button]");
                    }
                    get documentId() {
                        return this.state.get("documentId");
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get extensionId() {
                        return this.state.get("extensionId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get rowIds() {
                        return this.state.get("rowIds", []);
                    }
                    get isCopy() {
                        return this.state.get("isCopy");
                    }
                    get viewBox() {
                        return this.state.get("viewBox", null);
                    }
                    set viewBox(value) {
                        this.state.set("viewBox", value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.viewBox = new PDJS.Canvas.Actual.CanvasViewBox({
                            createContext: false,
                            documentId: this.documentId,
                            documentState: null,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: this.rowIds
                        });
                        this.controls.add(this.viewBox);
                        switch (true) {
                            case this.isCopy:
                                this.setWindowOptions({
                                    title: "Duplicate | List Item"
                                });
                                break;
                            case this.rowIds.length > 1:
                                this.setWindowOptions({
                                    title: "Batch Edit | List Items"
                                });
                                break;
                            case this.rowIds.length == 1:
                                this.setWindowOptions({
                                    title: "Edit | List Item"
                                });
                                break;
                            case this.rowIds.length == 0:
                                this.setWindowOptions({
                                    title: "New | List Item"
                                });
                                break;
                        }
                        this.okButton.on("click", $.proxy(this.okButton_onClick, this));
                        this.cancelButton.on("click", $.proxy(this.cancelButton_onClick, this));
                    }
                    okButton_onClick() {
                        let isCreate = (this.rowIds.length == 0 || this.isCopy);
                        PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.pending);
                        if (isCreate) {
                            this.createItem();
                        }
                        else {
                            this.updateItem();
                        }
                    }
                    cancelButton_onClick() {
                        this.close();
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-hub-designable-list-dialog">
                        <div data-controls></div>
                        <div>
                            <button data-role="ok-button" class="-jadeui-dialog-button">OK</button>
                            <button data-role="cancel-button" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            maximized: false,
                            height: 500,
                            width: 680
                        };
                    }
                    onInputReturnKeystroke() {
                        this.okButton.focus();
                        this.okButton_onClick();
                    }
                    createItem() {
                        let service = new PDJS.Services.Canvas.ListItemService();
                        service.create({
                            document: this.viewBox.document.source,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            success: (e) => {
                                this.itemRequestSuccess(e.data);
                            },
                            error: (e) => {
                                this.itemRequestError(e.data);
                            }
                        });
                    }
                    updateItem() {
                        let service = new PDJS.Services.Canvas.ListItemService();
                        service.update({
                            document: this.viewBox.document.source,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: this.rowIds,
                            success: (e) => {
                                this.itemRequestSuccess(e.data);
                            },
                            error: (e) => {
                                this.itemRequestError(e.data);
                            }
                        });
                    }
                    itemRequestSuccess(e) {
                        setTimeout(() => {
                            switch (true) {
                                case e.hasValidationErrors:
                                    PDJS.Canvas.Actual.CanvasRefresh.validate({
                                        validationErrors: e.validationErrors
                                    });
                                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.error);
                                    this.okButton.prop("disabled", false);
                                    break;
                                case e.hasScriptErrors:
                                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.error);
                                    Jade.UI.Dialogs.MultiMessageDialog.open({
                                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                        title: "Request Failure",
                                        header: "The request could not be completed due to the following errors:",
                                        messages: e.scriptErrors,
                                        select: (e) => {
                                            e.close();
                                        }
                                    });
                                    this.okButton.prop("disabled", false);
                                    break;
                                case e.hasScriptAlerts:
                                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.success);
                                    Jade.UI.Dialogs.MultiMessageDialog.open({
                                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Success,
                                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                        title: "Request Success",
                                        header: "The request completed successfully with the following alerts generated by the application:",
                                        messages: e.scriptAlerts,
                                        select: (e2) => {
                                            e2.close();
                                            this.close({
                                                name: "ok",
                                                data: {
                                                    rowId: e.rowId
                                                }
                                            });
                                        }
                                    });
                                default:
                                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.success);
                                    this.close({
                                        name: "ok",
                                        data: {
                                            rowId: e.rowId
                                        }
                                    });
                                    break;
                            }
                        }, 500);
                    }
                    itemRequestError(e) {
                        PDJS.Canvas.Actual.Forms.FormFieldAnimation.stop(null);
                        this.okButton.prop("disabled", false);
                    }
                    static open(options) {
                        return new DesignableListDialog(options);
                    }
                }
                DesignableList.DesignableListDialog = DesignableListDialog;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                let DeisgnableListPageEvent;
                (function (DeisgnableListPageEvent) {
                    DeisgnableListPageEvent["onListItemRefreshRequest"] = "list-item/refresh-request";
                })(DeisgnableListPageEvent = DesignableList.DeisgnableListPageEvent || (DesignableList.DeisgnableListPageEvent = {}));
                class DesignableListPage extends Explorer.ContentPage {
                    constructor(options) {
                        super(options);
                    }
                    get enableCreateListData() {
                        return this.getProperty("enableCreateListData");
                    }
                    get enableDeleteListData() {
                        return this.getProperty("enableDeleteListData");
                    }
                    get enableUpdateListData() {
                        return this.getProperty("enableUpdateListData");
                    }
                    get hideToolbar() {
                        return !this.enableCreateListData
                            && !this.enableDeleteListData
                            && !this.enableUpdateListData;
                    }
                    get contentNode() {
                        return this.bodyNode.children("div[role=content]");
                    }
                    get contentMenuNode() {
                        return this.contentNode.children("div[role=menu]");
                    }
                    get contentGridNode() {
                        return this.contentNode.children("div[role=grid]");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                        this.subscriptions.add(DesignableList.EventsHub.refreshGridSubscribe((e) => {
                            this.m_grid.refresh(e || {});
                        }));
                        this.setCommandState();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (this.hideToolbar) {
                            this.contentMenuNode.remove();
                            this.contentGridNode.css({
                                top: 0
                            });
                        }
                    }
                    onTemplate(e) {
                        super.onTemplate(e);
                        let template = `<div role="content" style="position:absolute;top:10px;right:0;bottom:0;left:0;">
                        <div role="menu" style="position:absolute;top:0;left:10px;right:10px;height:30px;"></div>
                        <div role="grid" style="position:absolute;top:40px;left:10px;right:10px;bottom:10px;"></div>
                    </div>`;
                        this.bodyNode.append($(template));
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.node.find("[role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.id
                                        };
                                    });
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            dblclick: (e) => {
                                this.setCommandState();
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("designable-list/list-items:list-item/edit");
                            },
                            needContext: (e) => {
                                e.filters = this.contextualFilters ? this.contextualFilters : [];
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new DesignableList.ToolbarSegment()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Explorer.DesignableList.ContextMenuSegment",
                                    context: () => {
                                        let ids = _.map(this.m_grid.getSelections().toArray(), (e) => {
                                            return e.id;
                                        });
                                        return {
                                            documentId: this.documentId,
                                            entityId: this.entityId,
                                            extensionId: this.extensionId,
                                            folderId: this.folderId,
                                            items: ids
                                        };
                                    }
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    setCommandState() {
                        if (!this.m_grid) {
                            return;
                        }
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "designable-list/list-items": {
                                allowUpdateListData: this.allowUpdateListData,
                                allowDeleteListData: this.allowDeleteListData,
                                enableCreateListData: this.enableCreateListData,
                                enableDeleteListData: this.enableDeleteListData,
                                enableUpdateListData: this.enableUpdateListData,
                                documentId: this.documentId,
                                entityId: this.entityId,
                                extensionId: this.extensionId,
                                folderId: this.folderId,
                                items: this.m_grid.getSelections().toArray()
                            }
                        }, { force: true });
                    }
                }
                DesignableList.DesignableListPage = DesignableListPage;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                let Events;
                (function (Events) {
                    Events["RefreshGrid"] = "designable-list/refresh-grid";
                })(Events = DesignableList.Events || (DesignableList.Events = {}));
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static refreshGridPublish(args = {}) {
                        this.current.publish(Events.RefreshGrid, args);
                    }
                    static refreshGridSubscribe(handler) {
                        return this.current.subscribe(Events.RefreshGrid, handler);
                    }
                }
                DesignableList.EventsHub = EventsHub;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class ToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "designable-list/list-items:list-item/create"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "designable-list/list-items:list-item/edit"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "designable-list/list-items:list-item/copy"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "designable-list/list-items:list-item/delete"
                        }));
                    }
                }
                DesignableList.ToolbarSegment = ToolbarSegment;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class CopyListItemCommand extends DesignableList.DesignableListCommandBase {
                    onExecute(e) {
                        PDJS.Hub.Explorer.DesignableList.DesignableListDialog.open({
                            documentId: this.documentId,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: this.itemIds,
                            isCopy: true,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    DesignableList.EventsHub.refreshGridPublish({
                                        clear: true,
                                        selections: [e.rowId]
                                    });
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/copy",
                            tooltip: "Duplicate",
                            label: "Duplicate",
                            icon: "copy.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.items.length == 1 && this.allowUpdateListData;
                        this.visible = this.enableCreateListData;
                    }
                }
                DesignableList.CopyListItemCommand = CopyListItemCommand;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class CreateListItemCommand extends DesignableList.DesignableListCommandBase {
                    onExecute(e) {
                        PDJS.Hub.Explorer.DesignableList.DesignableListDialog.open({
                            documentId: this.documentId,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: [],
                            isCopy: false,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    DesignableList.EventsHub.refreshGridPublish({
                                        clear: true,
                                        selections: [e.rowId]
                                    });
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/create",
                            tooltip: "New",
                            label: "New",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.allowUpdateListData;
                        this.visible = this.enableCreateListData;
                    }
                }
                DesignableList.CreateListItemCommand = CreateListItemCommand;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class DeleteListItemCommand extends DesignableList.DesignableListCommandBase {
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete List Items",
                            message: "Delete the selected list items?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.deleteItems();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.items.length > 0 && this.allowDeleteListData;
                        this.visible = this.enableDeleteListData;
                    }
                    deleteItems() {
                        let service = new PDJS.Services.Canvas.ListItemService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Delete List Items",
                            taskStart: (e) => {
                                service.delete({
                                    entityId: this.entityId,
                                    folderId: this.folderId,
                                    rowIds: this.itemIds,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                if (!e.hasErrors && !e.hasWarnings) {
                                    e.close();
                                }
                                DesignableList.EventsHub.refreshGridPublish({ clear: true });
                            }
                        });
                    }
                }
                DesignableList.DeleteListItemCommand = DeleteListItemCommand;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class DesignableListCommands extends Jade.CommandGroup {
                    constructor() {
                        super("designable-list/list-items");
                    }
                    registerCommands(e) {
                        e.commands.add(new DesignableList.CreateListItemCommand({}));
                        e.commands.add(new DesignableList.EditListItemCommand({}));
                        e.commands.add(new DesignableList.CopyListItemCommand({}));
                        e.commands.add(new DesignableList.DeleteListItemCommand({}));
                    }
                }
                DesignableList.DesignableListCommands = DesignableListCommands;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
Jade.Application.onStart(function () {
    Jade.CommandGroups.add(PDJS.Hub.Explorer.DesignableList.DesignableListCommands);
});
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var DesignableList;
            (function (DesignableList) {
                class EditListItemCommand extends DesignableList.DesignableListCommandBase {
                    onExecute(e) {
                        if (!this.allowUpdateListData || !this.enableUpdateListData) {
                            return;
                        }
                        PDJS.Hub.Explorer.DesignableList.DesignableListDialog.open({
                            documentId: this.documentId,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: this.itemIds,
                            isCopy: false,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    DesignableList.EventsHub.refreshGridPublish();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/edit",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.items.length > 0 && this.allowUpdateListData;
                        this.visible = this.enableUpdateListData;
                    }
                }
                DesignableList.EditListItemCommand = EditListItemCommand;
            })(DesignableList = Explorer.DesignableList || (Explorer.DesignableList = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class ContextMenuSegment extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-explorer:file/download"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-explorer:file/open-location"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-explorer:file/open-location-in-new-window"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-explorer:file/properties"
                        }));
                    }
                }
                FileExplorer.ContextMenuSegment = ContextMenuSegment;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class FileExplorerCommand extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            $grid: null,
                            entityId: null
                        });
                    }
                    get items() {
                        return this.grid.getSelections().toArray();
                    }
                    get fileIds() {
                        return this.items.map(item => item.id);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                }
                FileExplorer.FileExplorerCommand = FileExplorerCommand;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class FileExplorerCommands extends Jade.CommandGroup {
                    constructor() {
                        super("explorer/file-explorer");
                    }
                    registerCommands(e) {
                        e.commands.add(new FileExplorer.DownloadCommand({}));
                        e.commands.add(new FileExplorer.PropertiesCommand({}));
                        e.commands.add(new FileExplorer.FileOpenLocationCommand({
                            id: "file/open-location",
                            inNewWindow: false
                        }));
                        e.commands.add(new FileExplorer.FileOpenLocationCommand({
                            id: "file/open-location-in-new-window",
                            inNewWindow: true
                        }));
                    }
                }
                FileExplorer.FileExplorerCommands = FileExplorerCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(FileExplorerCommands);
                });
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                let FileExplorerPageEvent;
                (function (FileExplorerPageEvent) {
                    FileExplorerPageEvent["onGridRefreshRequest"] = "grid/refresh-request";
                })(FileExplorerPageEvent = FileExplorer.FileExplorerPageEvent || (FileExplorer.FileExplorerPageEvent = {}));
                class FileExplorerPage extends Explorer.ContentPage {
                    constructor(options) {
                        super(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.menu_init();
                        this.subscriptions.add(Jade.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .subscribe(FileExplorerPageEvent.onGridRefreshRequest, (e) => {
                            this.m_grid.refresh(e || {});
                        }));
                        this.setCommandState();
                    }
                    onTemplate(e) {
                        super.onTemplate(e);
                        let template = `<div style="position:absolute;top:10px;right:0;bottom:0;left:0;">
                        <div role="menu" style="position:absolute;top:0;left:10px;right:10px;height:30px;"></div>
                        <div role="grid" style="position:absolute;top:40px;left:10px;right:10px;bottom:10px;"></div>
                    </div>`;
                        this.bodyNode.append($(template));
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.node.find("[role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.id,
                                            parentId: item.ObjectParentId,
                                            folderId: item.d0_general_FolderId
                                        };
                                    });
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            dblclick: (e) => {
                                this.setCommandState();
                            },
                            needContext: (e) => {
                                e.filters = this.contextualFilters ? this.contextualFilters : [];
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=menu]",
                            segments: [new FileExplorer.ToolbarSegment()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Explorer.FileExplorer.ContextMenuSegment",
                                    context: () => {
                                        let ids = _.map(this.m_grid.getSelections().toArray(), (e) => {
                                            return e.id;
                                        });
                                        return {
                                            entityId: this.entityId,
                                            folderId: this.folderId,
                                            items: ids
                                        };
                                    }
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    setCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/file-explorer": {
                                entityId: this.entityId,
                                folderId: this.folderId,
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                FileExplorer.FileExplorerPage = FileExplorerPage;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class ToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-explorer:file/download"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-explorer:file/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-explorer:file/open-location"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-explorer:file/open-location-in-new-window"
                        }));
                    }
                }
                FileExplorer.ToolbarSegment = ToolbarSegment;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class DownloadCommand extends FileExplorer.FileExplorerCommand {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            documentId: null,
                            entityId: null,
                            extensionId: null,
                            items: null
                        });
                    }
                    onStateChanged(e) {
                        this.enabled = this.items.length > 0;
                    }
                    onExecute(e) {
                        if (this.items.length === 1) {
                            PDJS.Shared.Downloader.downloadWithProgress({
                                url: `~/file/download/${this.items[0].id}`
                            });
                            return;
                        }
                        if (this.items.length > 1) {
                            this.downloadMultipleFiles();
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/download",
                            tooltip: "Download",
                            label: "Download",
                            icon: "nav_down.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    downloadMultipleFiles() {
                        let service = new PDJS.Services.Files.FileService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Download Files",
                            showDetail: true,
                            taskStart: (args) => {
                                service.downloadMultipleFiles({
                                    ids: this.fileIds,
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e.xhr.responseJSON);
                                        e.errorHandled = true;
                                    }
                                });
                            },
                            taskSuccess: (args) => {
                                service.downloadMultipleFilesZip({
                                    path: args.output.path
                                });
                                args.close();
                            }
                        });
                    }
                }
                FileExplorer.DownloadCommand = DownloadCommand;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class FileOpenLocationCommand extends FileExplorer.FileExplorerCommand {
                    constructor(options = {}) {
                        super(options);
                    }
                    get fileParentId() {
                        return _.first(this.items).parentId;
                    }
                    get fileFolderId() {
                        return _.first(this.items).folderId;
                    }
                    get inNewWindow() {
                        return this.props.get("inNewWindow", false);
                    }
                    onExecute(e) {
                        let url = Jade.Path
                            .resolve(`~/explore/${this.fileParentId}/folder/${this.fileFolderId}`);
                        if (this.inNewWindow) {
                            window.open(url);
                        }
                        else {
                            window.location.href = url;
                        }
                    }
                    onStateChanged(e) {
                        this.enabled = this.items.length == 1;
                    }
                    getDefaultValuesForProps() {
                        let inNew = this.inNewWindow;
                        return {
                            tooltip: inNew ? "Open File Location In New Window" : "Open File Location",
                            label: inNew ? "Open File Location In New Window" : "Open File Location",
                            icon: inNew ? "window_new.png" : "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileExplorer.FileOpenLocationCommand = FileOpenLocationCommand;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileExplorer;
            (function (FileExplorer) {
                class PropertiesCommand extends FileExplorer.FileExplorerCommand {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            entityId: null,
                            folderId: null,
                            items: null
                        });
                    }
                    onStateChanged(e) {
                        this.enabled = this.items.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Entities.FileDialogs.showProperties({
                            fileId: _.first(this.fileIds),
                            onSave: () => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(FileExplorer.FileExplorerPageEvent.onGridRefreshRequest);
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/properties",
                            tooltip: "Properties",
                            label: "Properties",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileExplorer.PropertiesCommand = PropertiesCommand;
            })(FileExplorer = Explorer.FileExplorer || (Explorer.FileExplorer = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ContextMenuSegment extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/download"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/delete"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/change-type"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/move"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/replace"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/file-folder:file/properties"
                        }));
                    }
                }
                FileFolder.ContextMenuSegment = ContextMenuSegment;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                let FileFolderPageEvent;
                (function (FileFolderPageEvent) {
                    FileFolderPageEvent["onGridRefreshRequest"] = "grid/refresh-request";
                })(FileFolderPageEvent = FileFolder.FileFolderPageEvent || (FileFolder.FileFolderPageEvent = {}));
                class FileFolderPage extends Explorer.ContentPage {
                    constructor(options) {
                        super(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.menu_init();
                        this.subscriptions.add(Jade.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .subscribe(FileFolderPageEvent.onGridRefreshRequest, (e) => {
                            this.m_grid.refresh(e || {});
                        }));
                        this.setCommandState();
                    }
                    onTemplate(e) {
                        super.onTemplate(e);
                        let template = `<div style="position:absolute;top:10px;right:0;bottom:0;left:0;">
                        <div role="menu" style="position:absolute;top:0;left:10px;right:10px;height:30px;"></div>
                        <div role="grid" style="position:absolute;top:40px;left:10px;right:10px;bottom:10px;"></div>
                    </div>`;
                        this.bodyNode.append($(template));
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.node.find("[role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.id,
                                        name: e.ObjectName,
                                        extension: e.d0_general_FileExt
                                    };
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            dblclick: (e) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("explorer/file-folder:file/download");
                            },
                            needContext: (e) => {
                                e.filters = this.contextualFilters ? this.contextualFilters : [];
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "[role=menu]",
                            segments: [new FileFolder.ToolbarSegment()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Explorer.FileFolder.ContextMenuSegment",
                                    context: () => {
                                        return {
                                            entityId: this.entityId,
                                            folderId: this.folderId,
                                            files: this.m_grid.getSelections().toArray()
                                        };
                                    }
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    setCommandState() {
                        if (!this.m_grid) {
                            return;
                        }
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/file-folder": {
                                allowAddFiles: this.allowAddFiles,
                                allowReplaceFiles: this.allowReplaceFiles,
                                allowUploads: this.allowUploads,
                                allowEdit: this.allowEdit,
                                allowDeleteFile: this.allowDeleteFile,
                                entityId: this.entityId,
                                folderId: this.folderId,
                                files: this.m_grid.getSelections().toArray()
                            }
                        }, { force: true });
                    }
                }
                FileFolder.FileFolderPage = FileFolderPage;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/upload"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/download"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/change-type"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/move"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-folder:file/replace"
                        }));
                    }
                }
                FileFolder.ToolbarSegment = ToolbarSegment;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileFolderCommandBase extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            entityId: null,
                            folderId: null,
                            files: null,
                            allowReplaceFiles: null,
                            allowUploads: null,
                            allowEdit: null,
                            allowDeleteFile: null,
                            allowAddFiles: null
                        });
                    }
                    get allowDeleteFile() {
                        return this.state.get("allowDeleteFile", false);
                    }
                    get allowEdit() {
                        return this.state.get("allowEdit", false);
                    }
                    get allowAddFiles() {
                        return this.state.get("allowAddFiles", false);
                    }
                    get allowReplaceFiles() {
                        return this.state.get("allowReplaceFiles", false);
                    }
                    get allowUploads() {
                        return this.state.get("allowUploads", false);
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get files() {
                        return this.state.get("files", []);
                    }
                    get ids() {
                        return this.files.map(e => {
                            return e.id;
                        });
                    }
                    get parentContext() {
                        return PDJS.Application.instance.contexts.current.parent;
                    }
                }
                FileFolder.FileFolderCommandBase = FileFolderCommandBase;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileFolderCommands extends Jade.CommandGroup {
                    constructor() {
                        super("explorer/file-folder");
                    }
                    registerCommands(e) {
                        e.commands.add(new FileFolder.DownloadCommand({}));
                        e.commands.add(new FileFolder.PropertiesCommand({}));
                        e.commands.add(new FileFolder.UploadCommand({}));
                        e.commands.add(new FileFolder.ChangeTypeCommand({}));
                        e.commands.add(new FileFolder.MoveCommand({}));
                        e.commands.add(new FileFolder.DeleteCommand({}));
                        e.commands.add(new FileFolder.ReplaceCommand({}));
                    }
                }
                FileFolder.FileFolderCommands = FileFolderCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(FileFolderCommands);
                });
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class StoredFileCommandBase extends Jade.Command {
                    constructor(props) {
                        super(props);
                        this.state.set({
                            files: [],
                            status: FileFolder.UploadStatus.STOPPED
                        });
                        this.state.doNotSerialize.add("files");
                    }
                    get files() {
                        return this.state.get("files", null);
                    }
                    get status() {
                        return this.state.get("status", FileFolder.UploadStatus.STOPPED);
                    }
                    get hasFiles() {
                        return this.files != null && this.files.count > 0;
                    }
                    get hasSelectedFiles() {
                        return this.files.selected.count > 0;
                    }
                }
                FileFolder.StoredFileCommandBase = StoredFileCommandBase;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class StoredFileCommands extends Jade.CommandGroup {
                    constructor() {
                        super("explorer/file-upload");
                    }
                    registerCommands(e) {
                        e.commands.add(new FileFolder.AddFilesCommand({}));
                        e.commands.add(new FileFolder.RemoveFilesCommand({}));
                        e.commands.add(new FileFolder.ClearFilesCommand({}));
                        e.commands.add(new FileFolder.SetFileTypeCommand({}));
                        e.commands.add(new FileFolder.SelectFilesCommand({}));
                    }
                }
                FileFolder.StoredFileCommands = StoredFileCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(StoredFileCommands);
                });
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ChangeTypeCommand extends FileFolder.FileFolderCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.files.length > 0 && this.allowEdit;
                    }
                    onExecute(e) {
                        FileFolder.ChangeDocumentTypeDialog.open({
                            entityId: this.entityId,
                            folderId: this.folderId,
                            fileIds: this.ids,
                            select: {
                                ok: (sender, e) => {
                                    Jade.Application
                                        .instance
                                        .contexts
                                        .current
                                        .events
                                        .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/change-type",
                            tooltip: "Change Type",
                            label: "Change Type",
                            icon: "document_refresh.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileFolder.ChangeTypeCommand = ChangeTypeCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class DeleteCommand extends FileFolder.FileFolderCommandBase {
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Files",
                            message: "Delete the selected files?",
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.deleteFiles();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.files.length > 0 && this.allowDeleteFile;
                    }
                    deleteFiles() {
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Delete Files",
                            showDetail: true,
                            enableClose: false,
                            taskStart: (args) => {
                                PDJS.Ajax.call({
                                    type: "POST",
                                    url: Jade.Path.resolve("~/File/Delete"),
                                    data: {
                                        id: this.ids
                                    },
                                    success: (e) => {
                                        args.startPolling(e);
                                    },
                                    error: (e) => {
                                        args.abort(e.responseJSON);
                                        e.errorHandled = true;
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                let fileCount = this.ids.length;
                                fileCount > 1 ?
                                    PDJS.Shared.MessageStack.instance.success(`Deleted ${fileCount} files.`) :
                                    PDJS.Shared.MessageStack.instance.success(`Deleted ${fileCount} file.`);
                                Explorer.EventsHub.reloadExplorerPublish();
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .parent
                                    .events
                                    .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest, {
                                    clear: true
                                });
                                e.close();
                            }
                        });
                    }
                }
                FileFolder.DeleteCommand = DeleteCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class DownloadCommand extends FileFolder.FileFolderCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.files.length > 0;
                    }
                    onExecute(e) {
                        if (this.files.length == 1) {
                            PDJS.Shared.Downloader.downloadWithProgress({
                                url: `~/file/download/${this.ids[0]}`
                            });
                        }
                        if (this.files.length > 1) {
                            this.downloadMultipleFiles();
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/download",
                            tooltip: "Download",
                            label: "Download",
                            icon: "nav_down.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    downloadMultipleFiles() {
                        let service = new PDJS.Services.Files.FileService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Download Files",
                            showDetail: true,
                            taskStart: (args) => {
                                service.downloadMultipleFiles({
                                    ids: this.ids,
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e.xhr.responseJSON);
                                        e.errorHandled = true;
                                    }
                                });
                            },
                            taskSuccess: (args) => {
                                service.downloadMultipleFilesZip({
                                    path: args.output.path
                                });
                                args.close();
                            }
                        });
                    }
                }
                FileFolder.DownloadCommand = DownloadCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class MoveCommand extends FileFolder.FileFolderCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.files.length > 0 && this.allowAddFiles;
                    }
                    onExecute(e) {
                        FileFolder.FileMoveDialog.open({
                            entityId: this.entityId,
                            fileIds: this.files.map(file => file.id)
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/move",
                            tooltip: "Move",
                            label: "Move",
                            icon: "document_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileFolder.MoveCommand = MoveCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class PropertiesCommand extends FileFolder.FileFolderCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.files.length == 1 && this.allowEdit;
                    }
                    onExecute(e) {
                        PDJS.Entities.FileDialogs.showProperties({
                            fileId: this.ids[0],
                            onSave: () => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest);
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/properties",
                            tooltip: "Properties",
                            label: "Properties",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileFolder.PropertiesCommand = PropertiesCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ReplaceCommand extends FileFolder.FileFolderCommandBase {
                    onStateChanged(e) {
                        this.enabled = this.files.length == 1 && this.allowReplaceFiles;
                    }
                    onExecute(e) {
                        let file = this.files[0];
                        PDJS.Hub.Explorer.FileFolder.FileReplaceDialog.open({
                            fileId: file.id,
                            fileName: file.name,
                            fileExtension: file.extension,
                            select: {
                                ok: (sender, e) => {
                                    Jade.Application
                                        .instance
                                        .contexts
                                        .current
                                        .events
                                        .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/replace",
                            tooltip: "Replace",
                            label: "Replace",
                            icon: "documents_exchange.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                FileFolder.ReplaceCommand = ReplaceCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class UploadCommand extends FileFolder.FileFolderCommandBase {
                    onExecute(e) {
                        FileFolder.FileUploadDialog.open({
                            entityId: this.entityId,
                            folderId: this.folderId,
                            select: {
                                ok: (sender, e) => {
                                    Explorer.EventsHub.reloadExplorerPublish();
                                    Explorer.EventsHub.reloadExplorerTabsPublish();
                                    setTimeout(() => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest);
                                    }, 100);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/upload",
                            tooltip: "Upload",
                            label: "Upload",
                            icon: "nav_up.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.allowAddFiles;
                        this.visible = this.allowUploads;
                    }
                }
                FileFolder.UploadCommand = UploadCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class AddFilesCommand extends FileFolder.StoredFileCommandBase {
                    getDefaultValuesForProps() {
                        return {
                            id: "upload/add-files",
                            tooltip: "Add Files",
                            label: "Add Files...",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                FileFolder.AddFilesCommand = AddFilesCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ClearFilesCommand extends FileFolder.StoredFileCommandBase {
                    getDefaultValuesForProps() {
                        return {
                            id: "upload/clear-files",
                            tooltip: "Clear",
                            label: "Clear",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.hasFiles && this.status == FileFolder.UploadStatus.STOPPED;
                    }
                    onExecute(e) {
                        this.files.clear();
                    }
                }
                FileFolder.ClearFilesCommand = ClearFilesCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class RemoveFilesCommand extends FileFolder.StoredFileCommandBase {
                    onExecute(e) {
                        this.files.selected.each((file) => {
                            this.files.remove(file);
                        });
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.hasSelectedFiles && this.status == FileFolder.UploadStatus.STOPPED;
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "upload/remove-files",
                            tooltip: "Remove",
                            label: "Remove",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                FileFolder.RemoveFilesCommand = RemoveFilesCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class SelectFilesCommand extends FileFolder.StoredFileCommandBase {
                    get allSelected() {
                        return this.files.count === this.files.selected.count;
                    }
                    onExecute(e) {
                        let checked = !this.allSelected;
                        this.files.each((file) => {
                            file.source.selected = checked;
                        });
                        this.setDisplay();
                    }
                    onStateChanged(state) {
                        this.enabled = this.hasFiles && this.status == FileFolder.UploadStatus.STOPPED;
                        this.setDisplay();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "upload/select-files",
                            label: "Select Files",
                            icon: "CHECKBOX.PNG",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    setDisplay() {
                        if (this.allSelected) {
                            this.label = "Deselect All";
                            this.icon = "CHECKBOX_UNCHECKED.PNG";
                        }
                        else {
                            this.label = "Select All";
                            this.icon = "CHECKBOX.PNG";
                        }
                    }
                }
                FileFolder.SelectFilesCommand = SelectFilesCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class SetFileTypeCommand extends FileFolder.StoredFileCommandBase {
                    onStateChanged(state) {
                        this.enabled = this.hasSelectedFiles && this.status == FileFolder.UploadStatus.STOPPED;
                    }
                    onExecute(e) {
                        this.showDocumentTypeSelectionDialog();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "upload/set-file-type",
                            tooltip: "Set Document Type",
                            label: "Set Document Type",
                            icon: "DOCUMENTS_EXCHANGE.PNG",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    showDocumentTypeSelectionDialog() {
                        PDJS.Shared.DocumentTypes.DocumentTypeBrowserDialog.open({
                            filters: [PDJS.Core.Views.DocumentTypeFilter.entityOnly(Hub.Explorer.ExplorerContext.current.entityId)],
                            viewCustomId: PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPE_ASSIGNMENT,
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    let documentType = _.first(e);
                                    this.files.selected.each((file) => {
                                        file.source.documentType = documentType;
                                        file.source.setCanvasDocument();
                                    });
                                }
                            }
                        });
                    }
                }
                FileFolder.SetFileTypeCommand = SetFileTypeCommand;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class StoredFile extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.source.onStateChangeCallback = () => {
                            this.onStateChanged();
                        };
                    }
                    get source() {
                        return this.state.get("$source");
                    }
                    get fileNameNode() {
                        return this.labelNode.children(`div[role=name]`);
                    }
                    get fileSizeNode() {
                        return this.labelNode.children(`div[role=size]`);
                    }
                    get statusNode() {
                        return this.labelNode.children("div[role=status]");
                    }
                    get typeNode() {
                        return this.labelNode.children("div[role=type]");
                    }
                    get typeNameNode() {
                        return this.typeNode.children("div[role=name]");
                    }
                    get labelNode() {
                        return this.node.children("div[role=label]");
                    }
                    get iconNode() {
                        return this.node.children("div[role=icon]");
                    }
                    get editNode() {
                        return this.node.children("div[role=edit]");
                    }
                    get editButtonNode() {
                        return this.editNode.find("button");
                    }
                    get percentNode() {
                        return this.node.children(`div[role=percent]`);
                    }
                    get checkBoxNode() {
                        return this.node.find(`div[role=check] > input[type=checkbox]`);
                    }
                    get progressNode() {
                        return this.node.children(`div[role=progress]`);
                    }
                    get progressBarNode() {
                        return this.progressNode.children(`div[role=bar]`);
                    }
                    get onSelectedCallback() {
                        return this.state.get("onSelected", () => { });
                    }
                    get onChangeCallback() {
                        return this.state.get("onChange", () => { });
                    }
                    onActivate(e) {
                        this.percentNode.hide();
                        this.node.on("click", "input[type=checkbox]", _.bind(this.onCheckboxChecked, this));
                        this.editButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.editButton_onClick, this));
                        this.typeNameNode.on(Jade.BrowserEvent.CLICK, _.bind(this.typeName_onClick, this));
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.updateUI();
                        if (this.state.hasChanged("selected")) {
                            this.onSelectedCallback(this);
                        }
                        this.onChangeCallback(this);
                    }
                    onCheckboxChecked(e) {
                        this.source.selected = this.checkBoxNode.is(":checked");
                    }
                    template() {
                        return `
            <div data-id="${this.ID}" class="-pdjs-file-control">
                <div role="check">
                    <input type="checkbox">
                </div>
                <div role="label">
                    <div role="name">${this.source.name}${this.source.extension}</div>
                    <div role="size"></div>
                    <div role="type">
                        <div role="name">${this.source.documentType.name}</div>
                    </div>
                    <div role="status"></div>
                </div>
                <div role="icon"></div>
                <div role="edit">
                    <button>Edit</button>
                </div>
                <div role="percent"></div>
                <div role="progress">
                    <div role="bar" style="width:0;">&nbsp;</div>
                </div>
            </div>
        `;
                    }
                    updateUI() {
                        this.fileNameNode.text(`${this.source.name}${this.source.extension}`);
                        this.checkBoxNode.prop("checked", this.source.selected);
                        this.typeNameNode.text(this.source.documentType.name);
                        this.fileSizeNode.text(this.source.sizeText);
                        this.iconNode.empty();
                        this.iconNode.append(`<img src="${this.source.statusIconPath}"/>`);
                        this.statusNode.empty();
                        this.statusNode.append(`<span style='color:${this.source.statusColor}'>${this.source.statusText}</span>`);
                        if (this.source.alerts.count > 0) {
                            this.createErrorsToolTip();
                        }
                        else {
                            PDJS.Shared.PopOver.remove(this.iconNode);
                        }
                    }
                    editButton_onClick(e) {
                        FileFolder.FileFormDialog.open({
                            canvasDocument: this.source.canvasDocument,
                            lastCommitResponse: this.source.lastCommitResponse,
                            fileId: this.source.id,
                            select: {
                                ok: (sender, e) => {
                                    this.source.canvasDocument =
                                        new PDJS.Canvas.Core.Documents.DocumentModel(e.document);
                                    this.source.alerts.clear();
                                    this.source.status =
                                        PDJS.Core.Files.FileStatus.VALIDATED;
                                }
                            }
                        });
                    }
                    typeName_onClick(e) {
                        PDJS.Shared.DocumentTypes.DocumentTypeBrowserDialog.open({
                            filters: [PDJS.Core.Views.DocumentTypeFilter.entityOnly(Hub.Explorer.ExplorerContext.current.entityId)],
                            viewCustomId: PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPE_ASSIGNMENT,
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    let documentType = _.first(e);
                                    this.source.documentType = documentType;
                                    this.source.setCanvasDocument();
                                }
                            }
                        });
                    }
                    createErrorsToolTip() {
                        let message = "";
                        this.source.alerts.each((error) => {
                            message += `${error.message}<br/>`;
                        });
                        if (!Jade.String.isNullOrWhiteSpace(message)) {
                            PDJS.Shared.PopOver.validation(this.iconNode, message, {
                                position: {
                                    target: 'topmiddle',
                                    tooltip: 'bottommiddle'
                                }
                            });
                        }
                    }
                }
                FileFolder.StoredFile = StoredFile;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class StoredFileCollectionBase extends Jade.ObservableCollection {
                    constructor(options, callbacks) {
                        super([], callbacks);
                        this.m_controls = options.controls;
                        options.controls.each((control) => {
                            if (control instanceof FileFolder.StoredFile) {
                                this.add(control);
                            }
                        });
                    }
                    get controls() {
                        return this.m_controls;
                    }
                    get selected() {
                        let result = new Jade.ObservableCollection();
                        this.each((file) => {
                            if (file.source.selected) {
                                result.add(file);
                            }
                        });
                        return result;
                    }
                    getById(id) {
                        let result;
                        this.each((file) => {
                            if (file.ID === id) {
                                result = file;
                                return false;
                            }
                        });
                        return result;
                    }
                    getByFormStatus(...status) {
                        let result = new Jade.ObservableCollection();
                        this.each((file) => {
                            if (status.indexOf(file.source.status) > -1) {
                                result.add(file);
                            }
                        });
                        return result;
                    }
                }
                FileFolder.StoredFileCollectionBase = StoredFileCollectionBase;
                class StoredFileCollection extends StoredFileCollectionBase {
                }
                FileFolder.StoredFileCollection = StoredFileCollection;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class StoredFileContainer extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get files() {
                        return this.m_files;
                    }
                    get fileIds() {
                        return this.state.get("fileIds", []);
                    }
                    get onChangeCallback() {
                        return this.state.get("onChange", () => { });
                    }
                    get allFilesCommited() {
                        return this.files.getByFormStatus(PDJS.Core.Files.FileStatus.COMMITTED).count === this.files.count;
                    }
                    get noFilesWithErrors() {
                        return this.files.getByFormStatus(PDJS.Core.Files.FileStatus.ERROR).count === 0;
                    }
                    get noFilesPending() {
                        return this.files.getByFormStatus(PDJS.Core.Files.FileStatus.PENDING).count === 0;
                    }
                    template() {
                        return `
            <div class="-pdjs-file-container">
                <div data-role="grid" data-controls></div>
            </div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.m_files = new FileFolder.UploadFileCollection({
                            controls: this.controls
                        }, {
                            onAfterAdd: (e) => {
                                this.controls.add(e.item);
                            },
                            onAfterRemove: (e) => {
                                this.controls.remove(e.item);
                            },
                            onAfterChange: (e) => {
                                this.onChangeCallback();
                            }
                        });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.populate();
                    }
                    populate() {
                        let fileService = new PDJS.Services.Files.FileService();
                        fileService.getFileInfo({
                            fileIds: this.fileIds,
                            success: (e) => {
                                _.each(e.data, (data) => {
                                    let source = new PDJS.Core.Files.StoredFile({
                                        id: data.id,
                                        name: data.name,
                                        extension: data.extension,
                                        size: data.size,
                                        documentType: data.documentType,
                                        status: PDJS.Core.Files.FileStatus.PENDING
                                    });
                                    this.files.add(new FileFolder.StoredFile({
                                        $source: source,
                                        onChange: (item) => {
                                            this.onChangeCallback();
                                        }
                                    }));
                                    source.setCanvasDocument();
                                });
                            }
                        });
                    }
                }
                FileFolder.StoredFileContainer = StoredFileContainer;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class UploadFile extends FileFolder.StoredFile {
                    get source() {
                        return this.state.get("$source");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.editNode.hide();
                    }
                    updateUI() {
                        super.updateUI();
                        this.progressBarNode.css({
                            width: `${this.source.upload.percent}%`
                        });
                        this.percentNode.text(`${this.source.upload.percent}%`);
                        if (this.source.upload.percent == 100) {
                            this.percentNode.hide();
                            this.editNode.show();
                        }
                        else {
                            this.percentNode.show();
                            this.editNode.hide();
                        }
                    }
                }
                FileFolder.UploadFile = UploadFile;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class UploadFileCollection extends FileFolder.StoredFileCollectionBase {
                    getByUploadId(id) {
                        let result;
                        this.each((file) => {
                            if (file.source.upload.id === id) {
                                result = file;
                                return false;
                            }
                        });
                        return result;
                    }
                    getByUploadStatus(...status) {
                        let result = new Jade.ObservableCollection();
                        this.each((file) => {
                            if (status.indexOf(file.source.upload.status) > -1) {
                                result.add(file);
                            }
                        });
                        return result;
                    }
                }
                FileFolder.UploadFileCollection = UploadFileCollection;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ChangeDocumentTypeDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get fileContainer() {
                        return this.m_fileContainer;
                    }
                    get fileIds() {
                        return this.state.get("fileIds", []);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    template() {
                        return super.template(`
                <div style="position:absolute;inset:0;overflow:hidden;">
                    <div data-role="toolbar" style="position:absolute;top:0;left:0;right:0;height:30px;"></div>
                    <div data-controls style="position:absolute;top:40px;left:0;right:0;bottom:36px;"></div>
                    <div data-role="deck" style="height:26px;position:absolute;left:0;right:0;bottom:0;text-align:right;display:grid;grid-template-columns:auto 225px;">
                        <div data-role="deck-left">
                        </div>
                        <div data-role="deck-right">
                        <button data-command="ok" class="-jadeui-dialog-button">Save</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_fileContainer = new FileFolder.StoredFileContainer({
                            fileIds: this.fileIds,
                            onChange: () => {
                                this.onFileChange();
                            }
                        });
                        this.controls.add(this.m_fileContainer);
                        this.setButtonState();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                            this.close();
                        }, this));
                        this.toolbar_init();
                        this.progressbar_init();
                        setTimeout(() => {
                            this.selectAllDocumentOnOpen();
                        }, 100);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Change Document Type",
                            height: 450,
                            width: 700
                        };
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[data-role=toolbar]",
                            segments: [new FileFolder.ChangeDocumentTypeToolbarSegment()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    progressbar_init() {
                        this.m_progressbar = new PDJS.Shared.UI.Controls.ProgressBar({
                            insertAt: "div[data-role=deck-left]",
                            showMessage: true,
                            backgroundColor: "var(--visiv-theme-progress-success-back-color)",
                            message: "Pending save.",
                            height: "22px"
                        });
                        this.controls.add(this.m_progressbar);
                    }
                    okButton_onClick(e) {
                        this.okButtonNode.prop("disabled", false);
                        let files = this.fileContainer.files;
                        let promises = [];
                        let fileCommits = Promise.resolve();
                        files.each((file, index) => {
                            promises.push(() => this.commitFile(index));
                        });
                        promises.forEach(commit => {
                            fileCommits = fileCommits.then(commit);
                        });
                    }
                    setButtonState() {
                        this.okButtonNode.prop("disabled", !(this.fileContainer.noFilesPending && this.fileContainer.noFilesWithErrors));
                    }
                    checkAllFilesCommittedAndClose() {
                        if (this.fileContainer.allFilesCommited) {
                            this.close({
                                name: "ok",
                                data: []
                            });
                        }
                    }
                    commitFile(fileIndex) {
                        let files = this.fileContainer.files;
                        return new Promise((resolve, reject) => {
                            let file = files.item(fileIndex);
                            file.source.commit(this.entityId, this.folderId, () => {
                                fileIndex += 1;
                                this.m_progressbar.update({
                                    message: `Saving file "${file.source.name}${file.source.extension}"...`,
                                    percent: 100 * (fileIndex / files.count)
                                });
                                if (fileIndex == files.count) {
                                    this.onFileChange();
                                    this.updateProgressBarDisplay();
                                }
                                resolve();
                            });
                        });
                    }
                    updateContext() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/file-upload": {
                                files: this.fileContainer.files
                            }
                        }, { force: true });
                    }
                    onFileChange() {
                        this.updateContext();
                        this.setButtonState();
                        this.checkAllFilesCommittedAndClose();
                    }
                    updateProgressBarDisplay() {
                        let errors = [];
                        this.fileContainer.files.getByFormStatus(PDJS.Core.Files.FileStatus.ERROR).each(file => {
                            errors[errors.length] = `"${file.source.name}${file.source.extension}" has ${file.source.alerts.count} warnings.`;
                        });
                        if (errors.length > 0) {
                            Jade.UI.Dialogs.MultiMessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "Warnings Found",
                                header: `The following files contain warnings, fix the warnings and attempt the save operation again.`,
                                messages: errors,
                                select: (e) => {
                                    e.close();
                                }
                            });
                            this.m_progressbar.update({
                                message: "Pending save.",
                                percent: 0
                            });
                        }
                    }
                    selectAllDocumentOnOpen() {
                        this.updateContext();
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("explorer/file-upload:upload/select-files");
                    }
                    static open(options) {
                        return new ChangeDocumentTypeDialog(options);
                    }
                }
                FileFolder.ChangeDocumentTypeDialog = ChangeDocumentTypeDialog;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class ChangeDocumentTypeToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/remove-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/select-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/set-file-type"
                        }));
                    }
                }
                FileFolder.ChangeDocumentTypeToolbarSegment = ChangeDocumentTypeToolbarSegment;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileFormDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get canvasDocument() {
                        return this.state.get("canvasDocument");
                    }
                    get fileId() {
                        return this.state.get("fileId");
                    }
                    set fileId(value) {
                        this.state.set("fileId", value);
                    }
                    get viewBox() {
                        return this.m_viewBox;
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get lastCommitResponse() {
                        return this.state.get("lastCommitResponse");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-hub-explorer-file-form-dialog">
                    <div data-role="content" data-controls></div>
                    <div data-role="deck">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        this.m_viewBox = new PDJS.Canvas.Actual.CanvasViewBox({
                            documentId: this.canvasDocument.id,
                            documentState: this.canvasDocument.toJSON(),
                            entityId: this.fileId,
                            createContext: false
                        });
                        this.controls.add(this.m_viewBox);
                        setTimeout(() => {
                            this.applyLastCommitResponse();
                        }, 250);
                    }
                    getDefaultOptions() {
                        return {
                            title: "File | Edit",
                            height: 450,
                            width: 680,
                            padding: 0
                        };
                    }
                    okButton_onClick(e) {
                        this.viewBox.document.controls.each((element) => {
                            if (element instanceof PDJS.Canvas.Actual.Forms.FormField) {
                                element.onSubmit();
                            }
                        });
                        let formService = new PDJS.Services.Canvas.Forms.FormService();
                        formService.validate({
                            document: this.viewBox.document.source.toJSON(),
                            success: (e) => {
                                if (e.data.hasValidationErrors) {
                                    this.onValidationErrors(e.data);
                                }
                                else {
                                    this.close({
                                        name: "ok",
                                        data: {
                                            document: this.viewBox.document.source.toJSON()
                                        }
                                    });
                                }
                            }
                        });
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    onValidationErrors(e) {
                        PDJS.Canvas.Actual.CanvasRefresh.validate({
                            validationErrors: e.validationErrors
                        });
                        PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.error);
                    }
                    applyLastCommitResponse() {
                        if (this.lastCommitResponse == null) {
                            return;
                        }
                        if (this.lastCommitResponse.hasValidationErrors) {
                            PDJS.Canvas.Actual.CanvasRefresh.validate({
                                validationErrors: this.lastCommitResponse.validationErrors
                            });
                        }
                    }
                    static open(options) {
                        return new FileFormDialog(options);
                    }
                }
                FileFolder.FileFormDialog = FileFormDialog;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileMoveDialog extends Jade.UI.Dialogs.Dialog {
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get(" folderId");
                    }
                    set folderId(value) {
                        this.state.set(" folderId", value);
                    }
                    get fileIds() {
                        return this.state.get("fileIds");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    template() {
                        return super.template(`<div class="-pdjs-hub-explorer-file-folder-file-move-dialog">
                        <div role="header">Select the destination folder into which the files should be moved.</div>
                        <div role="content" data-controls>
                            <div role="tree"></div>
                        </div>
                        <div role="buttons">
                            <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        this.setOkButtonEnabledState(false);
                        this.tree_init();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Move | Files",
                            width: 400,
                            height: 450
                        };
                    }
                    okButton_onClick(e) {
                        this.executeMove();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    executeMove() {
                        this.close();
                        let service = new PDJS.Services.Files.FileService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Move | Files",
                            autoCloseOnSuccess: true,
                            taskStart: (e) => {
                                service.moveFiles({
                                    fileIds: this.fileIds,
                                    folderId: this.folderId,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            close: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest, {
                                    clear: true
                                });
                                Explorer.EventsHub.reloadExplorerPublish();
                                Explorer.EventsHub.reloadExplorerTabsPublish();
                            }
                        });
                    }
                    tree_init() {
                        this.m_tree = new Explorer.FileMoveTree({
                            insertAt: "div[role=tree]",
                            entityId: this.entityId,
                            folderId: this.folderId,
                            select: (folderId) => {
                                this.folderId = folderId;
                                this.setOkButtonEnabledState(folderId != null);
                            }
                        });
                        this.controls.add(this.m_tree);
                    }
                    setOkButtonEnabledState(enabled) {
                        this.okButtonNode.prop("disabled", !enabled);
                    }
                    static open(options) {
                        return new FileMoveDialog(options);
                    }
                }
                FileFolder.FileMoveDialog = FileMoveDialog;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class FileMoveTree extends PDJS.Shared.UI.Controls.TreeView {
                constructor(options) {
                    super(options);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                get selectCallback() {
                    return this.state.get("select", () => { });
                }
                createModel() {
                    return new PDJS.Core.Explorer.Model({
                        entityId: this.entityId,
                        folderId: this.folderId,
                        includeTabs: true
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.addClass(PDJS.Core.Explorer.CssClass.Model);
                }
                onSelect(e) {
                    super.onSelect(e);
                    let model = e.model;
                    if (!model.isFileFolder) {
                        e.preventDefault();
                    }
                    else {
                        this.selectCallback(model.folderId);
                    }
                }
                onNodeRequestComplete(e) {
                    if (this.folderId == null) {
                        return;
                    }
                    if (e.initialize) {
                        this.select(this.folderId);
                    }
                }
            }
            Explorer.FileMoveTree = FileMoveTree;
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileReplaceDialog extends Jade.UI.Dialogs.Dialog {
                    get fileId() {
                        return this.state.get("fileId");
                    }
                    get fileName() {
                        return this.state.get("fileName");
                    }
                    get fileExtension() {
                        return this.state.get("fileExtension");
                    }
                    get uploadId() {
                        return this.state.get("uploadId");
                    }
                    set uploadId(value) {
                        this.state.set("uploadId", value);
                    }
                    get uploadName() {
                        return this.state.get("uploadName");
                    }
                    set uploadName(value) {
                        this.state.set("uploadName", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-hub-explorer-file-folder-file-replace-dialog">
                        <div role="header">Replace the file <b>${this.getFileFullName()}</b>:</div>
                        <div role="content" data-controls></div>
                        <div role="buttons">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        this.setOkButtonEnabledState(false);
                        this.uploadInput_init();
                    }
                    getDefaultOptions() {
                        return {
                            title: "File | Replace",
                            width: 400,
                            resizable: false
                        };
                    }
                    okButton_onClick(e) {
                        this.executeReplace();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    executeReplace() {
                        let service = new PDJS.Services.Files.FileService();
                        service.replaceFile({
                            fileId: this.fileId,
                            fileName: this.uploadName,
                            uploadId: this.uploadId,
                            success: (e) => {
                                this.showSuccessDialog();
                                this.close({
                                    name: "ok"
                                });
                            }
                        });
                    }
                    uploadInput_init() {
                        this.m_uploadInput = new PDJS.Shared.UI.Controls.UploadInput({
                            onUploadStart: (e) => {
                                this.setOkButtonEnabledState(false);
                            },
                            onUploadComplete: (e) => {
                                this.uploadId = `${e.id}${e.extension}`;
                                this.uploadName = e.name;
                                this.setOkButtonEnabledState(true);
                            }
                        });
                        this.controls.add(this.m_uploadInput);
                    }
                    setOkButtonEnabledState(enabled) {
                        this.okButtonNode.prop("disabled", !enabled);
                    }
                    showSuccessDialog() {
                        PDJS.Shared.MessageStack.instance.success(`The file "${this.getFileFullName()}" has been replaced successfully.`);
                    }
                    getFileFullName() {
                        return `${this.fileName}${this.fileExtension}`;
                    }
                    static open(options) {
                        return new FileReplaceDialog(options);
                    }
                }
                FileFolder.FileReplaceDialog = FileReplaceDialog;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileUploadDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get upload() {
                        return this.m_upload;
                    }
                    get entityId() {
                        return this.state.get("entityId");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get defaultDocumentType() {
                        return this.state.get("defaultDocumentType", {});
                    }
                    set defaultDocumentType(value) {
                        this.state.set("defaultDocumentType", value);
                    }
                    get saveButtonNode() {
                        return this.node.find("button[data-command=save]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get uploadButtonNode() {
                        return this.node.find("button[data-command=upload]");
                    }
                    get selectButtonNode() {
                        return this.node.find("div[data-role=toolbar] button:first");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.subscriptions.add(Explorer.Events.FileChangeEvent, (e) => {
                            this.onFileChange(e);
                        });
                        this.saveButtonNode.hide();
                        this.uploadButtonNode.prop("disabled", true);
                        this.saveButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.saveButton_onClick, this));
                        this.uploadButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                            this.upload.startUpload();
                        }, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                            this.close();
                        }, this));
                        this.toolbar_init();
                        this.progressbar_init();
                        PDJS.Ajax.call({
                            url: Jade.Path.resolve("~/Hub/FileFolder/FileUploadDialog"),
                            data: {
                                entityId: this.entityId,
                                folderId: this.folderId
                            },
                            success: (e) => {
                                this.defaultDocumentType = e;
                                setTimeout(() => {
                                    this.upload_init();
                                }, 200);
                            },
                            error: () => {
                                this.close();
                            }
                        });
                    }
                    close(options) {
                        if (this.upload != null) {
                            this.upload.stopUpload();
                        }
                        super.close(options);
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-hub-explorer-file-upload-dialog">
                    <div data-role="toolbar"></div>
                    <div data-role="upload"></div>
                    <div data-role="deck">
                        <div data-role="deck-left">
                        </div>
                        <div data-role="deck-right">
                            <button data-command="save" class="-jadeui-dialog-button">Save</button>
                            <button data-command="upload" class="-jadeui-dialog-button">Upload</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "File | Upload",
                            height: 450,
                            width: 700
                        };
                    }
                    upload_init() {
                        this.m_upload = new FileFolder.Upload({
                            insertAt: "[data-role=upload]",
                            defaultDocumentType: this.defaultDocumentType,
                            containerNode: this.node,
                            selectButtonNode: this.selectButtonNode,
                            onQueueChanged: () => {
                                this.setUploadButtonDisplay();
                                this.setSaveButtonDisplay();
                            },
                            onBeforeUpload: () => {
                                this.setUploadButtonDisplay();
                                this.setSaveButtonDisplay();
                            },
                            onUploadProgress: (e) => {
                                this.m_progressbar.update({
                                    message: `Uploading file "${e.source.name}${e.source.extension}" ...`,
                                    percent: this.m_upload.totalPercent
                                });
                            },
                            onUploadComplete: (e) => {
                                this.m_progressbar.update({
                                    message: `Pending save.`,
                                    percent: 0
                                });
                            },
                            onFileRemoved: (e) => {
                                this.setUploadButtonDisplay();
                                this.setSaveButtonDisplay();
                            },
                            onFilesAdded: (e) => {
                                this.setUploadButtonDisplay();
                                this.setSaveButtonDisplay();
                                this.m_progressbar.update({
                                    message: `Pending upload.`,
                                    percent: 0
                                });
                            },
                            onError: (e) => {
                                Jade.UI.Dialogs.MessageDialog.open({
                                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                    allowClose: true,
                                    message: e.message,
                                    select: (e) => {
                                        e.close();
                                    }
                                });
                            }
                        });
                        this.controls.add(this.upload);
                        this.updateCommandState();
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[data-role=toolbar]",
                            segments: [new FileFolder.FileUploadToolbarSegment()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    progressbar_init() {
                        this.m_progressbar = new PDJS.Shared.UI.Controls.ProgressBar({
                            insertAt: "div[data-role=deck-left]",
                            showMessage: true,
                            backgroundColor: "var(--visiv-theme-progress-success-back-color)",
                            message: "Pending add files.",
                            height: "22px"
                        });
                        this.controls.add(this.m_progressbar);
                    }
                    setUploadButtonDisplay() {
                        let visible = this.upload.files.getByUploadStatus(plupload.FileStatus.QUEUED, plupload.FileStatus.UPLOADING).count > 0 || this.upload.files.count === 0;
                        let enabled = this.upload.files.getByUploadStatus(plupload.FileStatus.QUEUED).count > 0
                            && this.upload.uploadStatus === FileFolder.UploadStatus.STOPPED;
                        if (visible) {
                            this.uploadButtonNode.show();
                        }
                        else {
                            this.uploadButtonNode.hide();
                        }
                        this.uploadButtonNode.prop("disabled", !enabled);
                    }
                    setSaveButtonDisplay() {
                        let visible = this.upload.files.getByUploadStatus(plupload.FileStatus.DONE).count === this.upload.files.count
                            && this.upload.files.count > 0;
                        let enabled = this.upload.files.getByFormStatus(PDJS.Core.Files.FileStatus.VALIDATED, PDJS.Core.Files.FileStatus.COMMITTED).count == this.upload.files.count;
                        if (visible) {
                            this.saveButtonNode.show();
                        }
                        else {
                            this.saveButtonNode.hide();
                        }
                        this.saveButtonNode.prop("disabled", !enabled);
                    }
                    onFileChange(file) {
                        this.updateCommandState();
                        this.setUploadButtonDisplay();
                        this.setSaveButtonDisplay();
                        this.checkAllFilesCommittedAndClose(file);
                    }
                    saveButton_onClick(e) {
                        let promises = [];
                        let fileCommits = Promise.resolve();
                        this.upload.files.each((file, index) => {
                            promises.push(() => this.commitFile(index));
                        });
                        promises.forEach(commit => {
                            fileCommits = fileCommits.then(commit);
                        });
                    }
                    checkAllFilesCommittedAndClose(file) {
                        if (file.source.status === PDJS.Core.Files.FileStatus.COMMITTED) {
                            let commitedFileCount = this.upload.files.getByFormStatus(PDJS.Core.Files.FileStatus.COMMITTED).count;
                            if (commitedFileCount == this.upload.files.count) {
                                this.close({
                                    name: "ok"
                                });
                            }
                        }
                    }
                    commitFile(fileIndex) {
                        let fileCount = this.upload.files.count;
                        return new Promise((resolve, reject) => {
                            let file = this.upload.files.item(fileIndex);
                            file.source.commit(this.entityId, this.folderId, () => {
                                fileIndex += 1;
                                this.m_progressbar.update({
                                    message: `Saving file "${file.source.name}${file.source.extension}"...`,
                                    percent: 100 * (fileIndex / fileCount)
                                });
                                if (fileIndex == fileCount) {
                                    this.onFileChange(file);
                                    this.updateProgressBarDisplay();
                                }
                                resolve();
                            });
                        });
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/file-upload": {
                                files: this.upload.files,
                                status: this.upload.uploadStatus
                            }
                        }, { force: true });
                    }
                    updateProgressBarDisplay() {
                        let errors = [];
                        this.upload.files.getByFormStatus(PDJS.Core.Files.FileStatus.ERROR).each(file => {
                            errors[errors.length] = `"${file.source.name}${file.source.extension}" has ${file.source.alerts.count} warnings.`;
                        });
                        if (errors.length > 0) {
                            Jade.UI.Dialogs.MultiMessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "Warnings Found",
                                header: `The following files contain warnings, fix the warnings and attempt the save operation again.`,
                                messages: errors,
                                select: (e) => {
                                    e.close();
                                }
                            });
                            this.m_progressbar.update({
                                message: "Pending save.",
                                percent: 0
                            });
                        }
                    }
                    static open(options) {
                        return new FileUploadDialog(options);
                    }
                }
                FileFolder.FileUploadDialog = FileUploadDialog;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class FileUploadToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/add-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/remove-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/clear-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/select-files"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/file-upload:upload/set-file-type"
                        }));
                    }
                }
                FileFolder.FileUploadToolbarSegment = FileUploadToolbarSegment;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                let UploadStatus;
                (function (UploadStatus) {
                    UploadStatus[UploadStatus["STOPPED"] = 1] = "STOPPED";
                    UploadStatus[UploadStatus["STARTED"] = 2] = "STARTED";
                })(UploadStatus = FileFolder.UploadStatus || (FileFolder.UploadStatus = {}));
                class Upload extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get selectButtonNode() {
                        return this.state.get("selectButtonNode");
                    }
                    get containerNode() {
                        return this.state.get("containerNode");
                    }
                    get defaultDocumentType() {
                        return this.state.get("defaultDocumentType", {});
                    }
                    get uploader() {
                        return this.state.get("uploader");
                    }
                    set uploader(value) {
                        this.state.set("uploader", value);
                    }
                    get uploadStatus() {
                        return this.m_status;
                    }
                    get onFileUploadedCallback() {
                        return this.state.get("onFileUploaded", () => { });
                    }
                    get onFilesAddedCallback() {
                        return this.state.get("onFilesAdded", () => { });
                    }
                    get onFilesChangedCallback() {
                        return this.state.get("onFilesChanged", () => { });
                    }
                    get onBeforeUploadCallback() {
                        return this.state.get("onBeforeUpload", () => { });
                    }
                    get onFileRemovedCallback() {
                        return this.state.get("onFileRemoved", () => { });
                    }
                    get onQueueChangedCallback() {
                        return this.state.get("onQueueChanged", () => { });
                    }
                    get onErrorCallback() {
                        return this.state.get("onError", () => { });
                    }
                    get onUploadCompleteCallback() {
                        return this.state.get("onUploadComplete", () => { });
                    }
                    get onUploadProgressCallback() {
                        return this.state.get("onUploadProgress", () => { });
                    }
                    get files() {
                        return new FileFolder.UploadFileCollection({
                            controls: this.controls
                        }, {
                            onAfterRemove: (e) => {
                                this.uploader.files.removeById(e.item.source.upload.id);
                                this.controls.remove(e.item);
                                this.updateContext();
                                if (this.uploader.files.count === 0) {
                                    this.addEmptyMessage();
                                }
                                this.onFileRemovedCallback(e.item);
                            }
                        });
                    }
                    get totalPercent() {
                        if (this.uploader.uploader != null) {
                            return this.uploader.uploader.total.percent;
                        }
                        return 0;
                    }
                    onActivate(e) {
                        this.uploader_init();
                        this.addEmptyMessage();
                    }
                    uploader_onBeforeUpload(e) {
                        this.m_status = UploadStatus.STARTED;
                        let file = this.files.getByUploadId(e.id);
                        if (file != null) {
                            file.node.get(0).scrollIntoView();
                        }
                        this.onBeforeUploadCallback(file);
                    }
                    uploader_onError(e) {
                        this.m_status = UploadStatus.STOPPED;
                        let file = null;
                        if (e.file != null) {
                            file = this.files.getByUploadId(e.file.id);
                            if (file != null) {
                                file.source.upload.status = e.file.status;
                            }
                        }
                        e = this.getCustomError(e);
                        this.stopUpload();
                        this.onErrorCallback(e);
                    }
                    uploader_onFileUploaded(e) {
                        let file = this.files.getByUploadId(e.id);
                        if (file != null) {
                            file.source.upload.percent = e.percent;
                            file.source.upload.status = e.status;
                        }
                        this.updateContext();
                        this.onFileUploadedCallback(file);
                    }
                    uploader_onFilesAdded(e) {
                        let files = new Jade.Collection();
                        e.each((file) => {
                            let options = {
                                $source: new PDJS.Core.Files.UploadFile({
                                    id: null,
                                    extension: Jade.Path.getFileExtension(file.name),
                                    name: Jade.Path.getFileNameWithoutExtension(file.name),
                                    size: file.size,
                                    status: PDJS.Core.Files.FileStatus.PENDING,
                                    documentType: this.defaultDocumentType,
                                    upload: {
                                        id: file.id,
                                        status: file.status,
                                        percent: file.percent
                                    }
                                }),
                                onSelected: (item) => {
                                    this.updateContext();
                                },
                                onChange: (item) => {
                                    Jade.Application.instance.contexts.current.events.publish(Explorer.Events.FileChangeEvent, item);
                                }
                            };
                            let uploadFile = new FileFolder.UploadFile(options);
                            files.add(uploadFile);
                            this.controls.add(uploadFile);
                        });
                        this.files.last().node.get(0).scrollIntoView();
                        this.updateContext();
                        this.onFilesAddedCallback(files);
                    }
                    uploader_onQueueChanged(files) {
                        if (this.uploader.files.count > 0) {
                            this.removeEmptyMessage();
                        }
                        else {
                            this.addEmptyMessage();
                        }
                        this.updateContext();
                        this.onQueueChangedCallback(new Jade.Collection(this.files.toArray()));
                    }
                    uploader_onUploadComplete(files) {
                        this.m_status = UploadStatus.STOPPED;
                        let uploadFiles = new Jade.Collection();
                        let ids = [];
                        files.each((file) => {
                            let uploadFile = this.files.getByUploadId(file.id);
                            if (uploadFile != null) {
                                ids[ids.length] = uploadFile.ID;
                                uploadFiles.add(uploadFile);
                            }
                        });
                        this.updateContext();
                        this.onUploadCompleteCallback(uploadFiles);
                        this.getFormData(ids);
                    }
                    uploader_onUploadProgress(e) {
                        this.m_status = UploadStatus.STARTED;
                        let file = this.files.getByUploadId(e.id);
                        if (file != null) {
                            file.source.upload.percent = e.percent;
                            file.source.upload.status = e.status;
                            this.onUploadProgressCallback(file);
                        }
                        this.updateContext();
                    }
                    template() {
                        return `
            <div class="-pdjs-upload-control">
                <div data-role="grid" data-controls></div>    
                <div data-role="uploader"></div>
            </div>`;
                    }
                    startUpload() {
                        this.uploader.startUpload();
                    }
                    stopUpload() {
                        this.uploader.stopUpload();
                    }
                    uploader_init() {
                        this.uploader = new FileFolder.Uploader({
                            insertAt: "[data-role=uploader]",
                            containerNode: this.containerNode,
                            selectButtonNode: this.selectButtonNode,
                            dropNode: this.node,
                            onBeforeUpload: _.bind(this.uploader_onBeforeUpload, this),
                            onError: _.bind(this.uploader_onError, this),
                            onFileRemoved: () => { },
                            onFilesAdded: _.bind(this.uploader_onFilesAdded, this),
                            onFileUploaded: _.bind(this.uploader_onFileUploaded, this),
                            onQueueChanged: _.bind(this.uploader_onQueueChanged, this),
                            onUploadComplete: _.bind(this.uploader_onUploadComplete, this),
                            onUploadProgress: _.bind(this.uploader_onUploadProgress, this)
                        });
                        this.controls.add(this.uploader);
                        this.m_status = UploadStatus.STOPPED;
                    }
                    addEmptyMessage() {
                        if (this.getMessage() == null) {
                            this.controls.add(new FileFolder.UploadMessage());
                        }
                    }
                    removeEmptyMessage() {
                        let message = this.getMessage();
                        if (message != null) {
                            this.controls.remove(message);
                        }
                    }
                    getMessage() {
                        var result = null;
                        this.controls.each((control) => {
                            if (control instanceof FileFolder.UploadMessage) {
                                result = control;
                                return false;
                            }
                        });
                        return result;
                    }
                    updateContext() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "explorer/file-upload": {
                                files: this.files,
                                status: this.uploadStatus
                            }
                        }, { force: true });
                    }
                    getFormData(ids) {
                        _.each(ids, (id) => {
                            let file = this.files.getById(id);
                            if (file != null) {
                                file.source.setCanvasDocument();
                            }
                        });
                    }
                    getCustomError(e) {
                        let result = e;
                        switch (true) {
                            case e.code === -600:
                                result.message = `"${e.file.name}" exceeds the maximum upload size of 2 GB.`;
                                break;
                        }
                        return result;
                    }
                }
                FileFolder.Upload = Upload;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class UploadMessage extends Jade.UI.Control {
                    constructor() {
                        super({});
                    }
                    template() {
                        return `
                <table data-role="message" style="height:100%;width:100%;">
                    <tr>
                        <td style="vertical-align:middle;text-align:center;font-size:13px;">
                            <img src="${Jade.IconSet.get("pd").resolve("DOCUMENT_INTO.PNG", Jade.IconSetSizeSpecificDirectory.x48)}" /><br/><br/>
                            Drag files here or click the Add Files button above.
                        </td>
                    </tr>
                </table>
            `;
                    }
                }
                FileFolder.UploadMessage = UploadMessage;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                let UploaderErrorType;
                (function (UploaderErrorType) {
                    UploaderErrorType[UploaderErrorType["HTTP_ERROR"] = 400] = "HTTP_ERROR";
                    UploaderErrorType[UploaderErrorType["CANNOT_READ_FILE"] = -300] = "CANNOT_READ_FILE";
                    UploaderErrorType[UploaderErrorType["FILE_TOO_LARGE"] = -600] = "FILE_TOO_LARGE";
                    UploaderErrorType[UploaderErrorType["MAX_FILE_COUNT_EXCEEDED"] = 1000] = "MAX_FILE_COUNT_EXCEEDED";
                    UploaderErrorType[UploaderErrorType["CONTAINS_ZERO_BTYE_FILES"] = 1001] = "CONTAINS_ZERO_BTYE_FILES";
                })(UploaderErrorType = FileFolder.UploaderErrorType || (FileFolder.UploaderErrorType = {}));
                class Uploader extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.MAX_FILE_UPLOAD = 50;
                    }
                    get containerNode() {
                        return this.state.get("containerNode");
                    }
                    get dropNode() {
                        return this.state.get("dropNode", null);
                    }
                    get selectButtonNode() {
                        return this.state.get("selectButtonNode");
                    }
                    get uploader() {
                        return this.state.get("uploader");
                    }
                    set uploader(value) {
                        this.state.set("uploader", value);
                    }
                    get uploadState() {
                        return this.uploader.state;
                    }
                    get onFileUploadedCallback() {
                        return this.state.get("onFileUploaded", () => { });
                    }
                    get onBeforeUploadCallback() {
                        return this.state.get("onBeforeUpload", () => { });
                    }
                    get onQueueChangedCallback() {
                        return this.state.get("onQueueChanged", () => { });
                    }
                    get onErrorCallback() {
                        return this.state.get("onError", () => { });
                    }
                    get onUploadProgressCallback() {
                        return this.state.get("onUploadProgress", () => { });
                    }
                    get onUploadCompleteCallback() {
                        return this.state.get("onUploadComplete", () => { });
                    }
                    get onFilesAddedCallback() {
                        return this.state.get("onFilesAdded", () => { });
                    }
                    get onFileRemovedCallback() {
                        return this.state.get("onFileRemoved", () => { });
                    }
                    get files() {
                        return new FileFolder.UploaderFileCollection(this.uploader.files, {
                            onAfterRemove: (e) => {
                                this.uploader.removeFile(e.item);
                                this.onFileRemovedCallback(e.item);
                            }
                        });
                    }
                    onActivate(e) {
                        this.uploader_init();
                    }
                    onBeforeUpload(sender, e) {
                        this.onBeforeUploadCallback(e);
                    }
                    onError(sender, e) {
                        var _a;
                        this.uploader.stop();
                        if (e.file != null) {
                            e.file.status = plupload.FileStatus.FAILED;
                        }
                        let innerError = null;
                        try {
                            innerError = JSON.parse(e.response);
                        }
                        catch (e) { }
                        this.onErrorCallback({
                            code: e.status === 400 ? 400 : e.code,
                            file: e.file,
                            message: ((_a = innerError === null || innerError === void 0 ? void 0 : innerError.error) === null || _a === void 0 ? void 0 : _a.message) || e.message || "Error",
                            response: e.response,
                            innerError: innerError === null || innerError === void 0 ? void 0 : innerError.error
                        });
                    }
                    onFileUploaded(sender, e) {
                        this.onFileUploadedCallback(e);
                    }
                    onFilesAdded(sender, e) {
                        this.onFilesAddedCallback(new Jade.Collection(e));
                    }
                    onQueueChanged(sender, e) {
                        this.onQueueChangedCallback(new Jade.Collection(this.files.toArray()));
                    }
                    onStateChange(sender, e) {
                        if (this.uploader.state == plupload.UploaderState.STARTED) {
                        }
                    }
                    onUploadComplete(sender, e) {
                        this.uploader.stop();
                        this.onUploadCompleteCallback(new Jade.Collection(e));
                    }
                    onUploadProgress(sender, e) {
                        this.onUploadProgressCallback(e);
                    }
                    template() {
                        return `<div style="display:none;"></div>`;
                    }
                    startUpload() {
                        let hasErrors = !this.hasNoZeroLengthFiles() ||
                            !this.isMaxUploadValid();
                        if (hasErrors) {
                            return;
                        }
                        this.uploader.start();
                    }
                    stopUpload() {
                        this.uploader.stop();
                    }
                    uploader_init() {
                        this.uploader = new plupload.Uploader({
                            runtimes: "html5,silverlight,flash,html4",
                            container: this.containerNode.get(0),
                            browse_button: this.selectButtonNode.get(0),
                            drop_element: this.dropNode.get(0),
                            urlstream_upload: true,
                            max_file_size: "2gb",
                            chunk_size: "1024kb",
                            unique_names: true,
                            url: Jade.Path.resolve("~/application/handlers/Uploads.ashx"),
                            flash_swf_url: Jade.Path.resolve("~/areas/shared/assets/external/misc/plupload/moxie.swf"),
                            silverlight_xap_url: Jade.Path.resolve("~/areas/shared/assets/external/misc/plupload/moxie.xap")
                        });
                        this.uploader.bind(plupload.UploaderEvent.FilesAdded, _.bind(this.onFilesAdded, this));
                        this.uploader.bind(plupload.UploaderEvent.UploadProgress, _.bind(this.onUploadProgress, this));
                        this.uploader.bind(plupload.UploaderEvent.UploadComplete, _.bind(this.onUploadComplete, this));
                        this.uploader.bind(plupload.UploaderEvent.QueueChanged, _.bind(this.onQueueChanged, this));
                        this.uploader.bind(plupload.UploaderEvent.FileUploaded, _.bind(this.onFileUploaded, this));
                        this.uploader.bind(plupload.UploaderEvent.BeforeUpload, _.bind(this.onBeforeUpload, this));
                        this.uploader.bind(plupload.UploaderEvent.StateChanged, _.bind(this.onStateChange, this));
                        this.uploader.bind(plupload.UploaderEvent.Error, _.bind(this.onError, this));
                        this.uploader.init();
                        this.uploader.refresh();
                        this.uploader.stop();
                    }
                    isMaxUploadValid() {
                        let queueCount = this.files.getByStatus(plupload.FileStatus.QUEUED).count;
                        if (queueCount > this.MAX_FILE_UPLOAD) {
                            this.onError(this.uploader, {
                                code: UploaderErrorType.MAX_FILE_COUNT_EXCEEDED,
                                message: `There are ${queueCount} files in the upload queue, but no more than ${this.MAX_FILE_UPLOAD} files may be uploaded at one time.\n\n
                                Please remove ${queueCount - this.MAX_FILE_UPLOAD} file(s) and attempt your upload again.`
                            });
                            return false;
                        }
                        return true;
                    }
                    hasNoZeroLengthFiles() {
                        if (this.files.zeroLengthFiles().count > 0) {
                            this.onError(this.uploader, {
                                code: UploaderErrorType.CONTAINS_ZERO_BTYE_FILES
                            });
                            return false;
                        }
                        return true;
                    }
                }
                FileFolder.Uploader = Uploader;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var FileFolder;
            (function (FileFolder) {
                class UploaderFileCollection extends Jade.ObservableCollection {
                    getByStatus(status) {
                        let result = new Jade.ObservableCollection();
                        this.each((file) => {
                            if (file.status === status) {
                                result.add(file);
                            }
                        });
                        return result;
                    }
                    zeroLengthFiles() {
                        let result = new Jade.ObservableCollection();
                        this.each((file) => {
                            if (file.size === 0) {
                                result.add(file);
                            }
                        });
                        return result;
                    }
                    removeById(id) {
                        let target = null;
                        this.each((file) => {
                            if (file.id === id) {
                                target = file;
                                return false;
                            }
                        });
                        if (target != null) {
                            this.remove(target);
                        }
                    }
                }
                FileFolder.UploaderFileCollection = UploaderFileCollection;
            })(FileFolder = Explorer.FileFolder || (Explorer.FileFolder = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            var HtmlTemplate;
            (function (HtmlTemplate) {
                class HtmlTemplatePage extends Explorer.ContentPage {
                    get html() {
                        return this.getProperty("html");
                    }
                    onTemplate() {
                        if (this.html != null) {
                            this.bodyNode.append($(this.html));
                        }
                    }
                }
                HtmlTemplate.HtmlTemplatePage = HtmlTemplatePage;
            })(HtmlTemplate = Explorer.HtmlTemplate || (Explorer.HtmlTemplate = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchBar extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get queryCallback() {
                    return this.state.get("query", () => { });
                }
                get inputNode() {
                    return this.node.find("input");
                }
                get buttonNode() {
                    return this.node.find("button");
                }
                get results() {
                    return this.state.get("results");
                }
                set results(value) {
                    this.state.set("results", value);
                }
                get selectNode() {
                    return this.node.find("select");
                }
                update(results) {
                    this.results = results;
                }
                template() {
                    return `<div class="-pdjs-hub-search-bar">
                        <div role="control">
                            <div role="input">
                                <input type="text"/>
                            </div>
                            <div role="button">
                                <button>Search</button>
                            </div>
                        </div>
                        <div role="gap"></div>
                        <div role="label">Filter:</div>
                        <div role="filter">
                            <select></select>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.buttonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.search();
                    });
                    this.inputNode.on(Jade.BrowserEvent.KEYPRESS, (e) => {
                        if (e.keyCode == Jade.KeyCode.Enter) {
                            this.search();
                        }
                    });
                    this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                        this.search();
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.inputNode.val(this.results.keyword);
                    this.selectNode.empty();
                    this.results.filters.forEach(item => {
                        this.selectNode.append(`<option value="${item.id}">${item.name}</option>`);
                    });
                    if (this.results.filterId != null) {
                        this.selectNode.val(this.results.filterId.toString());
                    }
                }
                search() {
                    let filter = this.selectNode.val();
                    this.queryCallback({
                        term: this.inputNode.val(),
                        filter: filter == "null" ? "" : filter
                    });
                }
            }
            Search.SearchBar = SearchBar;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchContent extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get results() {
                    return this.state.get("results");
                }
                set results(value) {
                    this.state.set("results", value);
                }
                template() {
                    return `<div class="-pdjs-hub-search-content"></div>`;
                }
                update(results) {
                    this.results = results;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.results_init();
                }
                results_init() {
                    this.node.empty();
                    this.results.results.forEach(item => {
                        this.controls.add(new Search.SearchResult({
                            result: item
                        }));
                    });
                }
            }
            Search.SearchContent = SearchContent;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchHeader extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get labelNode() {
                    return this.node.children("div[role=label]");
                }
                get results() {
                    return this.state.get("results");
                }
                set results(value) {
                    this.state.set("results", value);
                }
                update(results) {
                    this.results = results;
                }
                template() {
                    return `<div class="-pdjs-hub-search-header">
                        <div role="label"></div>
                    </div>`;
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.labelNode.text(`${this.results.totalResults} Search Results for "${this.results.keyword}"`);
                }
            }
            Search.SearchHeader = SearchHeader;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchPage extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get results() {
                    return this.state.get("results");
                }
                template() {
                    return `<div class="-pdjs-hub-search-page">
                        <div role="body">
                            <div></div>
                            <div role="searchbar"></div>
                            <div role="header"></div>
                            <div role="content"></div>
                            <div role="pager-foot"></div>
                            <div></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.searchbar_init();
                    this.header_init();
                    this.content_init();
                    this.pager_init();
                }
                searchbar_init() {
                    this.m_searchbar = new Search.SearchBar({
                        insertAt: "div[role=searchbar]",
                        results: this.results,
                        query: (e) => {
                            window.location.href = Jade.Path.resolve("~/hub/search", { term: e.term, filter: e.filter });
                        }
                    });
                    this.controls.add(this.m_searchbar);
                }
                header_init() {
                    this.m_header = new Search.SearchHeader({
                        insertAt: "div[role=header]",
                        results: this.results
                    });
                    this.controls.add(this.m_header);
                }
                content_init() {
                    this.m_content = new Search.SearchContent({
                        insertAt: "div[role=content]",
                        results: this.results
                    });
                    this.controls.add(this.m_content);
                }
                pager_init() {
                    this.m_pagerHeader = new Search.SearchPager({
                        insertAt: "div[role=pager-head]",
                        results: this.results
                    });
                    this.controls.add(this.m_pagerHeader);
                    this.m_pagerFooter = new Search.SearchPager({
                        insertAt: "div[role=pager-foot]",
                        results: this.results
                    });
                    this.controls.add(this.m_pagerFooter);
                }
            }
            Search.SearchPage = SearchPage;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchPager extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get results() {
                    return this.state.get("results");
                }
                get settings() {
                    return this.m_settings;
                }
                template() {
                    return `<div class="-pdjs-hub-search-pager"></div>`;
                }
                onInit(e) {
                    super.onInit(e);
                    this.m_settings = new Search.SearchPagerSettings({
                        currentPage: this.results.pageIndex,
                        totalPages: this.results.totalPages
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.render();
                }
                render() {
                    let items = [];
                    if (this.settings.showPageLeft) {
                        items[items.length] = this.generatePageArrow("left");
                    }
                    if (this.settings.showPageLeftEllipsis) {
                        items[items.length] = this.generatePagerButton(1);
                        items[items.length] = this.generatePagerEllipsis();
                    }
                    for (let i = this.settings.startPagerIndexAt; i < this.settings.startPagerIndexAt + this.settings.centerPageCount; i++) {
                        items[items.length] = this.generatePagerButton(i);
                    }
                    if (this.settings.showPageRightEllipsis) {
                        items[items.length] = this.generatePagerEllipsis();
                        items[items.length] = this.generatePagerButton(this.settings.totalPages);
                    }
                    if (this.settings.showPageRight) {
                        items[items.length] = this.generatePageArrow("right");
                    }
                    items.forEach(item => {
                        this.node.append(item);
                    });
                }
                generatePagerButton(pageNumber) {
                    let isCurrentPage = this.results.pageIndex + 1 == pageNumber;
                    let selectedClass = `${isCurrentPage ? " selected" : ""}`;
                    return `<a href="${this.generateUrl(pageNumber - 1)}" class="pager-button${selectedClass}">${pageNumber}</a>`;
                }
                generatePagerEllipsis() {
                    return `<div class="pager-ellipsis">...</div>`;
                }
                generatePageArrow(direction) {
                    let pageNumber = direction == "left" ?
                        this.results.pageIndex - 1 : this.results.pageIndex + 1;
                    return `<a href="${this.generateUrl(pageNumber)}" class="pager-button"><i class="icofont-arrow-${direction}"></i></a>`;
                }
                generateUrl(pageNumber) {
                    return Jade.Path.resolve("~/search", {
                        term: this.results.keyword,
                        filter: this.results.filterId,
                        page: pageNumber
                    });
                }
            }
            Search.SearchPager = SearchPager;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchPagerSettings extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.currentPage = this.currentPage + 1;
                    this.totalPages = this.totalPages;
                }
                get showPageLeft() {
                    return this.currentPage > 1
                        && this.totalPages > this.centerPageMax;
                }
                get showPageLeftEllipsis() {
                    return this.showPageLeft
                        && this.currentPage > this.centerPageMin;
                }
                get showPageRight() {
                    return this.totalPages > this.centerPageMax
                        && this.currentPage < this.totalPages;
                }
                get showPageRightEllipsis() {
                    return this.showPageRight
                        && this.currentPage <= this.totalPages - this.centerPageMin;
                }
                get centerPageCount() {
                    let result = this.centerPageMax;
                    switch (true) {
                        case this.totalPages <= this.centerPageMax:
                            result = this.totalPages;
                            break;
                        case (this.isFirstPageGroup && !this.isLastPageGroup) ||
                            (!this.isFirstPageGroup && this.isLastPageGroup):
                            result = 4;
                            break;
                        case !this.isFirstPageGroup && !this.isLastPageGroup:
                            result = 3;
                            break;
                    }
                    return result;
                }
                get centerPageMin() {
                    return 3;
                }
                get centerPageMax() {
                    return 5;
                }
                get isFirstPageGroup() {
                    return (this.showPageLeft && !this.showPageLeftEllipsis)
                        || this.totalPages <= this.centerPageMax
                        || this.currentPage === 1;
                }
                get isLastPageGroup() {
                    return (this.showPageRight && !this.showPageRightEllipsis)
                        || this.totalPages > this.centerPageMax && this.totalPages - this.currentPage <= 2;
                }
                get currentPage() {
                    return this.state.get("currentPage", 0);
                }
                set currentPage(value) {
                    this.state.set("currentPage", value);
                }
                get totalPages() {
                    return this.state.get("totalPages", 1);
                }
                set totalPages(value) {
                    this.state.set("totalPages", value);
                }
                get startPagerIndexAt() {
                    let result = 1;
                    switch (true) {
                        case this.isFirstPageGroup:
                            result = 1;
                            break;
                        case this.isLastPageGroup:
                            result = (this.totalPages - this.centerPageCount) + 1;
                            break;
                        default:
                            result = this.currentPage - 1;
                            break;
                    }
                    return result < 1 ? 1 : result;
                }
            }
            Search.SearchPagerSettings = SearchPagerSettings;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchRecents extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get queryCallback() {
                    return this.state.get("query", () => { });
                }
                get inputNode() {
                    return this.node.find("input");
                }
                get buttonNode() {
                    return this.node.find("button");
                }
                get results() {
                    return this.state.get("results");
                }
                set results(value) {
                    this.state.set("results", value);
                }
                update(results) {
                    this.results = results;
                }
                template() {
                    return `<div class="-pdjs-hub-search-recents">
                        <div role="input">
                            <input type="text"/>
                        </div>
                        <div role="button">
                            <button>Search</button>
                        </div>
                        <div></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.inputNode.on("mousedown", (e) => {
                        if (e.keyCode == Jade.KeyCode.Enter) {
                        }
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.inputNode.val(this.results.keyword);
                }
            }
            Search.SearchRecents = SearchRecents;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Search;
        (function (Search) {
            class SearchResult extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get result() {
                    return this.state.get("result");
                }
                template() {
                    return `<div class="-pdjs-hub-search-result">
                        <div role="text">
                            <div role="title">
                                <a href="${this.generateUrl()}">${this.result.name}</a>
                            </div>
                            <div role="description">
                                ${this.result.description || "No description provided."}
                            </div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                generateUrl() {
                    if (this.result.isFile) {
                        return Jade.Path.resolve(`~/Explore/${this.result.parentId}/folder/${this.result.folderId}`);
                    }
                    return Jade.Path.resolve(`~/Explore/${this.result.id}`);
                }
            }
            Search.SearchResult = SearchResult;
        })(Search = Hub.Search || (Hub.Search = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            let IEventsHubEvent;
            (function (IEventsHubEvent) {
                IEventsHubEvent["ViewChanged"] = "Views:ViewChanged";
            })(IEventsHubEvent = Views.IEventsHubEvent || (Views.IEventsHubEvent = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static viewChangedPublish(args) {
                    this.global.publish(IEventsHubEvent.ViewChanged, args);
                }
                static viewChangedSubscribe(handler) {
                    return this.global.subscribe(IEventsHubEvent.ViewChanged, handler);
                }
            }
            Views.EventsHub = EventsHub;
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            let TabTypes;
            (function (TabTypes) {
                TabTypes["global"] = "global";
                TabTypes["personal"] = "personal";
                TabTypes["custom"] = "custom";
            })(TabTypes = Views.TabTypes || (Views.TabTypes = {}));
            class ViewPage extends PDJS.Shared.UI.Controls.ContentPage {
                constructor(options) {
                    super(options);
                }
                get header() {
                    return this.m_header;
                }
                get tabStrip() {
                    return this.m_tabstrip;
                }
                get tabType() {
                    return this.state.get("tabTypes");
                }
                set tabType(value) {
                    this.state.set("tabTypes", value);
                }
                get viewStateId() {
                    return this.state.get("data.viewStateId");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.subscriptions.add(Views.EventsHub.viewChangedSubscribe((e) => {
                        this.header.title = e.name;
                        this.header.subTitle = e.description;
                    }));
                }
                onTemplate() {
                    this.node.addClass("-pdjs-hub-viewpage");
                    let template = `<div role="grid"></div>`;
                    this.bodyNode.append(template);
                }
                addTabs(customTab = null) {
                    let tabs = [
                        { icon: "earth_find.png", text: "Global Views", value: "global" },
                        { icon: "user_find.png", text: "Personal Views", value: "personal" }
                    ];
                    if (customTab) {
                        tabs.push(customTab);
                    }
                    tabs.forEach(tab => {
                        tab.selected = tab.value == this.tabType;
                    });
                    this.tabStrip_init(tabs);
                }
                onTabClick(e) {
                    switch (e.item.value) {
                        case TabTypes.global:
                            window.location.href = Jade.Path.resolve("~/Hub/ViewBrowser/Global");
                            break;
                        case TabTypes.personal:
                            window.location.href = Jade.Path.resolve("~/Hub/ViewBrowser/Personal");
                            break;
                    }
                    return null;
                }
                addHead() {
                    this.m_header =
                        new PDJS.Shared.UI.Controls.ContentPageHeader({
                            insertAt: `.${this.headNodeClass}`,
                            icon: null,
                            title: "",
                            subTitle: ""
                        });
                    this.controls.add(this.m_header);
                }
                tabStrip_init(tabs) {
                    this.m_tabstrip =
                        new PDJS.Shared.UI.Controls.TabStrip({
                            insertAt: `.${this.tabsNodeClass}`,
                            tabsData: tabs,
                            tabClick: this.onTabClick
                        });
                    this.controls.add(this.m_tabstrip);
                }
            }
            Views.ViewPage = ViewPage;
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            class ViewPageCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        views: null,
                        $grid: null
                    });
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get views() {
                    return this.grid.getSelections().toArray();
                }
                get ids() {
                    return this.views.map(e => {
                        return e.id;
                    });
                }
            }
            Views.ViewPageCommand = ViewPageCommand;
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPage extends Views.ViewPage {
                    constructor(options) {
                        super(options);
                    }
                    get gridNode() {
                        return this.bodyNode.find("div[role=grid]");
                    }
                    get isOwner() {
                        return this.state.get("data.isOwner");
                    }
                    get viewName() {
                        return this.state.get("data.name");
                    }
                    get viewType() {
                        return this.state.get("data.viewType");
                    }
                    get viewId() {
                        return this.state.get("data.viewId");
                    }
                    get viewDescription() {
                        return this.state.get("data.description", "No Description");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.toolbar_init();
                        this.isBrowserResizeAware = true;
                        this.setHeader();
                        this.subscriptions.add(Views.EventsHub.viewChangedSubscribe((e) => {
                            this.tabStrip.tabs.all.forEach(tab => {
                                if (tab.binding.value == Views.TabTypes.custom) {
                                    tab.text = e.name;
                                }
                            });
                        }));
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addTabs() {
                        this.tabType = Views.TabTypes.custom;
                        super.addTabs({
                            icon: "find.png",
                            text: this.viewName,
                            value: Views.TabTypes.custom
                        });
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.gridNode,
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.id,
                                        name: e.Name,
                                        parentId: e.ObjectParentId,
                                        folderId: e.d0_general_FolderId
                                    };
                                }
                            },
                            change: (e) => {
                                this.updateCommandState();
                            },
                            dblclick: (e) => {
                                switch (this.viewType) {
                                    case "Documents":
                                        this.openFileLocation();
                                        break;
                                    default:
                                        this.openEntity();
                                        break;
                                }
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                        this.updateCommandState();
                    }
                    toolbar_init() {
                        let segments = [];
                        switch (this.viewType) {
                            case "Documents":
                                segments.push(new Browser.BrowserPageFileToolbar());
                                break;
                            default:
                                segments.push(new Browser.BrowserPageEntityToolbar());
                                break;
                        }
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: `.${this.menuNodeClass}`,
                            segments: segments
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    contextMenu_init() {
                        let contextMenuType = "";
                        switch (this.viewType) {
                            case "Documents":
                                contextMenuType = "PDJS.Hub.Views.Browser.BrowserPageFileContextMenu";
                                break;
                            default:
                                contextMenuType = "PDJS.Hub.Views.Browser.BrowserPageEntityContextMenu";
                                break;
                        }
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: contextMenuType
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "views/browser-page": {
                                $grid: this.m_grid,
                                viewId: this.viewId,
                                viewStateId: this.viewStateId,
                                isOwner: this.isOwner
                            }
                        }, { force: true });
                    }
                    openFileLocation() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("views/browser-page:file/open-location");
                    }
                    openEntity() {
                        PDJS.System.Environment.current.profile.preferences.onOpenBehavior == 1 ?
                            this.openEntityInNewWindow() :
                            this.openEntityInCurrentWindow();
                    }
                    openEntityInCurrentWindow() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("views/browser-page:entity/open");
                    }
                    openEntityInNewWindow() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("views/browser-page:entity/open-in-new-window");
                    }
                    setHeader() {
                        this.header.icon = "find.png";
                        this.header.title = this.viewName;
                        this.header.subTitle = this.viewDescription;
                    }
                }
                Browser.BrowserPage = BrowserPage;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageCommand extends Jade.Command {
                    constructor(props = {}) {
                        super(props);
                        this.state.set({
                            selectedItems: null,
                            $grid: null,
                            isOwner: null,
                            viewId: null,
                            viewStateId: null
                        });
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    get isOwner() {
                        return this.state.get("isOwner", false);
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    get selectedItems() {
                        return this.grid.getSelections().toArray();
                    }
                    get selectedItem() {
                        return _.first(this.grid.getSelections().toArray());
                    }
                    get ids() {
                        return this.selectedItems.map(e => {
                            return e.id;
                        });
                    }
                }
                Browser.BrowserPageCommand = BrowserPageCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageCommands extends Jade.CommandGroup {
                    constructor() {
                        super("views/browser-page");
                    }
                    registerCommands(e) {
                        e.commands.add(new Browser.EntityOpenCommand({
                            id: "entity/open",
                            inNewWindow: false
                        }));
                        e.commands.add(new Browser.EntityOpenCommand({
                            id: "entity/open-in-new-window",
                            inNewWindow: true
                        }));
                        e.commands.add(new Browser.EntityPropertiesCommand());
                        e.commands.add(new Browser.FileDownloadCommand());
                        e.commands.add(new Browser.FileOpenLocationCommand({
                            id: "file/open-location",
                            inNewWindow: false
                        }));
                        e.commands.add(new Browser.FileOpenLocationCommand({
                            id: "file/open-location-in-new-window",
                            inNewWindow: true
                        }));
                        e.commands.add(new Browser.FilePropertiesCommand());
                        e.commands.add(new Browser.ViewPropertiesCommand());
                        e.commands.add(new Browser.ViewRevertCommand());
                        e.commands.add(new Browser.ViewSaveAsCommand());
                        e.commands.add(new Browser.ViewSaveCommand());
                    }
                }
                Browser.BrowserPageCommands = BrowserPageCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(BrowserPageCommands);
                });
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageEntityContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:entity/open"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:entity/open-in-new-window"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:entity/properties"
                        }));
                    }
                }
                Browser.BrowserPageEntityContextMenu = BrowserPageEntityContextMenu;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageEntityToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/save"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/save-as"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/revert"
                        }));
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:entity/open"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:entity/open-in-new-window"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:entity/properties"
                        }));
                    }
                }
                Browser.BrowserPageEntityToolbar = BrowserPageEntityToolbar;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageFileContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:file/download"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:file/open-location"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:file/open-location-in-new-window"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/browser-page:file/properties"
                        }));
                    }
                }
                Browser.BrowserPageFileContextMenu = BrowserPageFileContextMenu;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class BrowserPageFileToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/save-as"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:view/revert"
                        }));
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:file/download"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:file/open-location"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:file/open-location-in-new-window"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/browser-page:file/properties"
                        }));
                    }
                }
                Browser.BrowserPageFileToolbar = BrowserPageFileToolbar;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class EntityOpenCommand extends Browser.BrowserPageCommand {
                    constructor(options = {}) {
                        super(options);
                    }
                    get inNewWindow() {
                        return this.props.get("inNewWindow", false);
                    }
                    onExecute(e) {
                        let url = Jade.Path.resolve(`~/explore/${this.selectedItem.id}`);
                        if (this.inNewWindow) {
                            window.open(url);
                        }
                        else {
                            window.location.href = url;
                        }
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length == 1;
                    }
                    getDefaultValuesForProps() {
                        let inNew = this.inNewWindow;
                        return {
                            id: "entity/open",
                            tooltip: inNew ? "Open the selected entity in a new browser window." : "Open the selected entity in this browser window.",
                            label: inNew ? "Open In New Window" : "Open",
                            icon: inNew ? "window_new.png" : "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.EntityOpenCommand = EntityOpenCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class EntityPropertiesCommand extends Browser.BrowserPageCommand {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Entities.EntityDialogs.showProperties({
                            entityId: _.first(this.ids),
                            onSave: (sender, e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/properties",
                            tooltip: "Edit the properties of the selected entity.",
                            label: "Properties",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.EntityPropertiesCommand = EntityPropertiesCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class FileDownloadCommand extends Browser.BrowserPageCommand {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length > 0;
                    }
                    onExecute(e) {
                        if (this.selectedItems.length == 1) {
                            this.downloadSingle();
                        }
                        else {
                            this.downloadMultiple();
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/download",
                            tooltip: "Download",
                            label: "Download",
                            icon: "download.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    downloadSingle() {
                        PDJS.Shared.Downloader.downloadWithProgress({
                            url: `~/file/download/${_.first(this.ids)}`
                        });
                    }
                    downloadMultiple() {
                        let service = new PDJS.Services.Files.FileService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Download Files",
                            showDetail: true,
                            taskStart: (args) => {
                                service.downloadMultipleFiles({
                                    ids: this.ids,
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e.xhr.responseJSON);
                                        e.errorHandled = true;
                                    }
                                });
                            },
                            taskSuccess: (args) => {
                                service.downloadMultipleFilesZip({
                                    path: args.output.path
                                });
                                args.close();
                            }
                        });
                    }
                }
                Browser.FileDownloadCommand = FileDownloadCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class FileOpenLocationCommand extends Browser.BrowserPageCommand {
                    constructor(options = {}) {
                        super(options);
                    }
                    get inNewWindow() {
                        return this.props.get("inNewWindow", false);
                    }
                    onExecute(e) {
                        let url = Jade.Path
                            .resolve(`~/explore/${this.selectedItem.parentId}/folder/${this.selectedItem.folderId}`);
                        if (this.inNewWindow) {
                            window.open(url);
                        }
                        else {
                            window.location.href = url;
                        }
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length == 1;
                    }
                    getDefaultValuesForProps() {
                        let inNew = this.inNewWindow;
                        return {
                            tooltip: inNew ? "Open File Location In New Window" : "Open File Location",
                            label: inNew ? "Open File Location In New Window" : "Open File Location",
                            icon: inNew ? "window_new.png" : "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.FileOpenLocationCommand = FileOpenLocationCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class FilePropertiesCommand extends Browser.BrowserPageCommand {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Entities.FileDialogs.showProperties({
                            fileId: _.first(this.ids),
                            onSave: () => {
                                this.grid.refresh();
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/properties",
                            tooltip: "File Properties",
                            label: "File Properties",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.FilePropertiesCommand = FilePropertiesCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class ViewPropertiesCommand extends Browser.BrowserPageCommand {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "View Properties",
                            args: {
                                properties: {
                                    isSaveAs: false
                                },
                                targetId: this.viewId,
                                targetType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewUIO",
                                arbiterType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    Views.EventsHub.viewChangedPublish(e.target);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/properties",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.ViewPropertiesCommand = ViewPropertiesCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class ViewRevertCommand extends Browser.BrowserPageCommand {
                    onExecute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            title: "Revert View",
                            message: "Undo all your changes and revert this view to the current state of the view from which it was copied?",
                            select: (e) => {
                                e.close();
                                this.revertView();
                            }
                        });
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.visible = this.isOwner;
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/revert",
                            tooltip: "Reverts the view to the current state of the view from which it was copied.",
                            label: "Revert",
                            icon: "reply-all.24px.font",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    revertView() {
                        PDJS.Ajax.call({
                            type: "POST",
                            url: Jade.Path.resolve("~/view/reset", {
                                viewStateId: this.viewStateId
                            }),
                            success: () => {
                                this.grid.build();
                            }
                        });
                    }
                }
                Browser.ViewRevertCommand = ViewRevertCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class ViewSaveAsCommand extends Browser.BrowserPageCommand {
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "View Save As",
                            args: {
                                properties: {
                                    isSaveAs: true
                                },
                                targetId: this.viewId,
                                targetType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewUIO",
                                arbiterType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.grid.refresh({ selections: [e.viewId] });
                                    window.location.href = Jade.Path.resolve(`~/ViewBrowser?viewId=${e.target.viewId}`);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/save-as",
                            tooltip: "Save As",
                            label: "Save As",
                            icon: "save_as.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.ViewSaveAsCommand = ViewSaveAsCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Browser;
            (function (Browser) {
                class ViewSaveCommand extends Browser.BrowserPageCommand {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.isOwner;
                        this.visible = this.isOwner;
                    }
                    onExecute(e) {
                        PDJS.Ajax.call({
                            type: "POST",
                            url: Jade.Path.resolve("~/Shared/View/Commit"),
                            data: {
                                viewStateId: this.viewStateId
                            },
                            success: (e) => {
                                PDJS.Shared
                                    .MessageStack
                                    .instance
                                    .success("View configuration saved successfully.");
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/save",
                            tooltip: "Save",
                            label: "Save",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Browser.ViewSaveCommand = ViewSaveCommand;
            })(Browser = Views.Browser || (Views.Browser = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class GlobalPage extends Views.ViewPage {
                    get gridNode() {
                        return this.bodyNode.find("div[role=grid]");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.toolbar_init();
                        this.isBrowserResizeAware = true;
                        this.setHeader();
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addTabs() {
                        this.tabType = Views.TabTypes.global;
                        super.addTabs();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.gridNode,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.id,
                                            name: item.Name
                                        };
                                    });
                                }
                            },
                            change: (e) => {
                                this.updateCommandState();
                            },
                            dblclick: (e) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("views/global-page:view/open", {
                                    views: e.selections.toArray()
                                });
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: `.${this.menuNodeClass}`,
                            segments: [new Global.GlobalPageToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Views.Global.GlobalPageContextMenu"
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "views/global-page": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                    setHeader() {
                        this.header.icon = "earth_find.png";
                        this.header.title = "Global Views";
                        this.header.subTitle = "A list of global views that have been published to the user community.";
                    }
                }
                Global.GlobalPage = GlobalPage;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class GlobalPageCommands extends Jade.CommandGroup {
                    constructor() {
                        super("views/global-page");
                    }
                    registerCommands(e) {
                        e.commands.add(new Global.SaveAsCommand({}));
                        e.commands.add(new Global.OpenCommand({}));
                        e.commands.add(new Global.OpenInNewWindowCommand({}));
                    }
                }
                Global.GlobalPageCommands = GlobalPageCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(GlobalPageCommands);
                });
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class GlobalPageContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/global-page:view/save-as"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/global-page:view/open"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/global-page:view/open-in-new-window"
                        }));
                    }
                }
                Global.GlobalPageContextMenu = GlobalPageContextMenu;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class GlobalPageToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/global-page:view/save-as"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/global-page:view/open"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/global-page:view/open-in-new-window"
                        }));
                    }
                }
                Global.GlobalPageToolbar = GlobalPageToolbar;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class OpenCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        let view = this.views[0];
                        window.location.href = Jade.Path.resolve(`~/ViewBrowser?viewId=${view.id}`);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open",
                            tooltip: "Open",
                            label: "Open",
                            icon: "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Global.OpenCommand = OpenCommand;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class OpenInNewWindowCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        let view = this.views[0];
                        window.open(Jade.Path.resolve(`~/ViewBrowser?viewId=${view.id}`));
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open-in-new-window",
                            tooltip: "Open In New Window",
                            label: "Open In New Window",
                            icon: "window_new.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Global.OpenInNewWindowCommand = OpenInNewWindowCommand;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Global;
            (function (Global) {
                class SaveAsCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "View Save As",
                            args: {
                                properties: {
                                    isSaveAs: true
                                },
                                targetId: _.first(this.views).id,
                                targetType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewUIO",
                                arbiterType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.grid.refresh({
                                        selections: [e.target.viewId]
                                    });
                                    window.location.href = Jade.Path.resolve(`~/ViewBrowser?viewId=${e.target.viewId}`);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/save-as",
                            tooltip: "Save As...",
                            label: "Save As...",
                            icon: "save_as.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Global.SaveAsCommand = SaveAsCommand;
            })(Global = Views.Global || (Views.Global = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class PersonalPage extends Views.ViewPage {
                    get gridNode() {
                        return this.bodyNode.find("div[role=grid]");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.toolbar_init();
                        this.isBrowserResizeAware = true;
                        this.setHeader();
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addTabs() {
                        this.tabType = Views.TabTypes.personal;
                        super.addTabs();
                        this.tabsNode;
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            pk: "id",
                            container: this.gridNode,
                            viewStateId: this.viewStateId,
                            selectOnRightClick: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.id,
                                        name: e.Name,
                                        categpoy: e.Category
                                    };
                                }
                            },
                            change: (e) => {
                                this.updateCommandState();
                            },
                            dblclick: (e) => {
                                PDJS.System.Environment.current.profile.preferences.onOpenBehavior == 1 ?
                                    this.openInNewWindow(e.selections) :
                                    this.open(e.selections);
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: `.${this.menuNodeClass}`,
                            segments: [new Personal.PersonalPageToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [
                                {
                                    type: "PDJS.Hub.Views.Personal.PersonalPageContextMenu"
                                }
                            ]
                        });
                        this.controls.add(contextMenu);
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "views/personal-page": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                    open(selections) {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("views/personal-page:view/open", {
                            views: selections.toArray()
                        });
                    }
                    openInNewWindow(selections) {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("views/personal-page:view/open-in-new-window", {
                            views: selections.toArray()
                        });
                    }
                    setHeader() {
                        this.header.icon = "user_find.png";
                        this.header.title = "Personal Views";
                        this.header.subTitle = "A list of global views which you have customized and saved for reference.";
                    }
                }
                Personal.PersonalPage = PersonalPage;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class PersonalPageCommands extends Jade.CommandGroup {
                    constructor() {
                        super("views/personal-page");
                    }
                    registerCommands(e) {
                        e.commands.add(new Personal.CategorizeCommand({}));
                        e.commands.add(new Personal.DeleteCommand({}));
                        e.commands.add(new Personal.OpenCommand({}));
                        e.commands.add(new Personal.OpenInNewWindowCommand({}));
                        e.commands.add(new Personal.PropertiesCommand({}));
                        e.commands.add(new Personal.SaveAsCommand({}));
                    }
                }
                Personal.PersonalPageCommands = PersonalPageCommands;
                Jade.Application.onStart(() => {
                    Jade.CommandGroups.add(PersonalPageCommands);
                });
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class PersonalPageContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/save-as"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/properties"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/categorize"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/delete"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/open"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "views/personal-page:view/open-in-new-window"
                        }));
                    }
                }
                Personal.PersonalPageContextMenu = PersonalPageContextMenu;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class PersonalPageToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/save-as"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/properties"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/categorize"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/delete"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/open"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "views/personal-page:view/open-in-new-window"
                        }));
                    }
                }
                Personal.PersonalPageToolbar = PersonalPageToolbar;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class CategorizeCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length > 0;
                    }
                    onExecute(e) {
                        Personal.CategorizeDialog.open({
                            viewIds: this.views.map(item => { return item.id; }),
                            select: {
                                ok: (sender, e) => {
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/categorize",
                            tooltip: "Categorize",
                            label: "Categorize",
                            icon: "index.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Personal.CategorizeCommand = CategorizeCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class DeleteCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length > 0;
                    }
                    onExecute(e) {
                        let message = this.views.length === 1 ?
                            `Delete the "${this.views[0].name}" view?` :
                            `Delete ${this.views.length} the selected views?`;
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            title: "Delete Views",
                            message: message,
                            select: (e) => {
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.deleteViews();
                                }
                                e.close();
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    deleteViews() {
                        PDJS.Ajax.call({
                            type: "POST",
                            url: Jade.Path.resolve("~/hub/viewbrowser/delete"),
                            data: {
                                ids: JSON.stringify(this.views.map(view => { return view.id; }))
                            },
                            success: () => {
                                this.grid.refresh({ clear: true });
                            }
                        });
                    }
                }
                Personal.DeleteCommand = DeleteCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class OpenCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        let view = this.views[0];
                        window.location.href = Jade.Path.resolve(`~/ViewBrowser?viewId=${view.id}`);
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open",
                            tooltip: "Open",
                            label: "Open",
                            icon: "folder_into.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Personal.OpenCommand = OpenCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class OpenInNewWindowCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        let view = this.views[0];
                        window.open(Jade.Path.resolve(`~/ViewBrowser?viewId=${view.id}`));
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open-in-new-window",
                            tooltip: "Open In New Window",
                            label: "Open In New Window",
                            icon: "window_new.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Personal.OpenInNewWindowCommand = OpenInNewWindowCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class PropertiesCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "View Properties",
                            args: {
                                properties: {
                                    isSaveAs: false
                                },
                                targetId: this.views[0].id,
                                targetType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewUIO",
                                arbiterType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/properties",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Personal.PropertiesCommand = PropertiesCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class SaveAsCommand extends Views.ViewPageCommand {
                    onStateChanged(e) {
                        this.enabled = this.views.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "View Save As",
                            args: {
                                properties: {
                                    isSaveAs: true
                                },
                                targetId: _.first(this.views).id,
                                targetType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewUIO",
                                arbiterType: "ProspectDirector.Web.Hub.Modules.Views.PersonalViewArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.grid.refresh({
                                        selections: [e.target.viewId]
                                    });
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/save-as",
                            tooltip: "Save As...",
                            label: "Save As...",
                            icon: "save_as.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                Personal.SaveAsCommand = SaveAsCommand;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Views;
        (function (Views) {
            var Personal;
            (function (Personal) {
                class CategorizeDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get okButton() {
                        return this.node.find("button[data-role=ok-button]");
                    }
                    get cancelButton() {
                        return this.node.find("button[data-role=cancel-button]");
                    }
                    get viewIds() {
                        return this.state.get("viewIds");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.categoryField_init();
                        this.okButton.on("click", $.proxy(this.okButton_onClick, this));
                        this.cancelButton.on("click", $.proxy(this.cancelButton_onClick, this));
                    }
                    okButton_onClick() {
                        this.okAndClose();
                    }
                    cancelButton_onClick() {
                        this.close();
                    }
                    template() {
                        return super.template(`
                <div class="${CanvasJS.Actual.CanvasCss.Element}">
                    <div data-controls style="position:absolute;inset:0;overflow:auto;">
                    </div>
                    <div style="position:absolute;bottom:0;right:0;left:0;height:46px;text-align:right;padding:10px 10px 0 10px;box-sizing:border-box;">
                        <button data-role="ok-button" class="-jadeui-dialog-button">OK</button>
                        <button data-role="cancel-button" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            resizable: false,
                            title: "Categorize",
                            maximized: false,
                            height: 110,
                            width: 400
                        };
                    }
                    setDefaultInputFocus() {
                        this.m_categoryField.focus();
                    }
                    onInputReturnKeystroke() {
                        this.okAndClose();
                    }
                    categoryField_init() {
                        this.m_categoryField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Category",
                            required: false,
                            maxLength: 50
                        });
                        this.controls.add(this.m_categoryField);
                    }
                    commit() {
                        PDJS.Ajax.call({
                            type: "POST",
                            url: Jade.Path.resolve("~/hub/view/categorize"),
                            data: {
                                viewIds: JSON.stringify(this.viewIds),
                                category: this.m_categoryField.value
                            },
                            success: () => {
                                this.close({
                                    name: "ok"
                                });
                            }
                        });
                    }
                    okAndClose() {
                        this.m_categoryField.validate();
                        if (this.m_categoryField.isValid) {
                            this.commit();
                        }
                    }
                    static open(options) {
                        return new CategorizeDialog(options);
                    }
                }
                Personal.CategorizeDialog = CategorizeDialog;
            })(Personal = Views.Personal || (Views.Personal = {}));
        })(Views = Hub.Views || (Hub.Views = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        let CssClass;
        (function (CssClass) {
            CssClass["ActionPane"] = "-pdjs-manage-module-action-pane";
            CssClass["Module"] = "-pdjs-manage-module";
            CssClass["ModuleSection"] = "-pdjs-manage-module-section";
            CssClass["ModuleSectionTitle"] = "-pdjs-manage-module-section-title";
            CssClass["ModuleSectionBody"] = "-pdjs-manage-module-section-body";
            CssClass["NavigationPane"] = "-pdjs-manage-module-navigation-pane";
        })(CssClass = Manage.CssClass || (Manage.CssClass = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        let Events;
        (function (Events) {
            Events["ModuleChangeData"] = "module/change-data";
        })(Events = Manage.Events || (Manage.Events = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class EventsHub extends PDJS.Shared.EventsHubBase {
            static moduleChangeDataPublish(args) {
                let exception = (msg) => { throw msg; };
                (args.newId != null && args.route == null) ?
                    exception("The route property must have a value when newId property has a value.") : null;
                (args.newId == null && args.route != null) ?
                    exception("The newId property must have a value when route property has a value.") : null;
                this.global.publish(Manage.Events.ModuleChangeData, args);
            }
            static moduleChangeDataSubscribe(handler) {
                return this.global.subscribe(Manage.Events.ModuleChangeData, handler);
            }
        }
        Manage.EventsHub = EventsHub;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ManageArea extends Jade.UI.Control {
            get tabStripNode() {
                return this.node.children(".-pdjs-manage-area-tabstrip");
            }
            template() {
                return `<div class="-pdjs-manage-area">
                        <div class="-pdjs-manage-area-menu"></div>
                        <div class="-pdjs-manage-area-tabstrip"></div>
                        <div class="-pdjs-manage-area-content" data-controls></div>
                    </div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                PDJS.Manage.Modules.instance.types.load(() => {
                    this.menu_init();
                    this.tabstrip_init();
                    this.loadDefaults();
                });
                this.subscriptions.add(Manage.ModuleEventsHub.modulesEmptiedSubscribe(() => {
                    window.location.hash = "#";
                    this.addMessage(`No modules are currently loaded.<br/>Click here to open the <a href="#/module/overview">Overview</a>.`);
                }));
            }
            menu_init() {
                this.m_menu = new Manage.ApplicationBar({
                    insertAt: ".-pdjs-area-manage-menu"
                });
            }
            tabstrip_init() {
                this.m_tabstrip = new Manage.ModuleTabStrip({
                    insertAt: ".-pdjs-manage-area-tabstrip",
                    allowScrollButtons: false,
                    menuAnchorAlwaysVisible: true
                });
                this.controls.add(this.m_tabstrip);
                this.subscriptions.add(PDJS.Manage.ModuleEventsHub.moduleCreatedSubscribe((e) => {
                    this.controls.add(e.module);
                    this.m_tabstrip.addTab({
                        $module: e.module
                    });
                    this.removeMessage();
                }));
            }
            loadDefaults() {
                let request = window.location.hash;
                if (Jade.String.isNullOrWhiteSpace(request)) {
                    window.location.hash = "#/module/overview";
                }
                Path.listen();
                if (request) {
                    window.location.hash = request;
                }
            }
            addMessage(text) {
                this.removeMessage();
                let message = new PDJS.Shared.UI.Controls.Message({
                    backgroundColor: "var(--visiv-theme-base-1-back-color)",
                    fontSize: "20px",
                    fill: true,
                    message: text,
                    textColor: "var(--visiv-theme-base-1-text-color)"
                });
                this.controls.add(message);
                message.node.css({
                    position: "absolute",
                    inset: 0
                });
            }
            removeMessage() {
                let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                if (message != null) {
                    this.controls.remove(message);
                }
            }
        }
        Manage.ManageArea = ManageArea;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ManageUrl {
            static get target() {
                return PDJS.System.Settings.current.manageWindowId;
            }
            static createModuleLink(url, label) {
                return (`<a href="${url}" target="${this.target}">${label}</a>`);
            }
            static createCanvasUrl(canvasId) {
                return `${this.createModuleUrl("canvas-editor")}/${canvasId}`;
            }
            static createEntityTypeUrl(entityTypeId) {
                return `${this.createModuleUrl("entity-type")}/${entityTypeId}`;
            }
            static createModuleUrl(route) {
                return Jade.Path.resolve(`~/manage#/module/${route}`);
            }
        }
        Manage.ManageUrl = ManageUrl;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ApplicationBar extends Jade.UI.Control {
            get env() {
                return PDJS.System.Environment.current;
            }
            get titleNode() {
                return this.node.children("div[role=title]");
            }
            get rightDockNode() {
                return this.node.find("div[role=dock-r]");
            }
            get leftDockNode() {
                return this.node.find("div[role=dock-l]");
            }
            template() {
                return `
                <div class="-pdjs-application-bar">
                    <div role="dock-l"></div>
                    <div role="title"></div>
                    <div role="dock-r" data-controls></div>
                </div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.populate();
            }
            populate() {
                this.controls.add(new Manage.ApplicationBarItem({
                    insertAt: "div[role=dock-l]",
                    backgroundColor: "var(--visiv-theme-application-bar-back-color-dark)",
                    icon: "font:fa-grid-3 fa-sharp",
                    url: "#/module/overview"
                }));
                this.titleNode.text(`${this.env.settings.applicationName} - Management`);
                this.controls.add(new Manage.ApplicationBarItem({
                    icon: "font:fa-home fa-sharp",
                    url: Jade.Path.resolve("~/Hub/Home"),
                    target: "_blank"
                }));
                this.controls.add(new Manage.DocumentationSearch({
                    width: 200
                }));
                this.controls.add(new Manage.ApplicationBarItem({
                    backgroundColor: "var(--visiv-theme-application-bar-back-color-dark)",
                    icon: "font: fa-solid fa-user-circle",
                    fontSize: 22,
                    onClick: (e) => {
                        this.m_userPanel.toggle();
                    }
                }));
                this.userPanel_init();
            }
            userPanel_init() {
                this.m_userPanel = new Manage.UserPanel({
                    anchor: this.rightDockNode,
                    top: 41
                });
                this.controls.add(this.m_userPanel);
            }
        }
        Manage.ApplicationBar = ApplicationBar;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ApplicationBarItem extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get backgroundColor() {
                return this.state.get("backgroundColor", null);
            }
            get cssClass() {
                return this.state.get("cssClass", null);
            }
            get onClickCallback() {
                return this.state.get("onClick", () => { });
            }
            get fontSize() {
                return this.state.get("fontSize", 20);
            }
            get icon() {
                return this.state.get("icon");
            }
            get isClickCallback() {
                return this.onClickCallback != null;
            }
            get isUrl() {
                return !Jade.String.isNullOrWhiteSpace(this.url) && this.url != "#";
            }
            get target() {
                return this.state.get("target");
            }
            get url() {
                return this.state.get("url", "#");
            }
            get width() {
                return this.state.get("width", 40);
            }
            template() {
                if (this.url == null) {
                    return `<div><div>`;
                }
                return `<a href="${Jade.Path.resolve(this.url)}"></a>`;
            }
            onActivate(e) {
                super.onActivate(e);
                let icon = Jade.Path.resolve(this.icon);
                this.node.css({
                    position: "relative",
                    display: "inline-block",
                    height: "40px",
                    width: `${this.width}px`,
                    backgroundPosition: "center center",
                    backgroundRepeat: "no-repeat",
                    backgroundColor: this.backgroundColor || "",
                    textDecoration: "none"
                });
                if (this.icon != null) {
                    if (this.icon.startsWith("font:")) {
                        this.node.append(`<i class="${this.icon.substr("font:".length)}" style="font-size:${this.fontSize}px;padding-top:1px;"></i>`);
                        this.node.css({
                            display: "inline-flex",
                            verticalAlign: "top",
                            alignItems: "center",
                            justifyContent: "space-around",
                            color: "var(--visiv-theme-application-bar-icon-color, var(--visiv-theme-application-bar-text-color))"
                        });
                    }
                    else {
                        this.node.css({
                            backgroundImage: `url(${icon})`,
                            color: "var(--visiv-theme-application-bar-text-color)"
                        });
                    }
                }
                if (this.isUrl) {
                    this.node.attr("href", Jade.Path.resolve(this.url));
                }
                if (!this.isUrl && this.isClickCallback) {
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.onClickCallback(e);
                        e.preventDefault();
                        e.cancelBubble = true;
                        e.returnValue = false;
                        return false;
                    });
                }
                if (this.target != null) {
                    this.node.attr("target", this.target);
                }
                if (this.cssClass) {
                    this.node.addClass(this.cssClass);
                }
                this.node.addClass("-pdjs-application-bar-item");
            }
        }
        Manage.ApplicationBarItem = ApplicationBarItem;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class DocumentationSearch extends Manage.ApplicationBarItem {
            get searchBox() {
                return this.m_searchBox;
            }
            template() {
                return `<div class="-pdjs-application-bar-manage-search"></div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                    defaultMaskText: "Search Docs...",
                    onBlur: () => {
                        PDJS.Application.instance.contexts.current.hotkeys.listen();
                    },
                    onFocus: () => {
                        PDJS.Application.instance.contexts.current.hotkeys.stop_listening();
                    },
                    onSearch: (e) => {
                        PDJS.Shared.PopOver.remove(this.searchBox.node);
                        let searchTerm = this.searchBox.textValue;
                        let isValidSearch = searchTerm.length > 1 ||
                            Jade.String.isNullOrWhiteSpace(searchTerm);
                        if (!isValidSearch) {
                            this.searchBox.clear();
                            this.searchBox.maskValue = searchTerm;
                            this.searchBox.textValue = searchTerm;
                            this.searchBox.focus();
                            this.showSearchTermErrorMessage();
                            return;
                        }
                        window.open(Jade.Path.resolve(`https://docs.visiv.com/docs/search?term=${searchTerm}`));
                    }
                });
                this.controls.add(this.searchBox);
            }
            showSearchTermErrorMessage() {
                PDJS.Shared.PopOver.validation(this.node, "<div>Search term must be at least 2 characters in length.</div>");
                PDJS.Shared.PopOver.show(this.searchBox.node);
            }
        }
        Manage.DocumentationSearch = DocumentationSearch;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ThemesList extends PDJS.Shared.UI.Controls.PanelMenuList {
            constructor(options = {}) {
                super();
                this.m_debounce = _.debounce(_.bind(this.onSelectionChange, this), 300);
                this.m_broadcaster = new PDJS.Shared.Themes.ThemeBroadcaster();
                this.m_broadcaster.subscribeSwitchTheme((e) => {
                    if (e.themeScope == PDJS.Services.Themes.ThemeScope.Manage) {
                        this.node.val(e.themeId);
                    }
                });
            }
            onChange(item) {
                this.m_debounce(item);
            }
            onActivate(e) {
                super.onActivate(e);
                this.populateThemes();
                this.subscriptions.add(PDJS.Shared.Themes.EventsHub.themeListChangedSubscribe(() => {
                    this.populateThemes();
                }));
            }
            populateThemes() {
                let service = new PDJS.Services.Themes.ThemeService();
                service.list({
                    success: (e) => {
                        this.clear();
                        let items = [
                            { name: "- Current Hub Theme -", value: "" }
                        ];
                        e.data.forEach(t => {
                            items.push({ name: t.name, value: t.id });
                        });
                        this.populate(items);
                        this.setSelectedTheme(e.data);
                    }
                });
            }
            onSelectionChange(item) {
                PDJS.Shared.Themes.Theme.manage.switchTheme(item.value);
            }
            setSelectedTheme(themes) {
                let themeIsActive = themes.find((theme) => {
                    return theme.id == PDJS.Application.profile.themes.manage;
                }) != null;
                if (!PDJS.Application.profile.themes.isManageUsingHub && themeIsActive) {
                    this.node.val(PDJS.Application.profile.themes.manage);
                }
            }
        }
        Manage.ThemesList = ThemesList;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class UserPanel extends PDJS.Shared.UI.Controls.PanelMenuPopUp {
            constructor(options) {
                super(options);
            }
            get env() {
                return PDJS.System.Environment.current;
            }
            get profile() {
                return PDJS.System.Environment.current.profile;
            }
            show() {
                super.show();
                if (this.m_quickAccess) {
                    this.m_quickAccess.refresh();
                }
                if (this.m_recentItems) {
                    this.m_recentItems.refresh();
                }
            }
            template() {
                let content = `
                <div data-controls></div>
                <div role="brand-and-version"></div>`;
                return super.template(content);
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.css({
                    top: `${this.top}px`
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: this.profile.identity.displayName
                }));
                this.addQuickAccess();
                this.addRecentItems();
                this.addPersonalization();
                this.addThemes();
                this.addHelp();
                this.addLogout();
                this.addVersion();
                this.node.addClass("-pdjs-manage-user-panel");
            }
            onComplete(e) {
                super.onComplete(e);
            }
            addHelp() {
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Help",
                    url: "https://docs.visiv.com",
                    largeText: true,
                    target: "_blank"
                }));
                if (this.env.settings.isLocalAuthMode) {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                }
            }
            addLogout() {
                if (!this.env.settings.isLocalAuthMode) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Sign Out",
                    url: Jade.Path.resolve("~/Shared/Account/Logout"),
                    largeText: true
                }));
            }
            addPersonalization() {
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Personalization"
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Preferences",
                    click: (e) => {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "Preferences",
                            args: {
                                targetType: "ProspectDirector.Web.Shared.Modules.Personalization.PreferencesUIO",
                                arbiterType: "ProspectDirector.Web.Shared.Modules.Personalization.PreferencesArbiter"
                            },
                            select: {
                                "ok": (sender, e) => {
                                    PDJS.System.Environment.current.profile.preferences.update(e.target);
                                    PDJS.System.Environment.setScrollBarSize();
                                }
                            }
                        });
                        this.hide();
                    }
                }));
            }
            addQuickAccess() {
                this.m_quickAccess = new Manage.QuickAccessList();
                this.controls.add(this.m_quickAccess);
                return this.m_quickAccess;
            }
            addRecentItems() {
                this.m_recentItems = new Manage.RecentItemsList();
                this.controls.add(this.m_recentItems);
                return this.m_recentItems;
            }
            addThemes() {
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Theme"
                }));
                this.controls.add(new Manage.ThemesList());
            }
            addVersion() {
                this.controls.add(new PDJS.Shared.BrandAndVersion({
                    insertAt: "[role=brand-and-version]"
                }));
            }
        }
        Manage.UserPanel = UserPanel;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class QuickAccessList extends Jade.UI.Control {
            constructor(options = {}) {
                super(options);
            }
            refresh() {
                this.populate();
            }
            onActivate(e) {
                super.onActivate(e);
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Quick Access"
                }));
                this.list_init();
                this.populate();
                this.node.css({
                    marginBottom: "10px"
                });
            }
            list_init() {
                this.m_list =
                    new PDJS.Shared.UI.Controls.ListView({
                        noItemsMessage: "No items have been added to quick access.",
                        allowRemove: true,
                        binding: {
                            label: "name",
                            value: "route"
                        },
                        data: [],
                        height: "315px",
                        change: (e) => {
                            if (e.count > 0) {
                                window.location.hash = e.first().value;
                            }
                        },
                        remove: (item) => {
                            this.removeItem(item.value);
                        }
                    });
                this.controls.add(this.m_list);
            }
            populate() {
                let service = new PDJS.Services.Personalization.QuickAccessService();
                service.list({
                    success: (e) => {
                        this.m_list.removeAll();
                        e.data.forEach(item => {
                            this.m_list.addItem(_.extend({
                                icon: "star.png",
                            }, item));
                        });
                    }
                });
            }
            removeItem(route) {
                let service = new PDJS.Services.Personalization.QuickAccessService();
                service.remove({
                    routes: [route]
                });
            }
        }
        Manage.QuickAccessList = QuickAccessList;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class RecentItemsList extends Jade.UI.Control {
            constructor(options = {}) {
                super(options);
            }
            get visible() {
                return !!(this.node.get(0).offsetWidth ||
                    this.node.get(0).offsetHeight ||
                    this.node.get(0).getClientRects().length);
            }
            refresh() {
                this.populate();
            }
            onActivate(e) {
                super.onActivate(e);
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Recent Items"
                }));
                this.list_init();
                this.populate();
                this.node.css({
                    marginBottom: "10px"
                });
                this.subscriptions.add(Manage.ModuleEventsHub.moduleFocusedSubscribe(e => {
                    if (this.visible) {
                        this.refresh();
                    }
                }));
                this.subscriptions.add(Manage.ModuleEventsHub.modulesLoadErrorSubscribe(e => {
                    if (this.visible) {
                        this.refresh();
                    }
                }));
            }
            list_init() {
                this.m_list =
                    new PDJS.Shared.UI.Controls.ListView({
                        noItemsMessage: "No items have been recently viewed.",
                        allowRemove: false,
                        binding: {
                            icon: null,
                            label: "name",
                            value: "route"
                        },
                        data: [],
                        height: "160px",
                        change: (e) => {
                            if (e.count > 0) {
                                window.location.hash = e.first().value;
                            }
                        }
                    });
                this.controls.add(this.m_list);
            }
            populate() {
                let service = new PDJS.Services.Personalization.RecentItemsService();
                service.list({
                    success: (e) => {
                        this.m_list.removeAll();
                        e.data.forEach(item => {
                            this.m_list.addItem(item);
                        });
                    }
                });
            }
        }
        Manage.RecentItemsList = RecentItemsList;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class Module extends Jade.UI.Control {
            constructor(options) {
                super(options);
                this.createContext();
            }
            get events() {
                this.ensureEvents();
                return this.m_events;
            }
            get subscribe() {
                return this.events;
            }
            get directives() {
                return this.m_directives;
            }
            get settings() {
                this.ensureSettings();
                return this.m_settings;
            }
            get focused() {
                return Manage.Modules.instance.current === this;
            }
            get monitor() {
                this.ensureMonitor();
                return this.m_monitor;
            }
            get status() {
                return this.m_status || "ok";
            }
            set status(value) {
                this.m_status = value;
            }
            blur() {
                let args = new Manage.ModuleEventArgs();
                this.events.blur();
                this.onModuleBlur(args);
                if (!args.cancelled && this.focused) {
                    Manage.Modules.instance.current = null;
                    this.node.css({ display: "none" });
                    this.events.blurred();
                }
            }
            commit() {
                let args = new Manage.ModuleCommitEventArgs();
                this.events.commit();
                this.onModuleCommit(args);
                args.addStep(() => {
                    return new Promise(() => {
                        if (!args.cancelled) {
                            this.onModuleCommitted(new Manage.ModuleEventArgs());
                            this.events.committed();
                            this.focus();
                        }
                    });
                });
                args.executeSteps((e) => {
                    this.status = "error";
                    this.onModuleCommitError(new Manage.ModuleErrorEventArgs({
                        error: e
                    }));
                    this.events.commitError();
                    this.focus();
                });
            }
            focus() {
                let args = new Manage.ModuleEventArgs();
                this.createContext();
                this.events.focus();
                this.onModuleFocus(args);
                if (!args.cancelled) {
                    this.node.css({ display: "grid" });
                    this.resize();
                    Manage.Modules.instance.current = this;
                    this.settings.lastAccessed = Date.now();
                    let callback = () => {
                        this.events.focused();
                        Manage.ModuleEventsHub.moduleFocusedPublish({
                            module: this
                        });
                    };
                    this.status == "ok" ?
                        this.addToRecentItems(callback) : callback();
                }
            }
            load() {
                let args = new Manage.ModuleLoadEventArgs();
                this.createContext();
                this.events.load();
                this.onModuleLoad(args);
                args.addCompleteStep(() => {
                    return new Promise(() => {
                        if (!args.cancelled) {
                            this.onModuleLoaded(new Manage.ModuleEventArgs());
                            this.events.loaded();
                            this.focus();
                            Manage.ModuleEventsHub.moduleLoadedPublish({
                                module: this
                            });
                        }
                    });
                });
                args.executeSteps((e) => {
                    this.status = "error";
                    this.onModuleLoadError(new Manage.ModuleErrorEventArgs({
                        error: e
                    }));
                    this.events.loadError();
                    this.focus();
                    this.removeFromRecentItems(() => {
                        Manage.ModuleEventsHub.modulesLoadErrorPublish({
                            module: this
                        });
                    });
                });
            }
            resize() {
            }
            unload() {
                let args = new Manage.ModuleUnloadEventArgs();
                let unload = () => {
                    this.onModuleUnloaded(new Manage.ModuleEventArgs());
                    PDJS.Manage.Modules.instance.remove(this);
                    this.events.unloaded();
                    this.destroy();
                };
                this.onModuleUnload(args);
                if (this.status == "error") {
                    unload();
                }
                args.addStep(() => {
                    return new Promise((resolve, reject) => {
                        if (!args.cancelled) {
                            unload();
                        }
                    });
                });
                args.executeSteps((error) => {
                    this.onModuleUnloadError(new Manage.ModuleErrorEventArgs({
                        error: error
                    }));
                    this.events.unloadError(new Manage.ModuleEventHandlerArgs({
                        module: this,
                        errors: error
                    }));
                });
            }
            execute(directive) {
                let args = this.decodeDirective(directive);
                this.registerDirectives();
                if (args == null) {
                    return;
                }
                let matched = null;
                this.directives.each(directive => {
                    if (directive.isMatch(args)) {
                        matched = directive;
                    }
                });
                if (this.events.isLoaded) {
                    if (matched != null) {
                        matched.execute(args);
                    }
                }
            }
            modulePromise(fn) {
                return new Promise((resolveInternal, rejectInternal) => {
                    fn((e) => {
                        resolveInternal("success");
                    }, (e) => {
                        switch (true) {
                            case e instanceof PDJS.Services.ServiceResponse:
                                e.errorHandled = true;
                                rejectInternal(e.xhr);
                                break;
                            case e.errorHandled != undefined:
                                e.errorHandled = true;
                                rejectInternal(e);
                                break;
                            default:
                                rejectInternal(e);
                        }
                    });
                });
            }
            onCreateContext(context) {
            }
            onModuleBlur(e) {
            }
            onModuleCommit(e) {
            }
            onModuleCommitError(e) {
            }
            onModuleCommitted(e) {
            }
            onModuleFocus(e) {
            }
            onModuleLoad(e) {
            }
            onModuleLoaded(e) {
            }
            onModuleLoadError(e) {
                var _a;
                let errorMessage = ((_a = e === null || e === void 0 ? void 0 : e.error) === null || _a === void 0 ? void 0 : _a.message) || "Error Loading Module";
                let message = new PDJS.Shared.UI.Controls.Message({
                    message: `<u style="color: var(--visiv-system-red);">Module Load Error</u><br/>${errorMessage}`,
                    fontSize: "20px",
                    fill: true,
                    textColor: "var(--visiv-error-fore-color)"
                });
                this.settings.label = "Error Loading";
                this.controls.clear();
                this.controls.add(message);
            }
            onModuleUnload(e) {
            }
            onModuleUnloaded(e) {
            }
            onModuleUnloadError(e) {
            }
            onRegisterDirectives() {
            }
            onDestroy(e) {
                super.onDestroy(e);
                this.destroyContext();
                if (this.m_monitor != null) {
                    this.m_monitor.destroy();
                }
            }
            decodeDirective(args) {
                let result = null;
                try {
                    result = JSON.parse(atob(args));
                }
                catch (ex) {
                    result = null;
                }
                return result;
            }
            registerDirectives() {
                if (this.m_directives == null) {
                    this.m_directives = new Manage.ModuleDirectiveCollection(this);
                    this.onRegisterDirectives();
                }
            }
            ensureEvents() {
                if (this.m_events == null) {
                    this.m_events = new Manage.ModuleEvents({ module: this });
                }
            }
            ensureMonitor() {
                if (this.m_monitor != null) {
                    return;
                }
                this.m_monitor = new PDJS.Shared.Navigate.ChangeMonitor({
                    proceed: () => {
                        this.settings.hasChanges = false;
                    }
                });
                this.m_monitor.validators.add(new PDJS.Shared.Navigate.ChangeMonitorValidator({
                    changes: () => {
                        return this.settings.hasChanges;
                    }
                }));
            }
            ensureSettings() {
                if (this.m_settings == null) {
                    this.m_settings = new Manage.ModuleSettings(_.extend(this.state.get("settings"), {
                        change: (e) => {
                            this.events.change();
                        }
                    }));
                }
            }
            createContext() {
                let contexts = PDJS.Application
                    .instance
                    .contexts;
                let contextExists = contexts.getContextById(this.ID) != null;
                if (!contextExists) {
                    contexts.createContext({
                        id: this.ID,
                        name: `Module: ${this.settings.label}`,
                        parent: PDJS.Application.instance.contexts.global,
                        makeDefault: true
                    });
                    this.settings.contextId = this.ID;
                    this.onCreateContext(contexts.current);
                }
                else {
                    contexts.setCurrent(this.ID);
                }
            }
            destroyContext() {
                PDJS.Application
                    .instance
                    .contexts
                    .destroyContext({
                    id: this.ID
                });
            }
            addToRecentItems(complete = () => { }) {
                let service = new PDJS.Services.Personalization.RecentItemsService();
                service.add({
                    name: this.settings.label,
                    route: this.settings.route,
                    complete: (e) => {
                        complete();
                    }
                });
            }
            removeFromRecentItems(complete = () => { }) {
                let service = new PDJS.Services.Personalization.RecentItemsService();
                service.remove({
                    route: this.settings.route,
                    complete: (e) => {
                        complete();
                    }
                });
            }
        }
        Manage.Module = Module;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleDirective {
            constructor(options) {
            }
            get name() {
                return this.m_name;
            }
            set name(value) {
                this.m_name = value;
            }
            get module() {
                return this.m_module;
            }
            set module(value) {
                this.m_module = value;
            }
            isMatch(args) {
                return this.name.toLowerCase() == args.name.toLowerCase();
            }
            mount(module) {
                this.m_module = module;
            }
            execute(args) {
            }
        }
        Manage.ModuleDirective = ModuleDirective;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleDirectiveCollection extends Jade.MappedCollection {
            constructor(module) {
                super({
                    key: "name"
                });
                this.m_module = module;
            }
            get module() {
                return this.m_module;
            }
            add(item) {
                item.mount(this.module);
                return super.add(item);
            }
        }
        Manage.ModuleDirectiveCollection = ModuleDirectiveCollection;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleDirectives {
            static assembleUrl(moduleId, arg1, arg2 = null) {
                let targetId = _.isString(arg1) ? arg1 : "*";
                let args = _.isPlainObject(arg1) ? arg1 : arg2;
                if (args != null) {
                    args = btoa(JSON.stringify(args));
                }
                return args == null ?
                    `#/module/${moduleId}/${targetId}` :
                    `#/module/${moduleId}/${targetId}/args/${args}`;
            }
            static createUrl(moduleId, arg1, arg2, arg3) {
                let hasTarget = _.isString(arg1) && _.isString(arg2);
                let targetId = null;
                let directiveName = null;
                let directiveArgs = null;
                if (hasTarget) {
                    targetId = arg1;
                    directiveName = arg2;
                    directiveArgs = _.extend(arg3 || {}, {
                        name: directiveName
                    });
                }
                if (!hasTarget) {
                    directiveName = arg1;
                    directiveArgs = _.extend(arg2 || {}, {
                        name: directiveName
                    });
                }
                return this.assembleUrl(moduleId, targetId, directiveArgs);
            }
            static execute(moduleId, arg1, arg2, arg3) {
                Manage.ModuleLoader.load(this.createUrl(moduleId, arg1, arg2, arg3));
            }
        }
        Manage.ModuleDirectives = ModuleDirectives;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleEventArgs {
            get cancelled() {
                return this.m_cancelled;
            }
            set cancelled(value) {
                this.m_cancelled = value;
            }
            cancel() {
                this.cancelled = true;
            }
        }
        Manage.ModuleEventArgs = ModuleEventArgs;
        class ModuleEventArgsWithSteps extends ModuleEventArgs {
            constructor() {
                super();
                this.m_steps = [];
                this.m_completes = [];
            }
            addStep(step) {
                this.m_steps.push(step);
            }
            addCompleteStep(step) {
                this.m_completes.push(step);
            }
            addError(message) {
                this.m_steps.push(() => {
                    return new Promise((resolve, reject) => {
                        reject(message);
                    });
                });
            }
            addCatch(step) {
                this.m_steps.push(step);
            }
            executeSteps(error = null) {
                let result = Promise.resolve();
                let aborted = false;
                this.m_steps.forEach(step => {
                    result = result.then(step, (e) => {
                        !aborted ? error(e) : null;
                        aborted = true;
                    });
                });
                result.finally(() => {
                    if (!aborted) {
                        this.executeFinallySteps(error);
                    }
                });
                if (error != null) {
                    result = result.catch(error);
                }
            }
            executeFinallySteps(error = null) {
                let result = Promise.resolve();
                let aborted = false;
                this.m_completes.forEach(step => {
                    result = result.then(step, (e) => {
                        !aborted ? error(e) : null;
                        aborted = true;
                    });
                });
                if (error != null) {
                    result = result.catch(error);
                }
            }
        }
        Manage.ModuleEventArgsWithSteps = ModuleEventArgsWithSteps;
        class ModuleLoadEventArgs extends ModuleEventArgsWithSteps {
        }
        Manage.ModuleLoadEventArgs = ModuleLoadEventArgs;
        class ModuleCommitEventArgs extends ModuleEventArgsWithSteps {
        }
        Manage.ModuleCommitEventArgs = ModuleCommitEventArgs;
        class ModuleUnloadEventArgs extends ModuleEventArgsWithSteps {
        }
        Manage.ModuleUnloadEventArgs = ModuleUnloadEventArgs;
        class ModuleErrorEventArgs {
            constructor(options) {
                this.processInput(options.error);
            }
            get error() {
                return this.m_error;
            }
            processInput(input) {
                if (_.isString(input)) {
                    this.processString(input);
                }
                if (input.responseText !== undefined) {
                    this.processJQuery(input);
                }
                if (input instanceof PDJS.Services.ServiceResponse) {
                    this.processService(input);
                }
            }
            processJQuery(input) {
                this.m_error = PDJS.Shared.ErrorFactory.first(input);
                input.errorHandled = true;
            }
            processService(input) {
                this.m_error = PDJS.Shared.ErrorFactory.first(input.xhr);
                input.errorHandled = true;
            }
            processString(input) {
                this.m_error = PDJS.Shared.ErrorFactory.first(input);
            }
        }
        Manage.ModuleErrorEventArgs = ModuleErrorEventArgs;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleEventHandlerArgs {
            constructor(options) {
                this.m_module = options.module;
                this.m_errors = PDJS.Shared.ErrorFactory
                    .convert(options.errors);
            }
            get module() {
                return this.m_module;
            }
            get errors() {
                return this.m_errors.map(err => err.toJSON());
            }
        }
        Manage.ModuleEventHandlerArgs = ModuleEventHandlerArgs;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleEvents {
            constructor(options) {
                this.m_executed = {};
                this.module = options.module;
                this.m_eventBus = new Jade.EventBus();
            }
            get executed() {
                return this.m_executed;
            }
            get module() {
                return this.m_module;
            }
            set module(value) {
                this.m_module = value;
            }
            get isLoaded() {
                return this.executed["loaded"] == true;
            }
            blur(handler = undefined) {
                return this.handle("blur", handler);
            }
            blurred(handler = undefined) {
                return this.handle("blurred", handler);
            }
            change(handler = undefined) {
                return this.handle("commit", handler);
            }
            commit(handler = undefined) {
                return this.handle("commit", handler);
            }
            commitError(handler = undefined) {
                return this.handle("commitError", handler);
            }
            committed(handler = undefined) {
                return this.handle("committed", handler);
            }
            focus(handler = undefined) {
                return this.handle("focus", handler);
            }
            focused(handler = undefined) {
                return this.handle("focused", handler);
            }
            load(handler = undefined) {
                return this.handle("load", handler);
            }
            loadError(handler = undefined) {
                return this.handle("loadError", handler);
            }
            loaded(handler = undefined) {
                return this.handle("loaded", handler);
            }
            unload(handler = undefined) {
                return this.handle("unload", handler);
            }
            unloadError(args = undefined) {
                return this.handle("unloadError", args);
            }
            unloaded(handler = undefined) {
                return this.handle("unloaded", handler);
            }
            handle(event, args) {
                if (args == undefined) {
                    args = new Manage.ModuleEventHandlerArgs({
                        module: this.module
                    });
                }
                if (args instanceof Manage.ModuleEventHandlerArgs) {
                    this.m_eventBus.publish(event, args);
                }
                if (_.isFunction(args)) {
                    let subscription = this.m_eventBus.subscribe(event, args);
                    this.executed[event] = true;
                    return subscription;
                }
            }
        }
        Manage.ModuleEvents = ModuleEvents;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        let Events;
        (function (Events) {
            Events["ModuleCreated"] = "Module:Created";
            Events["ModuleFocused"] = "Module:Focused";
            Events["ModuleLoaded"] = "Module:Loaded";
            Events["ModuleLoadError"] = "Module:Load:Error";
            Events["ModulesLoading"] = "Modules:Loading";
            Events["ModulesLoaded"] = "Modules:Loaded";
            Events["ModulesUnloadAll"] = "Modules:UnloadAll";
            Events["ModulesEmptied"] = "Modules:Emptied";
        })(Events = Manage.Events || (Manage.Events = {}));
        class ModuleEventsHub extends PDJS.Shared.EventsHubBase {
            static moduleCreatedPublish(args) {
                this.global.publish(Events.ModuleCreated, args);
            }
            static moduleFocusedPublish(args) {
                this.global.publish(Events.ModuleFocused, args);
            }
            static moduleLoadedPublish(args) {
                this.global.publish(Events.ModuleLoaded, args);
            }
            static modulesEmptiedPublish() {
                this.global.publish(Events.ModulesEmptied);
            }
            static modulesLoadedPublish() {
                this.global.publish(Events.ModulesLoaded);
            }
            static modulesLoadingPublish() {
                this.global.publish(Events.ModulesLoading);
            }
            static modulesLoadErrorPublish(args) {
                this.global.publish(Events.ModuleLoadError, args);
            }
            static moduleCreatedSubscribe(handler) {
                return this.global.subscribe(Events.ModuleCreated, handler);
            }
            static moduleLoadedSubscribe(handler) {
                return this.global.subscribe(Events.ModuleLoaded, handler);
            }
            static moduleFocusedSubscribe(handler) {
                return this.global.subscribe(Events.ModuleFocused, handler);
            }
            static modulesLoadedSubscribe(handler) {
                return this.global.subscribe(Events.ModulesLoaded, handler);
            }
            static modulesLoadingSubscribe(handler) {
                return this.global.subscribe(Events.ModulesLoading, handler);
            }
            static modulesLoadErrorSubscribe(handler) {
                return this.global.subscribe(Events.ModuleLoadError, handler);
            }
            static modulesEmptiedSubscribe(handler) {
                return this.global.subscribe(Events.ModulesEmptied, handler);
            }
        }
        Manage.ModuleEventsHub = ModuleEventsHub;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleLoader {
            static get queue() {
                this.m_queue == null ? this.m_queue = [] : null;
                return this.m_queue;
            }
            static get loadingDialog() {
                return this.m_loadingDialog;
            }
            static set loadingDialog(value) {
                this.m_loadingDialog = value;
            }
            static load(routes, options = {}) {
                options.complete = options.complete || (() => { });
                if (_.isString(routes)) {
                    routes = [routes];
                }
                if (this.loadingDialog == null && routes.length > 1) {
                    this.showLoadingDialog(options.message);
                }
                if (routes instanceof Array) {
                    let resolvedRoutes = [];
                    routes.forEach(route => {
                        let resolved = Manage.ModuleRoutes.instance.resolve(route);
                        if (resolved) {
                            resolvedRoutes.push(resolved);
                        }
                    });
                    if (this.m_requests != null) {
                        this.addToQueue(resolvedRoutes, options);
                        return;
                    }
                    this.executeRequests(resolvedRoutes, options, () => {
                        this.hideLoadingDialog();
                        setTimeout(() => { options.complete(); }, 50);
                    });
                }
            }
            static addToQueue(routes, options = {}) {
                this.queue.push({
                    id: Jade.Guid.new(),
                    routes: routes,
                    options: options
                });
            }
            static executeRequestsInQueue() {
                if (this.queue.length === 0) {
                    return;
                }
                let request = this.queue[0];
                this.executeRequests(request.routes, request.options, () => {
                    this.queue.shift();
                    setTimeout(() => {
                        request.options.complete();
                        this.executeRequestsInQueue();
                    }, 50);
                });
            }
            static executeRequests(routes, options, complete = (() => { })) {
                this.m_requests = Promise.resolve();
                Manage.ModuleEventsHub.modulesLoadingPublish();
                routes.forEach((route, index) => {
                    this.m_requests = this.m_requests.then(() => this.request(route, options));
                });
                this.m_requests = this.m_requests.then(() => {
                    return new Promise((resolve, reject) => {
                        resolve();
                        complete();
                    });
                });
                this.m_requests = this.m_requests.finally(() => {
                    Manage.ModuleEventsHub.modulesLoadedPublish();
                    if (!Jade.String.isNullOrWhiteSpace(options.returnUrl)) {
                        let route = Manage.ModuleRoutes.instance.resolve(options.returnUrl);
                        if (route != null) {
                            ModuleLoader.load(route.path);
                        }
                    }
                    else {
                        location.href = Jade.Path.resolve(`~/manage${routes[routes.length - 1].path}`);
                    }
                    this.m_requests = null;
                    this.queue.length > 0 ? this.executeRequestsInQueue() : null;
                });
            }
            static request(e, options) {
                return new Promise((resolve, reject) => {
                    try {
                        let definition = Manage.Modules.instance.getDefinition(e.getModuleDefinitionId());
                        if (!definition) {
                            reject();
                        }
                        let settings = _.extend(definition, e.toJSON(), { route: e.path });
                        let subscriber = Manage.ModuleEventsHub.moduleCreatedSubscribe((e1) => {
                            e1.module.subscribe.loaded((e2) => {
                                if (e2.module.settings.route == e.path) {
                                    resolve();
                                    subscriber.unsubscribe();
                                }
                            });
                            e1.module.subscribe.loadError((e2) => {
                                if (e2.module.settings.route == e.path) {
                                    resolve();
                                    subscriber.unsubscribe();
                                }
                            });
                        });
                        let moduleIsAlreadyLoaded = PDJS.Manage.Modules.instance.getModule(e.path) != null;
                        if (settings != null) {
                            Manage.Modules.instance.request(settings);
                            window.history.replaceState(settings, Jade.Path.resolve(`~/manage${e.path}`));
                        }
                        if (moduleIsAlreadyLoaded) {
                            resolve();
                        }
                    }
                    catch (ex) {
                        reject(ex.message);
                    }
                });
            }
            static showLoadingDialog(message) {
                this.loadingDialog = Jade.UI.Dialogs.MessageDialog.open({
                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.None,
                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                    allowClose: false,
                    title: false,
                    width: 250,
                    newContext: false,
                    message: message || "Opening modules, please wait..."
                });
            }
            static hideLoadingDialog() {
                if (this.loadingDialog != null) {
                    this.loadingDialog.close();
                    this.loadingDialog = null;
                }
            }
        }
        Manage.ModuleLoader = ModuleLoader;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleRouter {
            static get instance() {
                this.ensureInstance();
                return this.m_instance;
            }
            registerRoutes() {
                Path.map("#/module/:moduleId(/:targetId)(/:args/:values)").to(function (e) {
                    Manage.ModuleLoader.load(window.location.hash);
                });
            }
            static ensureInstance() {
                if (!this.m_instance) {
                    this.m_instance = new ModuleRouter();
                }
            }
        }
        Manage.ModuleRouter = ModuleRouter;
        PDJS.Application.onStart(() => {
            ModuleRouter.instance.registerRoutes();
        });
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleSettings {
            constructor(options) {
                this.m_state = new Jade.StateBag(options);
                this.m_state.on("change", (e) => { this.onStateChanged(e); });
            }
            get state() {
                return this.m_state;
            }
            get allowClose() {
                return this.state.get("allowClose", true);
            }
            set allowClose(value) {
                this.state.set("allowClose", value);
            }
            get color() {
                return this.state.get("allowClose", true);
            }
            set color(value) {
                this.state.set("allowClose", value);
            }
            get contextId() {
                return this.m_contextId;
            }
            set contextId(value) {
                this.m_contextId = value;
            }
            get changeCallback() {
                return this.state.get("change", () => { });
            }
            set changeCallback(value) {
                this.state.set("change", value);
            }
            get error() {
                return this.state.get("error", true);
            }
            set error(value) {
                this.state.set("error", value);
            }
            get fallback() {
                return this.state.get("fallback", true);
            }
            set fallback(value) {
                this.state.set("fallback", value);
            }
            get(name, defaultValue) {
                return this.state.get(name, defaultValue);
            }
            get hasChanges() {
                return this.state.get("hasChanges", false);
            }
            set hasChanges(value) {
                this.state.set("hasChanges", value);
            }
            get moduleId() {
                return this.state.get("moduleId", true);
            }
            set moduleId(value) {
                this.state.set("moduleId", value);
            }
            get pinned() {
                return this.state.get("pinned", false);
            }
            set pinned(value) {
                this.state.set("pinned", value);
            }
            get label() {
                return this.state.get("label", "Loading...");
            }
            set label(value) {
                this.state.set("label", value);
            }
            get ready() {
                return this.state.get("ready", true);
            }
            set ready(value) {
                this.state.set("ready", value);
            }
            get route() {
                return this.state.get("route", true);
            }
            set route(value) {
                this.state.set("route", value);
            }
            get script() {
                return this.state.get("script", true);
            }
            set script(value) {
                this.state.set("script", value);
            }
            set(name, value) {
                this.state.set(name, value);
            }
            get targetId() {
                return this.state.get("targetId", true);
            }
            set targetId(value) {
                this.state.set("targetId", value);
            }
            get uid() {
                return this.state.get("uid", true);
            }
            set uid(value) {
                this.state.set("uid", value);
            }
            get lastAccessed() {
                return this.state.get("lastAccessed");
            }
            set lastAccessed(value) {
                this.state.set("lastAccessed", value);
            }
            toJSON() {
                return this.state.toJSON();
            }
            onStateChanged(e) {
                this.changeCallback();
            }
        }
        Manage.ModuleSettings = ModuleSettings;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTypesCollection extends Jade.MappedCollection {
            constructor() {
                super({ key: "route" });
            }
            findByRoute(route) {
                route = route.toLowerCase();
                return super.get(route);
            }
            load(success = (() => { })) {
                let service = new PDJS.Services.Manage.ModuleService();
                service.loadDefinitions({
                    success: (e) => {
                        for (let key in e.data.modules) {
                            this.add(e.data.modules[key]);
                        }
                        ;
                        success();
                    }
                });
            }
        }
        Manage.ModuleTypesCollection = ModuleTypesCollection;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class Modules {
            get types() {
                this.ensureTypes();
                return this.m_types;
            }
            set types(value) {
                this.m_types = value;
            }
            get current() {
                return this.m_current;
            }
            set current(value) {
                this.m_current = value;
            }
            static get instance() {
                this.ensureInstance();
                return this.m_instance;
            }
            get modules() {
                this.ensureModules();
                return this.m_modules;
            }
            set modules(value) {
                this.m_modules = value;
            }
            getDefinition(route) {
                return this.types.findByRoute(route);
            }
            getModule(route) {
                return this.modules.findByRoute(route);
            }
            request(args) {
                new Manage.ModuleRequestCommand().execute(args);
            }
            remove(module) {
                this.modules.remove(module);
                if (this.modules.count === 0) {
                    Manage.ModuleEventsHub.modulesEmptiedPublish();
                }
            }
            getFallbackRoute(module) {
                let result = "#";
                let fallback = null;
                this.modules.each((item, index) => {
                    if (module === item) {
                        if (index > 0) {
                            fallback = this.modules.item(index - 1);
                        }
                        if (index == 0 && this.modules.count > 1) {
                            fallback = this.modules.item(index + 1);
                        }
                    }
                });
                if (fallback != null) {
                    result = fallback.settings.route;
                }
                return result;
            }
            static ensureInstance() {
                if (this.m_instance == null) {
                    this.m_instance = new Modules();
                }
            }
            ensureModules() {
                if (this.m_modules == null) {
                    this.m_modules = new Manage.ModulesCollection();
                }
            }
            ensureTypes() {
                if (this.m_types == null) {
                    this.m_types = new Manage.ModuleTypesCollection();
                }
            }
        }
        Manage.Modules = Modules;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModulesCollection extends Jade.Collection {
            constructor() {
                super();
            }
            findByRoute(route) {
                var result = _.find(this.toArray(), (module) => {
                    return module.settings.route === route;
                });
                return result;
            }
            add(module) {
                if (this.findByRoute(module.settings.route) == null) {
                    return super.add(module);
                }
                return false;
            }
            remove(module) {
                if (module == null) {
                    return null;
                }
                let index = _.indexOf(this.toArray(), module);
                if (index != null && index > -1) {
                    return super.removeAt(index);
                }
                return module;
            }
            getFallback(moduleUid) {
                let fallbackIndex = -1;
                _.find(this.toArray(), (module, index) => {
                    if (module.settings.uid === moduleUid) {
                        fallbackIndex = (index === 0 ? 1 : index - 1);
                        return true;
                    }
                });
                if (this.toArray().length > fallbackIndex) {
                    return this.item(fallbackIndex);
                }
            }
        }
        Manage.ModulesCollection = ModulesCollection;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModulesCommand {
            get modules() {
                return Manage.Modules.instance.modules;
            }
            get definitions() {
                return Manage.Modules.instance.types;
            }
            execute(args) {
            }
        }
        Manage.ModulesCommand = ModulesCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleFocusCommand extends Manage.ModulesCommand {
            execute(e) {
                let executeArgs = e.moduleSettings.args;
                this.modules.each(module => {
                    if (e.moduleSettings.route !== module.settings.route) {
                        module.blur();
                    }
                });
                e.module.focus();
                if (executeArgs != null) {
                    e.module.execute(executeArgs);
                }
            }
        }
        Manage.ModuleFocusCommand = ModuleFocusCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleLoadCommand extends Manage.ModulesCommand {
            execute(e) {
                let moduleType = Jade.Type.getType(e.script);
                moduleType != null ?
                    this.createInstance(moduleType, e) :
                    this.showErrorDialog(e);
            }
            createInstance(moduleType, settings) {
                let module = new moduleType({
                    settings: settings
                });
                this.modules.add(module);
                Manage.ModuleEventsHub.moduleCreatedPublish({
                    module: module
                });
                module.subscribe.loaded(e => {
                    if (settings.args != null) {
                        e.module.execute(settings.args);
                    }
                });
                this.modules.each(module => {
                    module.blur();
                });
                module.load();
            }
            showErrorDialog(e) {
                Jade.UI.Dialogs.MessageDialog.open({
                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                    allowClose: true,
                    title: "Module Error",
                    message: `Unable to load module "${e.moduleId}".`
                });
            }
        }
        Manage.ModuleLoadCommand = ModuleLoadCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleRequestCommand extends Manage.ModulesCommand {
            execute(args) {
                let module = this.modules.findByRoute(args.route);
                module != null ?
                    this.moduleFocus(module, args) :
                    this.moduleLoad(args);
            }
            moduleLoad(args) {
                new Manage.ModuleLoadCommand().execute(args);
            }
            moduleFocus(module, args) {
                new Manage.ModuleFocusCommand().execute({
                    module: module,
                    moduleSettings: args
                });
            }
        }
        Manage.ModuleRequestCommand = ModuleRequestCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class UnloadModuleCommand {
            get tabStrip() {
                return this.m_tabStrip;
            }
            set tabStrip(value) {
                this.m_tabStrip = value;
            }
            execute(args) {
                this.tabStrip = args.tabStrip;
                if (args.module.settings.hasChanges) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        message: `There are unsaved changes to "${args.module.settings.label}". Close without saving changes?`,
                        select: {
                            yes: (sender, e) => {
                                sender.close();
                                this.unloadModule(args.module);
                            }
                        }
                    });
                }
                else {
                    this.unloadModule(args.module);
                }
            }
            unloadModule(module) {
                let fallbackRoute = this.getFallbackRoute(module);
                let wasFocused = module.focused;
                let subscriber1 = module.subscribe.unloaded(e => this.moduleUnloaded({
                    fallbackRoute: fallbackRoute,
                    handlerArgs: e,
                    subscriber: subscriber1,
                    wasFocused: wasFocused
                }));
                let subscriber2 = module.subscribe.unloadError(e => this.moduleUnloadError({
                    fallbackRoute: fallbackRoute,
                    handlerArgs: e,
                    subscriber: subscriber2,
                    wasFocused: wasFocused
                }));
                module.unload();
            }
            showUnloadModuleErrors(message) {
                Jade.UI.Dialogs.MessageDialog.open({
                    title: "Module | Close Error",
                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                    message: `The module cannot be closed for the following reason:<br/>${message}`
                });
            }
            moduleUnloadError(e) {
                let error = _.first(e.handlerArgs.errors);
                if (error != null) {
                    this.showUnloadModuleErrors(error.message);
                }
                e.subscriber.unsubscribe();
            }
            moduleUnloaded(e) {
                if (e.wasFocused) {
                    window.location.hash = e.fallbackRoute || "";
                }
                e.subscriber.unsubscribe();
            }
            getFallbackRoute(module) {
                let result = [];
                let prev = [];
                let next = [];
                let found = false;
                this.tabStrip.tabModules.forEach(item => {
                    let isTargetModule = item.ID === module.ID;
                    isTargetModule ? found = true : null;
                    if (!isTargetModule) {
                        !found ?
                            prev.push(item.settings.route) :
                            next.push(item.settings.route);
                    }
                });
                result.push(...next);
                result.push(...prev.reverse());
                return _.first(result);
            }
        }
        Manage.UnloadModuleCommand = UnloadModuleCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class UnloadModulesCommand {
            constructor() {
                this.m_unloadErrors = [];
            }
            get tabStrip() {
                return this.m_tabStrip;
            }
            set tabStrip(value) {
                this.m_tabStrip = value;
            }
            execute(e) {
                this.tabStrip = e.tabStrip;
                let hasExclude = e.target != null;
                let args = {
                    target: e.target,
                    hasChanges: [],
                    noChanges: []
                };
                switch (true) {
                    case e.clear == "all" && !hasExclude:
                        this.closeAll(args);
                        break;
                    case e.clear == "all" && hasExclude:
                        this.closeAllButThis(args);
                        break;
                    case e.clear == "left" && hasExclude:
                        this.closeAllToTheLeft(args);
                        break;
                    case e.clear == "right" && hasExclude:
                        this.closeAllToTheRight(args);
                        break;
                    case e.clear == "unpinned":
                        this.closeAllButPinned(args);
                        break;
                }
                if (args.hasChanges.length > 0) {
                    Jade.UI.Dialogs.MultiMessageDialog.open({
                        title: "Modules | Unsaved Changes",
                        header: "The following modules have unsaved changes. Close these modules without saving changes?",
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNoCancel,
                        messages: args.hasChanges.map(module => module.settings.label),
                        select: {
                            yes: (sender, e) => {
                                sender.close();
                                this.unloadModules(args, true);
                            },
                            no: (sender, e) => {
                                sender.close();
                                this.unloadModules(args, false);
                            }
                        }
                    });
                    return;
                }
                this.unloadModules(args, false);
            }
            closeAll(args) {
                PDJS.Manage.Modules.instance.modules.toArray().forEach(module => {
                    module.settings.hasChanges ?
                        args.hasChanges.push(module) :
                        args.noChanges.push(module);
                });
            }
            closeAllButThis(args) {
                this.tabStrip.tabModules.forEach(module => {
                    if (module != args.target) {
                        module.settings.hasChanges ?
                            args.hasChanges.push(module) :
                            args.noChanges.push(module);
                        return;
                    }
                });
            }
            closeAllButPinned(args) {
                this.tabStrip.tabModules.forEach(module => {
                    if (!module.settings.pinned) {
                        module.settings.hasChanges ?
                            args.hasChanges.push(module) :
                            args.noChanges.push(module);
                        return;
                    }
                });
            }
            closeAllToTheLeft(args) {
                let foundTarget = false;
                this.tabStrip.tabModules.forEach(module => {
                    let isTarget = args.target.ID === module.ID;
                    !foundTarget ? foundTarget = isTarget : null;
                    if (!foundTarget) {
                        module.settings.hasChanges ?
                            args.hasChanges.push(module) :
                            args.noChanges.push(module);
                        return;
                    }
                });
            }
            closeAllToTheRight(args) {
                let foundTarget = false;
                this.tabStrip.tabModules.forEach(module => {
                    let isTarget = args.target.ID === module.ID;
                    if (foundTarget) {
                        module.settings.hasChanges ?
                            args.hasChanges.push(module) :
                            args.noChanges.push(module);
                        return;
                    }
                    !foundTarget ? foundTarget = isTarget : null;
                });
            }
            unloadModule(module) {
                return new Promise((resolve, reject) => {
                    let subscriber1 = module.subscribe.unloaded((e) => {
                        resolve();
                        subscriber1.unsubscribe();
                    });
                    let subscriber2 = module.subscribe.unloadError((e) => {
                        let error = _.first(e.errors);
                        reject();
                        if (error != null) {
                            this.m_unloadErrors.push(`${module.settings.label}: ${error.message}`);
                        }
                        subscriber2.unsubscribe();
                    });
                    module.unload();
                });
            }
            unloadModules(args, unloadChanged) {
                let tasks = [];
                let modules = [];
                let fallbacks = [];
                if (unloadChanged) {
                    args.hasChanges.forEach(module => {
                        modules.push(module);
                    });
                }
                args.noChanges.forEach(module => {
                    modules.push(module);
                });
                if (modules.some(module => module.focused)) {
                    fallbacks = this.getFallbackRoutes();
                }
                ;
                modules.forEach(module => {
                    tasks.push(this.unloadModule(module));
                });
                Promise.allSettled(tasks).finally(() => {
                    this.showUnloadErrors();
                    this.fallback(fallbacks);
                });
            }
            getFallbackRoutes() {
                let result = [];
                let found = false;
                let next = [];
                let prev = [];
                this.tabStrip.tabModules.forEach(module => {
                    module.focused ? found = true : null;
                    found ?
                        next.push(module.settings.route) :
                        prev.push(module.settings.route);
                });
                result.push(...next);
                result.push(...prev.reverse());
                return result;
            }
            showUnloadErrors() {
                if (this.m_unloadErrors.length == 0) {
                    return;
                }
                Jade.UI.Dialogs.MultiMessageDialog.open({
                    title: "Modules | Close Errors",
                    header: "The following issues prevent some modules from being closed.",
                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                    messages: this.m_unloadErrors
                });
                this.m_unloadErrors = [];
            }
            fallback(fallbacks) {
                let routes = [];
                if (fallbacks.length === 0) {
                    return;
                }
                fallbacks.forEach(route => {
                    if (PDJS.Manage.Modules.instance.modules.findByRoute(route) != null) {
                        routes.push(route);
                    }
                });
                let route = _.first(routes);
                if (route !== null) {
                    window.location.hash = route;
                }
            }
        }
        Manage.UnloadModulesCommand = UnloadModulesCommand;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleRoute {
            constructor(route) {
                this.route = route || "";
                this.route = this.route.replace(/\/args\//ig, this.argsText);
                this.ensurePrefix();
            }
            get areaId() {
                return this.parts.length > 1 ? this.parts[1] : "";
            }
            get argsIndex() {
                return this.route.indexOf(this.argsText);
            }
            get hash() {
                return this.parts.length > 1 ? this.parts[0] : "";
            }
            get parts() {
                return this.path.split("/");
            }
            get route() {
                return this.m_route;
            }
            set route(value) {
                this.m_route = value;
            }
            get path() {
                this.ensurePath();
                return this.m_path;
            }
            get args() {
                this.ensureArgs();
                return this.m_args;
            }
            get argsText() {
                return "/args/";
            }
            toJSON(data = {}) {
                return _.merge({
                    areaId: this.areaId,
                    args: this.args,
                    route: this.route,
                    path: this.path
                }, data);
            }
            canHandle() {
                return false;
            }
            getModuleDefinitionId() {
                return this.route;
            }
            ensureArgs() {
                if (this.m_args == null && this.argsIndex > -1) {
                    this.m_args = this.route.substring(this.argsIndex + this.argsText.length);
                }
            }
            ensurePath() {
                if (this.m_path == null) {
                    this.m_path = this.argsIndex > -1 ?
                        this.route.substring(0, this.argsIndex).toLowerCase() :
                        this.route.toLowerCase();
                }
            }
            ensurePrefix() {
                let startsWithHash = this.route.startsWith("#");
                let startsWithSlash = this.route.startsWith("/");
                let startsWithHashAndSlash = this.route.startsWith("#/");
                switch (true) {
                    case startsWithHashAndSlash:
                        break;
                    case startsWithSlash:
                        this.route = `#${this.route}`;
                        break;
                    case startsWithHash:
                        this.route = `#/${this.route.substring(1)}`;
                        break;
                    default:
                        this.route = `#/${this.route}`;
                        break;
                }
            }
        }
        Manage.ModuleRoute = ModuleRoute;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ManageModuleRoute extends Manage.ModuleRoute {
            get moduleId() {
                return this.parts.length > 2
                    ? this.parts[2] : "";
            }
            get targetId() {
                return this.parts.length > 3
                    ? this.parts[3] : "";
            }
            canHandle() {
                return this.areaId === "module";
            }
            getModuleDefinitionId() {
                return `${this.hash}/${this.areaId}/${this.moduleId}`;
            }
            toJSON() {
                return super.toJSON({
                    moduleId: this.moduleId,
                    targetId: this.targetId
                });
            }
        }
        Manage.ManageModuleRoute = ManageModuleRoute;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleRoutes {
            constructor() {
                this.m_routes = [];
            }
            static get instance() {
                this.ensureInstance();
                return this.m_instance;
            }
            get routes() {
                return this.m_routes.slice(0);
            }
            add(route) {
                this.m_routes.push(route);
            }
            resolve(path) {
                let result = null;
                path = path.slice(path.indexOf("#"), path.length);
                this.routes.forEach(route => {
                    if (result == null) {
                        let instance = new route(path);
                        if (instance.canHandle()) {
                            result = instance;
                        }
                    }
                });
                return result;
            }
            static ensureInstance() {
                if (!this.m_instance) {
                    this.m_instance = new ModuleRoutes();
                }
            }
        }
        Manage.ModuleRoutes = ModuleRoutes;
        PDJS.Application.onStart(() => {
            ModuleRoutes.instance.add(Manage.ManageModuleRoute);
            ModuleRoutes.instance.add(Manage.PluginModuleRoute);
        });
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class PluginModuleRoute extends Manage.ModuleRoute {
            get moduleId() {
                return this.parts.length > 3
                    ? this.parts[3] : "";
            }
            get pluginId() {
                return this.parts.length > 2
                    ? this.parts[2] : "";
            }
            get targetId() {
                return this.parts.length > 4
                    ? this.parts[4] : "";
            }
            canHandle() {
                return this.areaId === "plugin";
            }
            getModuleDefinitionId() {
                return Jade.String.isNullOrWhiteSpace(this.moduleId) ?
                    `${this.hash}/${this.areaId}/${this.pluginId}` :
                    `${this.hash}/${this.areaId}/${this.pluginId}/${this.moduleId}`;
            }
            toJSON() {
                return super.toJSON({
                    moduleId: this.moduleId,
                    pluginId: this.pluginId,
                    targetId: this.targetId
                });
            }
        }
        Manage.PluginModuleRoute = PluginModuleRoute;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripBase extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_scroller = null;
                        this.m_anchor = null;
                        this.m_observer = null;
                    }
                    get allowScrollButtons() {
                        return this.state.get("allowScrollButtons", true);
                    }
                    get anchor() {
                        return this.m_anchor;
                    }
                    set anchor(value) {
                        this.m_anchor = value;
                    }
                    get binding() {
                        return this.state.get("binding");
                    }
                    get clickCallback() {
                        return this.state.get("click", (e) => { });
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get menuAnchorAlwaysVisible() {
                        return this.state.get("menuAnchorAlwaysVisible", false);
                    }
                    get menuCreateCallback() {
                        return this.state.get("menuCreate", (e) => {
                            return this.menuCreate(e);
                        });
                    }
                    get menuItemClickCallback() {
                        return this.state.get("menuItemClick", (e) => { });
                    }
                    get menuItemCreateCallback() {
                        return this.state.get("menuItemCreate", (e) => {
                            return this.menuItemCreate(e);
                        });
                    }
                    get scroller() {
                        return this.m_scroller;
                    }
                    set scroller(value) {
                        this.m_scroller = value;
                    }
                    get tabClickCallback() {
                        return this.state.get("tabClick", () => { });
                    }
                    get tabCreateCallback() {
                        return this.state.get("tabCreate", (e) => {
                            return this.tabCreate(e);
                        });
                    }
                    get tabs() {
                        this.ensureTabs();
                        return this.m_tabs;
                    }
                    get tabsData() {
                        return this.state.get("tabsData", []);
                    }
                    get tabsNode() {
                        return this.node.find(".-pdjs-tabstrip-tabs");
                    }
                    addTab(e) {
                        let options = _.extend({
                            $tabStrip: this,
                            binding: this.binding,
                        }, e);
                        options.click = (e) => {
                            this.tabClick(e);
                        };
                        let tab = this.tabCreateCallback(options);
                        if (tab) {
                            this.controls.add(tab);
                            this.tabCreated(tab);
                        }
                        return tab;
                    }
                    clearSelectedTabs() {
                        this.tabs.all.forEach(tab => {
                            tab.selected = false;
                        });
                    }
                    template() {
                        return `<div class="-pdjs-tabstrip">
                        <div class="-pdjs-tabstrip-indent"></div>
                        <div class="-pdjs-tabstrip-tabs" data-controls></div>
                        <div class="-pdjs-tabstrip-scroll-l">
                            <div class="-pdjs-tabstrip-scroll-button">
                                <i class="icofont-simple-left"></i>
                            </div>
                        </div>
                        <div class="-pdjs-tabstrip-scroll-r">
                            <div class="-pdjs-tabstrip-scroll-button">
                                <i class="icofont-simple-right"></i>
                            </div>
                        </div>
                        <div class="-pdjs-tabstrip-spacer"></div>
                        <div class="-pdjs-tabstrip-overflow"></div>
                    </div>`;
                    }
                    select(value) {
                        this.clearSelectedTabs();
                        this.tabs.all.forEach(tab => {
                            if (tab.binding.value == value) {
                                tab.selected = true;
                            }
                        });
                    }
                    addMenu() {
                        let options = {
                            $anchor: this.anchor,
                            $tabStrip: this,
                            click: (e) => {
                                this.onItemClick(e);
                            },
                            itemClick: (e) => {
                                this.onMenuItemClick(e);
                                !e.cancel ?
                                    this.select(e.item.value) : null;
                            },
                            itemCreate: (e) => {
                                e.$tabStrip = this;
                                return this.menuItemCreateCallback(e);
                            }
                        };
                        let menu = this.menuCreateCallback(options);
                        if (menu) {
                            this.anchor.controls.add(menu);
                        }
                        return menu;
                    }
                    menuCreate(options) {
                        return new Controls.TabStripMenu(options);
                    }
                    menuItemCreate(e) {
                        return new Controls.TabStripMenuItem(e);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.anchor_init();
                        this.scroller_init();
                        this.observer_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.renderTabs();
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        this.m_observer.unobserve(this.node.get(0));
                    }
                    onItemClick(e) {
                        this.clickCallback(e);
                    }
                    onTabClick(e) {
                        this.tabClickCallback(e);
                    }
                    onMenuItemClick(e) {
                        this.menuItemClickCallback(e);
                    }
                    tabCreate(e) {
                        return new Controls.TabStripTab(e);
                    }
                    tabCreated(e) {
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled ?
                            this.node.removeClass("-pdjs-disabled") :
                            this.node.addClass("-pdjs-disabled");
                    }
                    onResize(e) {
                    }
                    onResized(e) {
                        this.scroller.scrollToSelectedTab();
                    }
                    anchor_init() {
                        this.m_anchor = new Controls.TabStripMenuAnchor({
                            insertAt: ".-pdjs-tabstrip-overflow",
                            $tabStrip: this,
                            alwaysVisible: this.menuAnchorAlwaysVisible,
                            addMenu: () => {
                                return this.addMenu();
                            }
                        });
                        this.controls.add(this.anchor);
                    }
                    observer_init() {
                        let debounced = _.debounce((e) => {
                            this.onResize(e);
                            this.scroller.resize();
                            this.onResized(e);
                        }, 250);
                        this.m_observer = new ResizeObserver((e) => {
                            debounced(e);
                        });
                        this.m_observer.observe(this.node.get(0));
                    }
                    renderTabs() {
                        this.tabsData.forEach(options => {
                            this.addTab(options);
                        });
                    }
                    scroller_init() {
                        this.m_scroller = new Controls.TabStripScroller({
                            tabStrip: this,
                            allowScrollButtons: this.allowScrollButtons,
                            change: (overflowed) => {
                                overflowed ?
                                    this.anchor.show() :
                                    this.anchor.hide();
                            }
                        });
                    }
                    tabClick(tab) {
                        let args = new Controls.TabStripTabClickEventArgs(tab);
                        if (this.enabled) {
                            tab.click(args);
                            if (!args.cancel) {
                                this.onTabClick(args);
                            }
                            if (!args.cancel) {
                                this.onItemClick(args);
                            }
                        }
                        if (!args.cancel) {
                            this.select(tab.value);
                        }
                    }
                    ensureTabs() {
                        if (this.m_tabs == null) {
                            this.m_tabs = new Controls.TabStripTabCollection({
                                tabStrip: this
                            });
                        }
                    }
                }
                Controls.TabStripBase = TabStripBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripOf extends Controls.TabStripBase {
                    constructor(options) {
                        super(options);
                    }
                    get tabs() {
                        return super.tabs;
                    }
                }
                Controls.TabStripOf = TabStripOf;
                class TabStrip extends TabStripOf {
                }
                Controls.TabStrip = TabStrip;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStrip extends PDJS.Shared.UI.Controls.TabStripOf {
            get tabModules() {
                let result = [];
                this.tabs.all.forEach((tab) => {
                    let module = PDJS.Manage.Modules
                        .instance.modules.findByRoute(tab.value);
                    module != null ? result.push(module) : null;
                });
                return result;
            }
            addTab(e) {
                let result = super.addTab(e);
                result.detach();
                this.unpin(result.ID);
                return result;
            }
            pin(id) {
                let targetNode = this.controls.getById(id).node;
                let pinnedNode = this.tabs.pinnedNodes.last();
                let unpinnedNode = this.tabs.unpinnedNodes.first();
                if (targetNode == null || targetNode.length === 0) {
                    return;
                }
                if (pinnedNode != null && pinnedNode.length > 0) {
                    targetNode.insertAfter(pinnedNode);
                    return;
                }
                if (unpinnedNode != null && unpinnedNode.length > 0) {
                    targetNode.insertBefore(unpinnedNode);
                    return;
                }
                this.tabsNode.append(targetNode);
                this.refreshMenu();
            }
            unpin(id) {
                let targetNode = this.controls.getById(id).node;
                let pinnedNode = this.tabs.pinnedNodes.last();
                let unpinnedNode = this.tabs.unpinnedNodes.first();
                if (targetNode == null || targetNode.length === 0) {
                    return;
                }
                if (pinnedNode != null && pinnedNode.length > 0) {
                    targetNode.insertAfter(pinnedNode);
                    return;
                }
                if (unpinnedNode != null && unpinnedNode.length > 0) {
                    targetNode.insertBefore(unpinnedNode);
                    return;
                }
                this.tabsNode.append(targetNode);
                this.refreshMenu();
            }
            refreshMenu() {
                let menu = this.anchor.menu;
                if (menu != null) {
                    menu.update();
                }
            }
            resize() {
                let tabsWidth = this.tabsNode.outerWidth();
                let totalWidth = 0;
                this.tabs.all.forEach(tab => {
                    let tabWidth = tab.node.outerWidth();
                    let addedWidth = totalWidth + tabWidth;
                    if (tab instanceof Manage.ModuleTabStripTab) {
                        addedWidth > tabsWidth ? tab.hide() : tab.show();
                    }
                    totalWidth += tabWidth;
                });
                this.repositionSelectedTab();
            }
            onActivate(e) {
                super.onActivate(e);
                this.draggable_init();
                this.subscriptions.add(Manage.ModuleEventsHub.modulesLoadingSubscribe(() => {
                    this.enabled = false;
                }));
                this.subscriptions.add(Manage.ModuleEventsHub.modulesLoadedSubscribe(() => {
                    this.enabled = true;
                    this.resize();
                }));
            }
            menuCreate(e) {
                return new Manage.ModuleTabStripMenu(e);
            }
            tabCreate(e) {
                return new Manage.ModuleTabStripTab(e);
            }
            tabCreated(tab) {
                if (this.tabs.allNodes.length > 1) {
                    tab.node.insertBefore(this.tabs.allNodes.first());
                }
                this.draggable_init();
            }
            menuItemCreate(e) {
                return new Manage.ModuleTabStripMenuItem(e);
            }
            onItemClick(e) {
                super.onItemClick(e);
                if (!Jade.String.isNullOrWhiteSpace(e.item.value)) {
                    window.location.href = e.item.value;
                }
            }
            onResized(e) {
                this.resize();
            }
            draggable_init() {
                this.m_draggable = new Manage.ModuleTabStripDraggable({
                    tabStrip: this,
                    tabStripMenu: this.anchor.menu
                });
            }
            repositionSelectedTab() {
                let selected = this.tabs.selectedNode;
                if (this.tabs.selectedIsVisible) {
                    return;
                }
                let totalWidth = 0;
                let selectedWidth = selected.outerWidth();
                this.tabs.getVisibleBeforeSelected().every(tab => {
                    totalWidth += tab.node.outerWidth();
                    if (totalWidth >= selectedWidth) {
                        if (!tab.pinned) {
                            selected.insertBefore(tab.node);
                            this.resize();
                            this.tabs.getAfterSelected().forEach(tab => tab.hide());
                            return false;
                        }
                    }
                    return true;
                });
            }
        }
        Manage.ModuleTabStrip = ModuleTabStrip;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripDraggable {
            constructor(options) {
                this.m_tabStrip = options.tabStrip;
                this.m_tabStripMenu = options.tabStripMenu;
                this.init();
            }
            get dragState() {
                return this.m_dragState;
            }
            get tabStrip() {
                return this.m_tabStrip;
            }
            get tabStripMenu() {
                return this.m_tabStripMenu;
            }
            get tabNodes() {
                return this.tabStrip.node.find(".-pdjs-manage-area-tab");
            }
            get tabsNode() {
                return this.tabStrip.tabsNode;
            }
            init() {
                this.m_dragState = new Manage.ModuleTabStripDraggableState({
                    tabStrip: this.tabStrip
                });
                this.tabNodes.draggable({
                    containment: this.tabsNode,
                    axis: "x",
                    distance: 10,
                    scroll: true,
                    helper: () => {
                        return `<div></div>`;
                    },
                    drag: _.throttle((e, ui) => {
                        this.drag(e, ui);
                    }, 10),
                    start: (e, ui) => {
                        this.start(e, ui);
                    },
                    stop: (e, ui) => {
                        this.stop(e, ui);
                    }
                });
            }
            createHelper(srcTab) {
                return $(`<div class="-pdjs-manage-area-tab-drag" style="width:${srcTab.outerWidth()}px;">${srcTab.find("div[role=label]").text()}</div>`);
            }
            drag(e, ui) {
                let state = this.dragState;
                this.dragState.refresh(e.pageX);
                if (state.cursorWasWithinDragTab) {
                    let canMoveLeft = (state.dragTabIsPinned && state.prevTabIsPinned) ||
                        (!state.dragTabIsPinned && !state.prevTabIsPinned);
                    let canMoveRight = (state.dragTabIsPinned && state.nextTabIsPinned) ||
                        (!state.dragTabIsPinned && !state.nextTabIsPinned);
                    if (state.cursorX < state.dragTabLeft && state.cusrorMovingLeft && canMoveLeft) {
                        state.dragTab.insertBefore(state.prevTab);
                        state.curosrShiftedOutsideDragTab = !state.cursorWithinDragTab;
                    }
                    else if (state.cursorX > state.dragTabRight && state.cusrorMovingRight && canMoveRight) {
                        state.dragTab.insertAfter(state.nextTab);
                        state.curosrShiftedOutsideDragTab = !state.cursorWithinDragTab;
                    }
                    state.cursorWasWithinDragTab = state.cursorWithinDragTab;
                }
                if (state.curosrShiftedOutsideDragTab) {
                    let hoverTabRect = state.hoverTabRect;
                    let canSkipTab = state.hoverTabExists &&
                        (state.dragTabIsPinned && state.hoverTabIsPinned) ||
                        (!state.dragTabIsPinned && !state.hoverTabIsPinned);
                    if (state.cusrorMovingLeft && state.hoverTabExists && state.hoverTab != state.nextTab && canSkipTab) {
                        if (state.cursorX <= hoverTabRect.left + (hoverTabRect.width / 2)) {
                            state.dragTab.insertBefore(state.hoverTab);
                            state.curosrShiftedOutsideDragTab = !state.cursorWithinDragTab;
                            return;
                        }
                    }
                    if (state.cusrorMovingRight && state.hoverTabExists && state.hoverTab != state.prevTab && canSkipTab) {
                        if (state.cursorX > hoverTabRect.right - (hoverTabRect.width / 2)) {
                            state.dragTab.insertAfter(state.hoverTab);
                            state.curosrShiftedOutsideDragTab = !state.cursorWithinDragTab;
                            return;
                        }
                    }
                }
                state.cursorWasWithinDragTab = state.cursorWithinDragTab;
            }
            start(e, ui) {
                let state = this.dragState;
                let srcTab = $(e.target);
                let dragHelper = this.createHelper(srcTab);
                this.tabNodes.addClass("-pdjs-no-hover");
                srcTab.addClass("-pdjs-dragging");
                dragHelper.addClass("-pdjs-manage-area-tab-drag");
                if (srcTab.hasClass("-pdjs-selected")) {
                    dragHelper.addClass("-pdjs-selected");
                }
                if (srcTab.hasClass("-pdjs-pinned")) {
                    dragHelper.addClass("-pdjs-pinned");
                }
                dragHelper.insertBefore(srcTab);
                state.cursorWasWithinDragTab = true;
                this.dragState.refresh(e.pageX);
            }
            stop(e, ui) {
                let state = this.dragState;
                let srcTab = $(e.target);
                srcTab.removeClass("-pdjs-dragging");
                srcTab.insertBefore(state.dragTab);
                state.dragTab.remove();
                this.tabNodes.removeClass("-pdjs-no-hover");
                this.tabStripMenu.update();
                state.curosrShiftedOutsideDragTab = false;
            }
        }
        Manage.ModuleTabStripDraggable = ModuleTabStripDraggable;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripDraggableState {
            constructor(options) {
                this.m_tabStrip = options.tabStrip;
            }
            get cursorX() {
                return this.m_cursorX || 0;
            }
            set cursorX(value) {
                this.m_cursorX = value;
            }
            get cursorPreviousX() {
                return this.m_cursorPreviousX || 0;
            }
            set cursorPreviousX(value) {
                this.m_cursorPreviousX = value;
            }
            get cursorWithinDragTab() {
                var _a, _b;
                return this.cursorX >= Math.floor(((_a = this.dragTabRect) === null || _a === void 0 ? void 0 : _a.left) || 0) &&
                    this.cursorX <= Math.ceil(((_b = this.dragTabRect) === null || _b === void 0 ? void 0 : _b.right) || 0);
            }
            get cursorWasWithinDragTab() {
                return this.m_cursorWasWithinDragTab;
            }
            set cursorWasWithinDragTab(value) {
                this.m_cursorWasWithinDragTab = value;
            }
            get cusrorMovingLeft() {
                return this.cursorX < this.cursorPreviousX;
            }
            get cusrorMovingRight() {
                return this.cursorX > this.cursorPreviousX;
            }
            get dragTab() {
                return this.tabsNode.find(".-pdjs-manage-area-tab-drag");
            }
            get dragTabLeft() {
                var _a;
                return (_a = this.dragTabRect) === null || _a === void 0 ? void 0 : _a.left;
            }
            get dragTabRight() {
                var _a;
                return (_a = this.dragTabRect) === null || _a === void 0 ? void 0 : _a.right;
            }
            get dragTabRect() {
                var _a;
                return (_a = this.dragTab.get(0)) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
            }
            get dragTabIsPinned() {
                return this.dragTab.hasClass("-pdjs-pinned");
            }
            get hoverTab() {
                return this.getHoverTab();
            }
            get hoverTabRect() {
                var _a, _b;
                return (_b = (_a = this.hoverTab) === null || _a === void 0 ? void 0 : _a.get(0)) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect();
            }
            get hoverTabExists() {
                return this.hoverTabRect != null;
            }
            get hoverTabIsPinned() {
                return this.prevTab.hasClass("-pdjs-pinned");
            }
            get nextTab() {
                return this.dragTab.nextAll(".-pdjs-manage-area-tab:not(.-pdjs-dragging)").first();
            }
            get nextTabExists() {
                return this.nextTabRect != null;
            }
            get nextTabRect() {
                var _a;
                return (_a = this.nextTab.get(0)) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
            }
            get nextTabLeft() {
                var _a;
                return (_a = this.nextTabRect) === null || _a === void 0 ? void 0 : _a.left;
            }
            get nextTabIsPinned() {
                return this.nextTab.hasClass("-pdjs-pinned");
            }
            get prevTab() {
                return this.dragTab.prevAll(".-pdjs-manage-area-tab:not(.-pdjs-dragging)").first();
            }
            get prevTabExists() {
                return this.prevTabRect != null;
            }
            get prevTabRect() {
                var _a;
                return (_a = this.prevTab.get(0)) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
            }
            get prevTabRight() {
                var _a;
                return (_a = this.prevTabRect) === null || _a === void 0 ? void 0 : _a.right;
            }
            get prevTabIsPinned() {
                return this.prevTab.hasClass("-pdjs-pinned");
            }
            get curosrShiftedOutsideDragTab() {
                return this.m_curosrShiftedOutsideDragTab;
            }
            set curosrShiftedOutsideDragTab(value) {
                this.m_curosrShiftedOutsideDragTab = value;
            }
            get tabStrip() {
                return this.m_tabStrip;
            }
            get tabsNode() {
                return this.tabStrip.tabsNode;
            }
            refresh(cursorX) {
                this.cursorPreviousX = this.cursorX;
                this.cursorX = cursorX;
            }
            getHoverTab() {
                let result = null;
                let nodes = this.tabStrip.tabsNode
                    .find(".-pdjs-manage-area-tab, .-pdjs-manage-area-tab-drag");
                let nodesCount = nodes.length;
                nodes.each((index, element) => {
                    let node = $(element);
                    let rect = element.getBoundingClientRect();
                    let first = index === 0;
                    let last = index === nodesCount;
                    if (first && this.cursorX <= rect.right) {
                        result = node;
                        return false;
                    }
                    if (last && this.cursorX >= rect.left) {
                        result = node;
                        return false;
                    }
                    if (this.cursorX >= rect.left && this.cursorX <= rect.right) {
                        result = node;
                        return false;
                    }
                });
                return result;
            }
        }
        Manage.ModuleTabStripDraggableState = ModuleTabStripDraggableState;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripMenu extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_hideOnIframeClick = null;
                    }
                    get anchor() {
                        return this.state.get("$anchor");
                    }
                    get bodyNode() {
                        return $("BODY");
                    }
                    get itemClickCallback() {
                        return this.state.get("itemClick");
                    }
                    get itemCreateCallback() {
                        return this.state.get("itemCreate");
                    }
                    get items() {
                        return this.getItems();
                    }
                    get clickCallback() {
                        return this.state.get("click", () => { });
                    }
                    get tabStrip() {
                        return this.state.get("$tabStrip");
                    }
                    get visible() {
                        return this.node.is(":visible");
                    }
                    get hideOnClickOutside() {
                        return this.state.get("hideOnClickOutside", true);
                    }
                    set hideOnClickOutside(value) {
                        this.state.set("hideOnClickOutside", value);
                    }
                    hide() {
                        this.node.hide();
                    }
                    select(value) {
                        this.clearSelectedItems();
                        this.items.each(item => {
                            if (item.binding.value == value) {
                                item.selected = true;
                            }
                        });
                    }
                    show() {
                        this.createMenuItems();
                        this.node.show();
                        this.positionMenu();
                    }
                    template(contents = "") {
                        return `<div class="-pdjs-tabstrip-menu">${contents || ""}</div>`;
                    }
                    addMenuItem(item) {
                        this.controls.add(item);
                    }
                    clearMenuItems() {
                        let items = this.items.toArray();
                        items.forEach(item => {
                            this.controls.remove(item);
                        });
                    }
                    createMenuItem(tab) {
                        let options = _.extend({
                            $tabStrip: this.tabStrip,
                            $menu: this,
                            binding: this.tabStrip.binding,
                        }, tab.toJSON());
                        options.click = (e) => {
                            this.onMenuItemClick(e);
                        };
                        return this.itemCreateCallback(options);
                    }
                    hideOnIframeClick(e) {
                        setTimeout(() => {
                            document.activeElement.tagName === "IFRAME" ? this.hide() : null;
                        });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_hideOnIframeClick = (e) => {
                            this.hideOnIframeClick(e);
                        };
                        window.addEventListener("blur", this.m_hideOnIframeClick);
                        this.hideOnClickOutsideOn();
                        this.anchor.hideMenu();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.node.detach();
                        this.bodyNode.append(this.node);
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        this.hideOnClickOutsideOff();
                        window.removeEventListener("blur", this.m_hideOnIframeClick);
                    }
                    getItems() {
                        return this.controls.getByType(Controls.TabStripMenuItemBase);
                    }
                    clearSelectedItems() {
                        this.items.each(tab => {
                            tab.selected = false;
                        });
                    }
                    createMenuItems() {
                        this.clearMenuItems();
                        this.tabStrip.tabs.all.forEach(tab => {
                            let item = this.createMenuItem(tab);
                            if (item != null) {
                                this.addMenuItem(item);
                            }
                        });
                    }
                    hideOnClickOutsideOn() {
                        this.bodyNode.on(`${Jade.BrowserEvent.CLICK}.${this.ID}`, (e) => {
                            if (this.hideOnClickOutside && this.visible) {
                                let notClickedInMenu = $(e.target)
                                    .closest(`#${this.ID}`).length === 0;
                                let notClickedInMenuButton = $(e.target)
                                    .closest(`#${this.anchor.ID}`).length === 0;
                                if (notClickedInMenu && notClickedInMenuButton) {
                                    this.anchor.hideMenu();
                                }
                            }
                        });
                    }
                    hideOnClickOutsideOff() {
                        $("body").off(`${Jade.BrowserEvent.CLICK}.${this.ID}`);
                    }
                    positionMenu() {
                        let rect = this.anchor.node.parent()
                            .get(0).getBoundingClientRect();
                        this.node.css({
                            top: rect.top + rect.height
                        });
                    }
                    onMenuItemClick(item) {
                        let args = new Controls.TabStripMenuItemClickEventArgs(item);
                        item.click(args);
                        if (!args.cancel) {
                            this.itemClickCallback(args);
                        }
                        if (!args.cancel) {
                            this.clickCallback(args);
                        }
                        if (!args.cancel) {
                            this.select(item.value);
                        }
                    }
                }
                Controls.TabStripMenu = TabStripMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripMenu extends PDJS.Shared.UI.Controls.TabStripMenu {
            get sortButtonNode() {
                return this.node.find("div[role=sort] > button");
            }
            get isSortApplied() {
                return this.sortButtonNode.hasClass("-pdjs-selected");
            }
            update() {
                this.applyFilter(this.m_filter.textValue);
            }
            show() {
                super.show();
                this.update();
            }
            template() {
                return super.template(`
                        <div role="root">
                            <div role="toolbar">
                                <div role="sort">
                                    <button><i class="icofont-font"></i></button>
                                </div>
                                <div role="filter">
                            
                                </div>
                            </div>
                            <div role="items" data-controls></div>
                        </div>`);
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.addClass("-pdjs-manage-area-tabstrip-menu");
                this.filter_init();
                this.sortButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.sortButtonNode_onClick();
                });
                this.setSortButtonToolTip();
                this.hideOnClickOutside = true;
                PDJS.Manage.ModuleEventsHub.moduleCreatedSubscribe((e) => {
                    e.module.subscribe.loaded((e) => {
                        setTimeout(() => {
                            this.applyFilter(this.m_filter.textValue);
                        }, 50);
                    });
                });
            }
            onComplete(e) {
                super.onComplete(e);
                this.applyFilter(this.m_filter.textValue);
            }
            filter_init() {
                this.m_filter = new PDJS.Shared.UI.Controls.SearchBox({
                    insertAt: "div[role=filter]",
                    defaultMaskText: "Filter open items...",
                    searchOnEnter: false,
                    onSearch: (e) => {
                        var _a;
                        this.applyFilter((_a = e.term) === null || _a === void 0 ? void 0 : _a.toLowerCase());
                    }
                });
                this.controls.add(this.m_filter);
            }
            applyFilter(term) {
                this.removeMessage();
                let isEmptyTerm = Jade.String.isNullOrWhiteSpace(term);
                if (isEmptyTerm) {
                    term = "";
                }
                term = term.toLowerCase();
                this.clearMenuItems();
                let tabs = [];
                this.tabStrip.tabs.all.forEach(tab => {
                    if (tab.binding.text.toLowerCase().indexOf(term) > -1 || isEmptyTerm) {
                        tabs.push(tab);
                    }
                });
                if (this.isSortApplied) {
                    this.sortTabs(tabs);
                }
                this.addMenuItems(tabs);
                if (this.tabStrip.tabs.all.length == 0) {
                    this.addMessage("No items are open.");
                    return;
                }
                if (tabs.length == 0) {
                    this.addMessage(`No loaded items match the filter "${this.m_filter.textValue}"`);
                    return;
                }
            }
            sortButtonNode_onClick() {
                this.clearMenuItems();
                this.isSortApplied ?
                    this.sortButtonNode.removeClass("-pdjs-selected") :
                    this.sortButtonNode.addClass("-pdjs-selected");
                this.setSortButtonToolTip();
                let tabs = this.tabStrip.tabs.all;
                if (this.isSortApplied) {
                    this.sortTabs(tabs);
                }
                this.addMenuItems(tabs);
            }
            sortTabs(items) {
                items.sort((a, b) => {
                    let aText = a.binding.text.toLowerCase();
                    let bText = b.binding.text.toLowerCase();
                    if (aText < bText) {
                        return -1;
                    }
                    if (aText > bText) {
                        return 1;
                    }
                    return 0;
                });
            }
            addMenuItems(items) {
                items.forEach(item => {
                    this.controls.add(this.createMenuItem(item));
                });
            }
            setSortButtonToolTip() {
                this.isSortApplied ?
                    this.sortButtonNode.attr("title", "Remove alphabetical sort") :
                    this.sortButtonNode.attr("title", "Apply alphabetical sort");
            }
            addMessage(text) {
                this.removeMessage();
                let message = new PDJS.Shared.UI.Controls.Message({
                    message: text,
                    backgroundColor: "var(--visiv-theme-base-1-back-color)",
                    textColor: "var(--visiv-theme-base-1-text-color)"
                });
                this.controls.add(message);
                message.node.css({
                    position: "absolute",
                    inset: 0
                });
            }
            removeMessage() {
                let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                if (message != null) {
                    this.controls.remove(message);
                }
            }
        }
        Manage.ModuleTabStripMenu = ModuleTabStripMenu;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get tabStrip() {
                        return this.state.get("$tabStrip");
                    }
                    get binding() {
                        this.ensureBinding();
                        return this.m_binding;
                    }
                    get selected() {
                        return this.node.hasClass("-pdjs-selected");
                    }
                    set selected(value) {
                        this.setSelected(value);
                    }
                    get clickCallback() {
                        return this.state.get("click", () => { });
                    }
                    get value() {
                        return this.binding.value;
                    }
                    click(e) {
                    }
                    template(content) {
                        return `<a data-uid="${this.ID}" class="-pdjs-tabstrip-item">${content}</a>`;
                    }
                    toJSON() {
                        return _.extend({
                            binding: this.binding.map
                        }, this.state.toJSON());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, () => {
                            this.clickCallback(this);
                        });
                        this.setSelected(this.state.get("selected"));
                    }
                    setSelected(value) {
                        value === true ?
                            this.node.addClass("-pdjs-selected") :
                            this.node.removeClass("-pdjs-selected");
                    }
                    ensureBinding() {
                        if (this.m_binding == null) {
                            this.m_binding = new Controls.TabStripItemBinding({
                                defaults: this.state.get("binding"),
                                state: this.state
                            });
                        }
                    }
                }
                Controls.TabStripItem = TabStripItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripMenuItemBase extends Controls.TabStripItem {
                    constructor(options) {
                        super(options);
                    }
                    get menu() {
                        return this.state.get("$menu");
                    }
                    template(content) {
                        return super.template(content);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-pdjs-tabstrip-menu-item");
                    }
                }
                Controls.TabStripMenuItemBase = TabStripMenuItemBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripMenuItem extends PDJS.Shared.UI.Controls.TabStripMenuItemBase {
            constructor(options) {
                super(options);
            }
            get changeNode() {
                return this.gridNode.children("div[role=change]");
            }
            get closeNode() {
                return this.gridNode.find("div[role=close] > i");
            }
            get gridNode() {
                return this.node.children("div[role=grid]");
            }
            get indicatorNode() {
                return this.changeNode.children("div[role=indicator]");
            }
            get labelNode() {
                return this.gridNode.children("div[role=label]");
            }
            get module() {
                return this.state.get("$module");
            }
            template() {
                return super.template(`
                <div role="grid">
                    <div role="change">
                        <div role="indicator"></div>
                    </div>
                    <div role="label">${this.module.settings.label}</div>
                    <div role="close">
                        <i class="icofont-close"></i>
                    </div>
                </div>`);
            }
            toJSON() {
                return _.extend(super.toJSON(), {
                    $module: this.module
                });
            }
            onActivate(e) {
                super.onActivate(e);
                this.moduleEventsSubscribe();
                this.closeNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    this.onMenuItemClose();
                });
                this.binding.setValue("value", this.module.settings.route);
                this.binding.setValue("text", this.module.settings.label);
                this.module.settings.hasChanges ?
                    this.indicatorNode.show() :
                    this.indicatorNode.hide();
                this.node.addClass("-pdjs-manage-area-menu-item");
            }
            onStateChanged() {
                this.labelNode.empty();
                this.labelNode.text(this.module.settings.label);
                this.module.settings.hasChanges ?
                    this.indicatorNode.show() :
                    this.indicatorNode.hide();
            }
            onMenuItemClose() {
                new Manage.UnloadModuleCommand().execute({
                    module: this.module,
                    tabStrip: this.tabStrip
                });
            }
            onModuleUnloadComplete() {
                if (this.menu instanceof Manage.ModuleTabStripMenu) {
                    this.menu.controls.remove(this);
                    this.menu.update();
                }
            }
            moduleEventsSubscribe() {
                this.subscriptions.add(this.module.subscribe.change((e) => {
                    this.onStateChanged();
                }));
                this.subscriptions.add(this.module.subscribe.unloaded((e) => {
                    this.onModuleUnloadComplete();
                }));
            }
        }
        Manage.ModuleTabStripMenuItem = ModuleTabStripMenuItem;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripTabBase extends Controls.TabStripItem {
                    constructor(options) {
                        super(options);
                    }
                    get visible() {
                        return !!(this.node.get(0).offsetWidth ||
                            this.node.get(0).offsetHeight ||
                            this.node.get(0).getClientRects().length);
                    }
                    hide() {
                        this.node.addClass("-pdjs-hidden");
                    }
                    show() {
                        this.node.removeClass("-pdjs-hidden");
                    }
                    template(content) {
                        return super.template(content);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-pdjs-tabstrip-tab");
                    }
                }
                Controls.TabStripTabBase = TabStripTabBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripTab extends PDJS.Shared.UI.Controls.TabStripTabBase {
            constructor(options) {
                super(options);
            }
            get module() {
                return this.state.get("$module");
            }
            set module(value) {
                this.state.set("$module", value);
            }
            get gridNode() {
                return this.node.children("div[role=grid]");
            }
            get changeNode() {
                return this.gridNode.children("div[role=change]");
            }
            get closeNode() {
                return this.gridNode.find("div[role=close] > i");
            }
            get indicatorNode() {
                return this.changeNode.children("div[role=indicator]");
            }
            get labelNode() {
                return this.gridNode.children("div[role=label]");
            }
            get menuNode() {
                return this.gridNode.children("div[role=menu]");
            }
            get pinNode() {
                return this.gridNode.find("div[role=pin] > i");
            }
            get pinned() {
                return this.node.hasClass("-pdjs-pinned");
            }
            template() {
                return super.template(`
                <div role="grid">
                    <div role="menu">
                        <i class="icofont-caret-down"></i>
                    </div>
                    <div role="change">
                        <div role="indicator"></div>
                    </div>
                    <div role="label"></div>
                    <div role="pin">
                        <i class="icofont-tack-pin"></i>
                    </div>
                    <div role="close">
                        <i class="icofont-close"></i>
                    </div>
                </div>`);
            }
            toJSON() {
                return _.extend(super.toJSON(), {
                    $module: this.module
                });
            }
            onActivate(e) {
                super.onActivate(e);
                this.contextMenu_init();
                this.labelNode.html(PDJS.Shared.Spinner.toHtml({
                    text: "Loading...",
                    color: "var(--visiv-theme-base-1-text-color",
                    size: 12
                }));
                this.closeNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    new Manage.UnloadModuleCommand().execute({
                        module: this.module,
                        tabStrip: this.tabStrip
                    });
                    e.stopPropagation();
                    e.preventDefault();
                    e.returnValue = false;
                    return false;
                });
                this.pinNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.onTabPinned(e);
                    e.stopPropagation();
                    e.preventDefault();
                    e.returnValue = false;
                    return false;
                });
                this.menuNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    e.returnValue = false;
                    return false;
                });
                this.module.subscribe.focus((e) => {
                    this.clickCallback(this);
                });
                this.module.subscribe.change((e) => {
                    this.onStateChanged();
                });
                this.module.subscribe.unloaded((e) => {
                    this.onModuleUnloadComplete();
                });
                this.node.addClass("-pdjs-manage-area-tab");
                this.binding.setValue("value", this.module.settings.route);
                this.binding.setValue("text", this.module.settings.label);
                this.module.settings.hasChanges ?
                    this.indicatorNode.show() :
                    this.indicatorNode.hide();
            }
            onStateChanged() {
                var _a;
                if (((_a = this.module) === null || _a === void 0 ? void 0 : _a.settings) == null) {
                    return;
                }
                this.labelNode.empty();
                this.labelNode.text(this.module.settings.label);
                this.binding.setValue("text", this.module.settings.label);
                this.binding.setValue("value", this.module.settings.route);
                this.module.settings.hasChanges ?
                    this.indicatorNode.show() :
                    this.indicatorNode.hide();
            }
            contextMenu_init() {
                let menu = new PDJS.Shared.UI.Controls.ContextMenu({
                    anchor: this.menuNode,
                    segments: [new Manage.ModuleTabStripTabMenu()],
                    width: 200,
                    show: () => {
                        return {
                            module: this.module,
                            tabStrip: (this.tabStrip)
                        };
                    },
                    options: {
                        showOn: "click",
                        offset: {
                            y: -3,
                            x: -6
                        }
                    }
                });
                this.controls.add(menu);
            }
            onModuleUnloadComplete() {
                this.tabStrip.controls.remove(this);
            }
            onTabPinned(e) {
                let tabStrip = this.tabStrip;
                let isPinned = this.node.hasClass("-pdjs-pinned");
                if (isPinned) {
                    tabStrip.unpin(this.ID);
                    this.module.settings.pinned = false;
                    this.node.removeClass("-pdjs-pinned");
                    tabStrip.refreshMenu();
                    return;
                }
                if (!isPinned) {
                    tabStrip.pin(this.ID);
                    this.module.settings.pinned = true;
                    this.node.addClass("-pdjs-pinned");
                    tabStrip.refreshMenu();
                    return;
                }
            }
        }
        Manage.ModuleTabStripTab = ModuleTabStripTab;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class ModuleTabStripTabMenu extends PDJS.Shared.UI.Controls.ContextMenuSegment {
            get module() {
                return this.m_module;
            }
            set module(value) {
                this.m_module = value;
            }
            get tabStrip() {
                return this.m_tabStrip;
            }
            set tabStrip(value) {
                this.m_tabStrip = value;
            }
            onMenuShow(e) {
                this.module = e.data.module;
                this.tabStrip = e.data.tabStrip;
            }
            onAddMenuItems(e) {
                super.onAddMenuItems(e);
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "open-in-new-window",
                    label: "Open In New Window",
                    select: (item) => {
                        window.open(Jade.Path.resolve(`~/Manage/${this.module.settings.route}`));
                    }
                }));
                e.addSeparator();
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "close",
                    label: "Close",
                    select: (item) => {
                        new Manage.UnloadModuleCommand().execute({
                            module: this.module,
                            tabStrip: this.tabStrip
                        });
                    }
                }));
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "close-all",
                    label: "Close All",
                    select: (item) => {
                        new Manage.UnloadModulesCommand().execute({
                            tabStrip: this.tabStrip,
                            clear: "all"
                        });
                    },
                    show: (e) => {
                        e.item.enabled = PDJS.Manage.Modules.instance.modules.count > 1;
                    }
                }));
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "close-all-but-this",
                    label: "Close All But This",
                    select: (item) => {
                        new Manage.UnloadModulesCommand().execute({
                            tabStrip: this.tabStrip,
                            clear: "all",
                            target: this.module
                        });
                    },
                    show: (e) => {
                        e.item.enabled = PDJS.Manage.Modules.instance.modules.count > 1;
                    }
                }));
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "close-all-but-pinned",
                    label: "Close All But Pinned",
                    select: (item) => {
                        new Manage.UnloadModulesCommand().execute({
                            tabStrip: this.tabStrip,
                            clear: "unpinned",
                            target: this.module
                        });
                    }
                }));
                e.addSeparator();
                e.addItem(new PDJS.Shared.UI.Controls.ContextMenuItem({
                    value: "pin",
                    label: "Add to Quick Access",
                    icon: "star.png",
                    iconSet: "pdjs",
                    select: (item) => {
                        let service = new PDJS.Services.Personalization.QuickAccessService();
                        service.add({
                            name: this.module.settings.label,
                            route: this.module.settings.route,
                            success: (e) => {
                                PDJS.Shared.MessageStack.instance.success(`"${this.module.settings.label}" added to quick access.`);
                            }
                        });
                    }
                }));
            }
        }
        Manage.ModuleTabStripTabMenu = ModuleTabStripTabMenu;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class ActionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get splitter() {
                    return this.m_splitter;
                }
                get splitterNode() {
                    return this.node.find("div[data-role=splitter]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get originalAction() {
                    return this.state.get("originalAction", {
                        id: null, pluginId: null
                    });
                }
                onResize() {
                    if (this.m_splitter) {
                        this.m_splitter.resize();
                    }
                }
                template() {
                    return super.template(`
                <div class="-pdjs-fb-action-dialog">
                    <div data-role="content">
                        <div data-role="splitter">
                            <div data-role="pane1"></div>
                            <div data-role="pane2"></div>
                        </div>
                    </div>
                    <div data-role="deck">
                        <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    var _a;
                    super.onActivate(e);
                    this.splitter_init();
                    this.content_init();
                    this.plugins_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                        this.okButton_onClick();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                        this.cancelButton_onClick();
                    });
                    this.m_plugins.selectedPluginId = (_a = this.originalAction) === null || _a === void 0 ? void 0 : _a.pluginId;
                }
                onComplete(e) {
                    var _a;
                    super.onComplete(e);
                    if ((_a = this.originalAction) === null || _a === void 0 ? void 0 : _a.pluginId) {
                        this.m_plugins.select(this.originalAction.pluginId);
                    }
                    else {
                        this.m_plugins.select(_.first(PDJS.Shared.Plugins.PluginManager.instance.getPlugins()).id);
                    }
                }
                getDefaultOptions() {
                    return {
                        title: "Action Editor",
                        height: 500,
                        width: 700
                    };
                }
                splitter_init() {
                    this.m_splitter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "200px" },
                            { resizable: true }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                plugins_init() {
                    this.m_plugins = new Actions.PluginList({
                        insertAt: "div[data-role=pane1]",
                        change: (e) => {
                            if (e != null) {
                                this.m_content.load({
                                    plugin: e,
                                    action: this.originalAction
                                });
                            }
                        }
                    });
                    this.controls.add(this.m_plugins);
                }
                content_init() {
                    this.m_content = new Actions.PluginContent({
                        insertAt: "div[data-role=pane2]"
                    });
                    this.controls.add(this.m_content);
                }
                okButton_onClick() {
                    this.m_content.save({
                        commitSuccess: (e) => {
                            this.close({
                                name: "ok",
                                data: e
                            });
                        }
                    });
                }
                cancelButton_onClick() {
                    this.close();
                }
                static open(options) {
                    return new ActionDialog(options);
                }
            }
            Actions.ActionDialog = ActionDialog;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class ActionEditor extends Jade.UI.Control {
                load(plugin, action) {
                    if ((action === null || action === void 0 ? void 0 : action.id) == null) {
                        this.showMessage(plugin.name);
                        return;
                    }
                    this.hideMessage();
                    this.loadEditor(action);
                }
                save(args) {
                    let successFn = (args.commitSuccess || (() => { }));
                    this.m_editor.commit({
                        success: (e) => {
                            successFn(e.target);
                        }
                    });
                }
                template() {
                    return `<div class="-pdjs-fb-action-dialog-action-editor"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Features.FeatureEditor({
                        layoutType: FeatureBlendJS.Views.FeatureBlendLayoutType.Simple
                    });
                    this.controls.add(this.m_editor);
                }
                loadEditor(args) {
                    if (!this.isArbiterSpecified(args)) {
                        this.applyArbiterSettings(args);
                    }
                    if (!this.isArbiterSpecified(args)) {
                    }
                    this.m_editor.load({
                        "initialized": false,
                        "arbiter": {
                            json: JSON.stringify(args),
                            type: args.targetArbiter,
                            targetType: args.targetType
                        }
                    });
                }
                applyArbiterSettings(args) {
                    let plugin = PDJS.Shared.Plugins.PluginManager.instance.getPlugin(args.pluginId);
                    if (plugin == null) {
                        return;
                    }
                    let action = plugin.actions.getActionDefinitionById(args.id);
                    if (action == null) {
                        return;
                    }
                    args.targetArbiter = action.targetArbiter;
                    args.targetType = action.targetType;
                }
                isArbiterSpecified(args) {
                    return args.targetArbiter != null && args.targetType != null;
                }
                showMessage(pluginName) {
                    this.hideMessage();
                    let text = pluginName != null ?
                        `Select an action to edit from <b>${pluginName}</b>.` :
                        `Select an action to edit.`;
                    let message = new PDJS.Shared.UI.Controls.Message({
                        message: text,
                        borderWidth: 1
                    });
                    this.controls.add(message);
                }
                hideMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                    }
                }
            }
            Actions.ActionEditor = ActionEditor;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class ActionList extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get plugin() {
                    this.ensurePlugin();
                    return this.m_plugin;
                }
                set plugin(value) {
                    this.m_plugin = value;
                }
                get pluginData() {
                    return this.state.get("pluginData");
                }
                set pluginData(value) {
                    this.state.set("pluginData", value);
                }
                get originalAction() {
                    return this.state.get("originalAction", {});
                }
                set originalAction(value) {
                    this.state.set("originalAction", value);
                }
                get actionData() {
                    this.ensureActionData();
                    return this.m_actionData;
                }
                set actionData(value) {
                    this.m_actionData = value;
                }
                get selectNode() {
                    return this.node.find("select");
                }
                load(args) {
                    this.clear();
                    this.pluginData = args.plugin;
                    this.originalAction = args.action;
                    this.list_init();
                }
                template() {
                    return `<div class="-pdjs-fb-action-dialog-action-list">
                        <select></select>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                        let id = this.selectNode.val();
                        let result = null;
                        this.actionData.forEach(item => {
                            if (item.id === id) {
                                result = item;
                            }
                        });
                        this.changeCallback(result);
                    });
                }
                clear() {
                    this.actionData = null;
                    this.originalAction = null;
                    this.plugin = null;
                    this.pluginData = null;
                }
                list_init() {
                    this.selectNode.empty();
                    this.selectNode.append(`<option>Select action...</option>`);
                    this.actionData.forEach(item => {
                        let isSelected = item.id == this.originalAction.id;
                        this.selectNode.append(`<option value="${item.id}" ${isSelected ? "selected" : ""}>${item.name}</option>`);
                    });
                }
                ensurePlugin() {
                    var _a;
                    if (this.m_plugin == null) {
                        this.m_plugin = PDJS.Shared.Plugins.PluginManager
                            .instance.getPlugin((_a = this.pluginData) === null || _a === void 0 ? void 0 : _a.id);
                    }
                }
                ensureActionData() {
                    if (this.plugin != null && this.m_actionData == null) {
                        this.actionData = _.map(this.plugin.actions.getActionDefinitions(), (action) => {
                            return action.toJSON();
                        });
                        ;
                    }
                }
            }
            Actions.ActionList = ActionList;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxListItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get data() {
                        return this.state.get("data", {});
                    }
                    get uid() {
                        return this.resolveMap(this.uidMap);
                    }
                    get uidMap() {
                        return this.state.get("uidMap", "uid");
                    }
                    get label() {
                        return this.resolveMap(this.labelMap);
                    }
                    get labelMap() {
                        return this.state.get("labelMap", "label");
                    }
                    get icon() {
                        return this.resolveMap(this.iconMap);
                    }
                    get iconMap() {
                        return this.state.get("iconMap", "icon");
                    }
                    template() {
                        let result = $(`<div data-role="item" data-id="${this.uid}" title="${this.label}" class="-pdjs-combo-box-pop-up-item">${this.label}</div>`);
                        if (this.icon != null) {
                            result.css({
                                paddingLeft: "25px",
                                backgroundImage: `url(${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                        }
                        return result;
                    }
                    resolveMap(id, defaultValue) {
                        return this.state.get(`data.${id}`, defaultValue);
                    }
                }
                Controls.ComboBoxListItem = ComboBoxListItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class SingleSelectListItem extends Controls.ComboBoxListItem {
                }
                Controls.SingleSelectListItem = SingleSelectListItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class ActionListItem extends PDJS.Shared.UI.Controls.ComboBoxListItem {
                get description() {
                    return this.resolveMap("description", "");
                }
                template() {
                    let template = `<div data-role="item" 
                                        data-id="${this.uid}" title="${this.label}"
                                        class="-pdjs-combo-box-pop-up-item"
                                        style="line-height:16px;padding:5px;min-height:42px;">
                                            <b>${this.label}</b><br/>
                                            ${this.description}
                                    </div>`;
                    let result = $(template);
                    if (this.icon != null) {
                        result.css({
                            paddingLeft: "40px",
                            backgroundPosition: "3px 4px",
                            backgroundRepeat: "no-repeat",
                            backgroundImage: `url(${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x32)})`
                        });
                    }
                    return result;
                }
            }
            Actions.ActionListItem = ActionListItem;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class PluginContent extends Jade.UI.Control {
                get plugin() {
                    return this.state.get("plugin");
                }
                set plugin(value) {
                    this.state.set("plugin", value);
                }
                load(args) {
                    var _a;
                    this.plugin = args.plugin;
                    if (this.plugin == null) {
                        this.showMessage();
                    }
                    this.m_action.load({
                        action: args.action,
                        plugin: args.plugin
                    });
                    if (args.plugin.id === ((_a = args.action) === null || _a === void 0 ? void 0 : _a.pluginId)) {
                        this.m_editor.load(this.plugin, args.action);
                    }
                    else {
                        this.m_editor.load(this.plugin);
                    }
                }
                save(args) {
                    let successFn = (args.commitSuccess || (() => { }));
                    this.m_editor.save({
                        commitSuccess: (e) => {
                            successFn(e);
                        }
                    });
                }
                template() {
                    return `<div class="-pdjs-fb-action-dialog-plugin-content">
                        <div role="action"></div>
                        <div role="editor"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.action_init();
                    this.editor_init();
                }
                editor_init() {
                    this.m_editor = new Actions.ActionEditor({
                        insertAt: "div[role=editor]"
                    });
                    this.controls.add(this.m_editor);
                }
                action_init() {
                    this.m_action = new Actions.ActionList({
                        insertAt: "div[role=action]",
                        change: (e) => {
                            this.m_editor.load(this.plugin, e);
                        }
                    });
                    this.controls.add(this.m_action);
                }
                showMessage() {
                    this.hideMessage();
                    let message = new PDJS.Shared.UI.Controls.Message({
                        message: `Select a plugin to list available actions.`,
                        borderWidth: 1
                    });
                    this.controls.add(message);
                    message.node.css({
                        position: "absolute",
                        inset: 0
                    });
                }
                hideMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                    }
                }
            }
            Actions.PluginContent = PluginContent;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class PluginList extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_plugins = [];
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selectedPluginId() {
                    return this.state.get("selectedPluginId", null);
                }
                set selectedPluginId(value) {
                    this.state.set("selectedPluginId", value);
                }
                template() {
                    return `<div class="-pdjs-fb-action-dialog-plugins-list"></div>`;
                }
                select(pluginId) {
                    if (pluginId) {
                        this.selectedPluginId = pluginId;
                        this.m_list.select([pluginId]);
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.loadPlugins();
                    this.list_init();
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        data: this.getPluginItems(),
                        binding: { value: "id", label: "label", icon: "icon" },
                        noItemsMessage: "No plugins found.",
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                        change: (e) => {
                            let item = e.first();
                            if (item != null) {
                                let plugin = this.m_plugins.find(plugin => {
                                    return plugin.id == item.data.value;
                                });
                                if (plugin != null) {
                                    this.changeCallback(plugin);
                                }
                            }
                        },
                        createItem: (item) => {
                            return new PDJS.Shared.UI.Controls.ListViewItem(item);
                        }
                    });
                    this.controls.add(this.m_list);
                }
                loadPlugins() {
                    var _a;
                    let plugins = PDJS.Shared.Plugins.PluginManager.instance.getPlugins();
                    plugins.forEach((plugin, index) => {
                        if (plugin.actions.hasActions) {
                            this.m_plugins.push(_.extend(plugin.toJSON(), { selected: index === 0 }));
                        }
                    });
                    this.selectedPluginId = (_a = _.first(this.m_plugins)) === null || _a === void 0 ? void 0 : _a.id;
                }
                getPluginItems() {
                    let plugins = this.m_plugins;
                    let data = [];
                    plugins.forEach((plugin) => {
                        data.push({
                            id: plugin.id,
                            label: plugin.name,
                            icon: "folder.png",
                            active: false,
                            selected: false,
                            visible: true
                        });
                    });
                    return data;
                }
            }
            Actions.PluginList = PluginList;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenu extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                }
                Controls.PanelMenu = PanelMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get tag() {
                    return this.state.get("tag");
                }
                set tag(value) {
                    this.state.set("tag", value);
                }
                load(tag) {
                    this.tag = tag;
                }
                template() {
                    return `<div class="-pdjs-manage-active-directory-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Users",
                        url: "#/module/users"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Groups",
                        url: "#/module/groups"
                    }));
                }
            }
            ActiveDirectory.ActiveDirectoryActions = ActiveDirectoryActions;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/active-directory": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            ActiveDirectory.ActiveDirectoryCommand = ActiveDirectoryCommand;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class DomainAddCommand extends ActiveDirectory.ActiveDirectoryCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "domain/new",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new domain.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Domain",
                        height: 500,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Security.SyncSettingsUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Security.SyncSettingsArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                this.grid.refresh({
                                    selections: [e.target.id],
                                    clear: true
                                });
                            }
                        }
                    });
                }
            }
            ActiveDirectory.DomainAddCommand = DomainAddCommand;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class DomainDeleteCommand extends ActiveDirectory.ActiveDirectoryCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "domain/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected domain.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Delete | Domain",
                        message: "Delete the selected domains?",
                        select: {
                            ok: (e) => {
                                e.close();
                                this.deleteDomain();
                            }
                        }
                    });
                }
                deleteDomain(confirmed = false) {
                    let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                    service.deleteDomain({
                        ids: this.selectedIds,
                        confirmed: confirmed,
                        success: (e) => {
                            e.data.requiresConfirmation ?
                                this.showInUseConfirmationDialog() :
                                this.grid.refresh({ clear: true });
                        }
                    });
                }
                showInUseConfirmationDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        title: "Delete Active Directory Synchroniztion",
                        message: `One or more user/group accounts make use of one the synchronization settings you have selected.<br/><br/>
                            Proceed with deletion?`,
                        select: {
                            yes: (sender, e) => {
                                sender.close();
                                this.deleteDomain(true);
                            }
                        }
                    });
                }
            }
            ActiveDirectory.DomainDeleteCommand = DomainDeleteCommand;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class DomainEditCommand extends ActiveDirectory.ActiveDirectoryCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "domain/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the properties of the selected domain.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${this.selection.name}`,
                        height: 500,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Security.SyncSettingsUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Security.SyncSettingsArbiter",
                            targetId: this.selection.id
                        },
                        select: {
                            ok: (sender, e) => {
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            ActiveDirectory.DomainEditCommand = DomainEditCommand;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/active-directory");
                }
                registerCommands(e) {
                    e.commands.add(new ActiveDirectory.DomainAddCommand());
                    e.commands.add(new ActiveDirectory.DomainDeleteCommand());
                    e.commands.add(new ActiveDirectory.DomainEditCommand());
                }
            }
            ActiveDirectory.ActiveDirectoryCommands = ActiveDirectoryCommands;
            Jade.CommandGroups.add(ActiveDirectoryCommands);
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-tags-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Domains</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new ActiveDirectory.TagsGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No domains."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/active-directory:domain/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.ActiveDirectory.ActiveDirectoryGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            ActiveDirectory.ActiveDirectoryGrid = ActiveDirectoryGrid;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/active-directory";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:domain/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:domain/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:domain/delete`
                    }));
                }
            }
            ActiveDirectory.ActiveDirectoryGridContextMenu = ActiveDirectoryGridContextMenu;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class TagsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/active-directory";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:domain/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:domain/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:domain/delete`
                    }));
                }
            }
            ActiveDirectory.TagsGridToolbar = TagsGridToolbar;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-tags">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new ActiveDirectory.ActiveDirectoryGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new ActiveDirectory.ActiveDirectoryActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/active-directory": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            ActiveDirectory.ActiveDirectoryModule = ActiveDirectoryModule;
        })(ActiveDirectory = Manage.ActiveDirectory || (Manage.ActiveDirectory = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Canvas;
        (function (Canvas) {
            class CanvasDirective extends PDJS.Manage.ModuleDirective {
                constructor(options) {
                    super(options);
                }
            }
            Canvas.CanvasDirective = CanvasDirective;
        })(Canvas = Manage.Canvas || (Manage.Canvas = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Canvas;
        (function (Canvas) {
            let Directives;
            (function (Directives) {
                Directives["HighlightElement"] = "HighlightElement";
            })(Directives = Canvas.Directives || (Canvas.Directives = {}));
            class CanvasDirectivesHub extends PDJS.Manage.ModuleDirectives {
                static get moduleId() {
                    return "canvas-editor";
                }
                static highlightElement(targetId, args) {
                    return this.execute(this.moduleId, targetId, Directives.HighlightElement, args);
                }
            }
            Canvas.CanvasDirectivesHub = CanvasDirectivesHub;
        })(Canvas = Manage.Canvas || (Manage.Canvas = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Canvas;
        (function (Canvas) {
            class CanvasModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get documentId() {
                    return this.settings.targetId;
                }
                get canvasType() {
                    return this.state.get("canvasType");
                }
                set canvasType(value) {
                    this.state.set("canvasType", value);
                }
                get entityTypeId() {
                    return this.settings.get("entityTypeId");
                }
                set entityTypeId(value) {
                    this.settings.set("entityTypeId", value);
                }
                get entityTypeName() {
                    return this.settings.get("entityTypeName");
                }
                set entityTypeName(value) {
                    this.settings.set("entityTypeName", value);
                }
                get canvasName() {
                    return this.settings.get("canvasName");
                }
                set canvasName(value) {
                    this.settings.set("canvasName", value);
                }
                template() {
                    return `<div class="${CanvasJS.Design.CanvasCss.Design}">`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addSubscribers();
                }
                onCreateContext(context) {
                    super.onCreateContext(context);
                    if (!context.tags.includes("canvas")) {
                        context.tags.push("canvas");
                    }
                }
                onInit(e) {
                    super.onInit(e);
                    this.m_documentService = new PDJS.Services.Canvas.DocumentService();
                }
                onModuleUnload(e) {
                    super.onModuleUnload(e);
                    e.addStep(() => this.closeModule());
                }
                onModuleCommit(e) {
                    super.onModuleCommit(e);
                    e.addStep(() => this.commitCanvas());
                }
                onModuleLoad(e) {
                    e.addStep(() => this.loadWorkspace());
                    e.addStep(() => this.loadDocument());
                    e.addStep(() => this.loadToolBox());
                }
                onRegisterDirectives() {
                    super.onRegisterDirectives();
                    this.directives.add(new Canvas.HighlightElement());
                }
                addSubscribers() {
                    this.subscriptions.add(Canvas.EventsHub.canvasRenamedSubscribe(e => {
                        if (this.settings.targetId == e.canvasId) {
                            this.canvasName = e.canvasName;
                            this.settings.label = `${this.entityTypeName} | ${this.canvasName}`;
                        }
                    }));
                    this.subscriptions.add(Manage.EntityType.EventsHub.entityTypeRenamedSubscribe(e => {
                        if (this.entityTypeId == e.entityTypeId) {
                            this.entityTypeName = e.entityTypeName;
                            this.settings.label = `${this.entityTypeName} | ${this.canvasName}`;
                        }
                    }));
                }
                loadWorkspace() {
                    return this.modulePromise((resolve, reject) => {
                        setTimeout(() => {
                            this.m_workspace = new CanvasJS.Design.Workspace({});
                            this.controls.add(this.m_workspace);
                            CanvasJS.Design.Environment.store.add("module", this);
                            CanvasJS.Design.Environment.statusBar.controls.add(new PDJS.Canvas.Design.StatusBar.Theme());
                            CanvasJS.Design.Environment.statusBar.controls.add(new PDJS.Canvas.Design.StatusBar.Errors({}));
                            this.loadHotKeys();
                            resolve();
                        }, 100);
                    });
                }
                loadToolBox() {
                    return this.modulePromise((resolve, reject) => {
                        setTimeout(() => {
                            let service = new PDJS.Services.Canvas.ToolBoxService();
                            let loadingMessage = new PDJS.Shared.UI.Controls.Message({
                                message: `<span style="font-size: 20px;">Loading Items...</span>`
                            });
                            CanvasJS.Design.Environment.toolBox.controls.add(loadingMessage);
                            service.load({
                                canvasType: this.canvasType,
                                success: (e) => {
                                    CanvasJS.Design.Environment.toolBox.loadToolBoxItems(e.data);
                                    CanvasJS.Design.Environment.toolBox.controls.remove(loadingMessage);
                                    resolve("success");
                                },
                                error: (e) => {
                                    reject(e);
                                }
                            });
                        }, 100);
                    });
                }
                loadDocument() {
                    return new Promise((resolve, reject) => {
                        setTimeout(() => {
                            let loadingMessage = new PDJS.Shared.UI.Controls.Message({
                                message: `<span style="font-size: 20px;">Loading Document...</span>`
                            });
                            CanvasJS.Design.Environment.surface.controls.add(loadingMessage);
                            this.m_documentService.loadDesignDocument({
                                documentId: this.documentId,
                                success: (e) => {
                                    let model = new PDJS.Canvas.Core.Documents.DesignDocument(e.data.document);
                                    CanvasJS.Design.Environment.surface.loadDocument(new PDJS.Canvas.Design.DocumentView({
                                        $source: model,
                                        canvasType: e.data.document.canvasType,
                                        entityTypeId: e.data.entityTypeId,
                                        extensionId: e.data.extensionId,
                                        documentTypeId: e.data.documentTypeId,
                                        isFileBased: e.data.isFileBased,
                                        isListBased: e.data.isListBased
                                    }));
                                    if (loadingMessage != null) {
                                        CanvasJS.Design.Environment.surface.controls.remove(loadingMessage);
                                    }
                                    this.canvasType = e.data.document.canvasType;
                                    this.settings.label = this.getModuleName(e.data);
                                    this.entityTypeName = e.data.entityTypeName;
                                    this.entityTypeName = e.data.entityTypeName;
                                    this.entityTypeId = e.data.entityTypeId;
                                    this.canvasName = e.data.documentTypeId != null ?
                                        e.data.documentTypeName : e.data.folderName;
                                    resolve("success");
                                    CanvasJS.Design.Environment.document.source.addStateChangeHandler(() => {
                                        this.settings.hasChanges = true;
                                    });
                                },
                                error: (e) => {
                                    reject(e);
                                }
                            });
                        }, 100);
                    });
                }
                loadHotKeys() {
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "ctrl e",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/close", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "ctrl s",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/save", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                    CanvasJS.Design.Environment.context.hotkeys.register_combo({
                        keys: "alt f s",
                        on_keydown: () => {
                            CanvasJS.Design.Environment
                                .context
                                .commands
                                .execute("pdjs/canvas/standard:document/save", null);
                        },
                        prevent_default: true,
                        prevent_repeat: true
                    });
                }
                getModuleName(e) {
                    let result;
                    if (e.documentTypeName != null) {
                        return `${e.documentTypeName}`;
                    }
                    if (e.entityTypeName != null) {
                        return `${e.entityTypeName} | ${e.folderName}`;
                    }
                    return "Canvas";
                }
                getModuleTooltip(e) {
                    if (e.documentTypeId != null) {
                        return `${e.documentTypeName}`;
                    }
                    if (e.entityTypeName != null) {
                        return `${e.entityTypeName} &gt; ${e.folderName}`;
                    }
                    return "Canvas";
                }
                commitCanvas() {
                    return new Promise((resolve, reject) => {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("", {
                            success: (e) => {
                                resolve("resolve");
                            },
                            error: (e) => {
                                reject("reject");
                            }
                        });
                    });
                }
                closeModule() {
                    return new Promise((resolve, reject) => {
                        let previousContext = PDJS.Application.instance.contexts.current;
                        PDJS.Application.instance.contexts.setCurrent(this.ID);
                        let service = new PDJS.Services.Canvas.DocumentService();
                        let document = CanvasJS.Design.Environment.document.source;
                        service.closeDesignDocument({
                            sessionId: document.sessionId,
                            success: (e) => {
                                PDJS.Application.instance.contexts.setCurrent(previousContext.ID);
                                resolve();
                            },
                            error: (e) => {
                                if (!this.focused) {
                                    e.errorHandled = true;
                                }
                                PDJS.Application.instance.contexts.setCurrent(previousContext.ID);
                                reject(e.xhr.responseText);
                            }
                        });
                    });
                }
            }
            Canvas.CanvasModule = CanvasModule;
        })(Canvas = Manage.Canvas || (Manage.Canvas = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Canvas;
        (function (Canvas) {
            let Events;
            (function (Events) {
                Events["CanvasRenamed"] = "canvas/renamed";
            })(Events = Canvas.Events || (Canvas.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static canvasRenamedPublish(args) {
                    this.global.publish(Events.CanvasRenamed, args);
                }
                static canvasRenamedSubscribe(handler) {
                    return this.global.subscribe(Events.CanvasRenamed, handler);
                }
            }
            Canvas.EventsHub = EventsHub;
        })(Canvas = Manage.Canvas || (Manage.Canvas = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Canvas;
        (function (Canvas) {
            class HighlightElement extends Canvas.CanvasDirective {
                constructor() {
                    super({});
                    this.name = Canvas.Directives.HighlightElement;
                }
                execute(e) {
                    if (Jade.String.isNullOrWhiteSpace(e.elementId)) {
                        this.openDocumentProperties(e);
                    }
                    else {
                        this.openElementProperties(e);
                    }
                }
                openElementProperties(e) {
                    let views = CanvasJS.Design.Environment
                        .document.controls.getByType(PDJS.Canvas.Design.ElementView).toArray();
                    views.forEach(element => {
                        if (element.ID == e.elementId) {
                            CanvasJS.Design.Environment.selection.clear();
                            CanvasJS.Design.Environment.selection.add(element);
                            CanvasJS.Design.Environment.selection.box.hide();
                            CanvasJS.Design.Environment.selection.box.show();
                            PDJS.Canvas.Design.FeatureEditor.showForElement(element);
                        }
                    });
                }
                openDocumentProperties(e) {
                    let document = CanvasJS.Design.Environment.document;
                    PDJS.Canvas.Design.FeatureEditor.showForDocument(document);
                }
            }
            Canvas.HighlightElement = HighlightElement;
        })(Canvas = Manage.Canvas || (Manage.Canvas = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get jobId() {
                    return this.state.get("jobId");
                }
                set jobId(value) {
                    this.state.set("jobId", value);
                }
                load(jobId) {
                    this.jobId = jobId;
                }
                template() {
                    return `<div class="-pdjs-manage-data-load-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Data Model"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/data-model-properties",
                        label: "Property Data Extensions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/data-model-list",
                        label: "List Data Extensions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/selection-lists",
                        label: "Selection Lists"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Entities"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Types",
                        url: "#/module/entity-types"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Management",
                        url: "#/module/entity-management"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Behaviors"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tags",
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tag-expressions",
                        label: "Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Users and Groups"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/users",
                        label: "Users"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/groups",
                        label: "Groups"
                    }));
                }
            }
            DataLoad.DataLoadActions = DataLoadActions;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/data-load": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            DataLoad.DataLoadCommand = DataLoadCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DeleteAllJobsCommand extends DataLoad.DataLoadCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "job/delete-all",
                        label: "Delete All",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Delete all data load jobs.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Data Load Jobs",
                        message: "Delete all data load jobs?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.executeServiceCall();
                            }
                        }
                    });
                }
                executeServiceCall() {
                    let service = new PDJS.Services.DataLoad.DataLoadService();
                    service.deleteAllJobs({
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            DataLoad.DeleteAllJobsCommand = DeleteAllJobsCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DeleteJobsCommand extends DataLoad.DataLoadCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "job/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected data load jobs.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Data Load Jobs",
                        message: `Delete the selected data load jobs?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.executeServiceCall();
                            }
                        }
                    });
                }
                executeServiceCall() {
                    let service = new PDJS.Services.DataLoad.DataLoadService();
                    service.deleteJobs({
                        ids: _.map(this.selections, "id"),
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            DataLoad.DeleteJobsCommand = DeleteJobsCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DownloadInputCommand extends DataLoad.DataLoadCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "job/download-input-file",
                        label: "Download Input",
                        icon: "inbox_into.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Download the input file of the selected job.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Downloader.download({
                        url: "~/Manage/DataLoad/GetSourceFile",
                        params: {
                            id: _.first(_.map(this.selections, "id"))
                        }
                    });
                }
            }
            DataLoad.DownloadInputCommand = DownloadInputCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DownloadOutputCommand extends DataLoad.DataLoadCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "job/download-output-file",
                        label: "Download Output",
                        icon: "inbox_out.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Download the output file of the selected job.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Downloader.download({
                        url: "~/Manage/DataLoad/GetOutputFile",
                        params: {
                            id: _.first(_.map(this.selections, "id"))
                        }
                    });
                }
            }
            DataLoad.DownloadOutputCommand = DownloadOutputCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class NewJobCommand extends DataLoad.DataLoadCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "job/create",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Start a new data load job.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    DataLoad.NewJobDialog.open({
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                e.validateOnly ?
                                    this.startTask(e) :
                                    this.promptToConfirm(e);
                            }
                        }
                    });
                }
                promptToConfirm(args) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Execute Data Load Job?",
                        message: `<b>WARNING:</b> You are about to execute a data load job.
                          This may result in the modification of application data.
                          <br/><br/>
                          Do you wish to continue?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.startTask(args);
                            }
                        }
                    });
                }
                startTask(args) {
                    let service = new PDJS.Services.DataLoad.DataLoadService();
                    let taskId = null;
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Data Load Job Progress",
                        enableClose: false,
                        showDetail: true,
                        taskStart: (e) => {
                            service.createJob({
                                uploadId: args.uploadId,
                                uploadName: args.uploadName,
                                validateOnly: args.validateOnly,
                                success: (e2) => {
                                    taskId = e2.data.taskId;
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        close: (e) => {
                            this.grid.refresh({
                                clear: true,
                                selections: [taskId]
                            });
                        }
                    });
                }
            }
            DataLoad.NewJobCommand = NewJobCommand;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/data-load");
                }
                registerCommands(e) {
                    e.commands.add(new DataLoad.DeleteAllJobsCommand({}));
                    e.commands.add(new DataLoad.DeleteJobsCommand({}));
                    e.commands.add(new DataLoad.DownloadInputCommand({}));
                    e.commands.add(new DataLoad.DownloadOutputCommand({}));
                    e.commands.add(new DataLoad.NewJobCommand({}));
                }
            }
            DataLoad.DataLoadCommands = DataLoadCommands;
            Jade.CommandGroups.add(DataLoadCommands);
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/data-load";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:job/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:job/download-input-file`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:job/download-output-file`
                    }));
                }
            }
            DataLoad.DataLoadContextMenu = DataLoadContextMenu;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-data-load-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Data Load Jobs</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new DataLoad.DataLoadToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        defaultSelectionEnabled: true,
                        messaging: {
                            noRecordsMessage: "No data load jobs."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/data-load:job/download-output-file");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.DataLoad.DataLoadContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            DataLoad.DataLoadGrid = DataLoadGrid;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-data-load">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new DataLoad.DataLoadGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new DataLoad.DataLoadActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.DataLoad.DataLoadService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/data-load": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            DataLoad.DataLoadModule = DataLoadModule;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/data-load";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:job/create`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:job/delete`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:job/delete-all`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:job/download-input-file`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:job/download-output-file`
                    }));
                }
            }
            DataLoad.DataLoadToolbar = DataLoadToolbar;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class NewJobDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get upload() {
                    return this.m_upload;
                }
                set upload(value) {
                    this.m_upload = value;
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get validateOnly() {
                    return this.node.find("input[type=checkbox]").is(":checked");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-data-load-new-job-dialog">
                    <div role="header">
                        Data Load Workbook:
                    </div>
                    <div role="upload">
                    </div>
                    <div role="content">
                        <label>
                            <span>
                                <input type="checkbox" />
                            </span>
                            <span>
                                <b>Validate Only</b><br/>
                                When this option is selected, the specified import workbook
                                will be checked for errors, but no data will be imported.
                            </span>
                        </label>
                    </div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "New | Data Load Job",
                        width: "400px",
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.upload_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    this.enableOkButton(false);
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=upload]",
                        onFileSelected: (e) => {
                        },
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.okButtonNode.removeAttr("disabled");
                            this.enableOkButton(true);
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                okButton_onClick(e) {
                    this.close({
                        name: "ok",
                        data: {
                            uploadId: this.upload.uploadId,
                            uploadName: this.upload.uploadName,
                            validateOnly: this.validateOnly
                        }
                    });
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                enableOkButton(enabled) {
                    enabled ?
                        this.okButtonNode.removeAttr("disabled") :
                        this.okButtonNode.attr("disabled", "disabled");
                }
                showConfirmationDialog(callback) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Execute Data Load Job?",
                        message: "<b>WARNING:</b> You are about to execute a data load job. This may result in the modification of application data.<br/><br/>Do you wish to continue?",
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                callback(e);
                            }
                        }
                    });
                }
                static open(options = {}) {
                    return new NewJobDialog(options);
                }
            }
            DataLoad.NewJobDialog = NewJobDialog;
        })(DataLoad = Manage.DataLoad || (Manage.DataLoad = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get tableId() {
                    return this.state.get("tableId");
                }
                set tableId(value) {
                    this.state.set("tableId", value);
                }
                get columnId() {
                    return this.state.get("columnId");
                }
                set columnId(value) {
                    this.state.set("columnId", value);
                }
                load(tableId, columnId) {
                    this.tableId = tableId;
                    this.columnId = columnId;
                }
                template() {
                    return `<div class="-pdjs-manage-data-model-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new DataModel.DataModelSearch());
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Selection Lists"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Manage Selection Lists",
                        url: "#/module/selection-lists"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Insights"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "All Extensions and Columns",
                        url: "#/module/insights-viewer/extensioncolumnsall"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Extension Column Forms",
                        url: "#/module/insights-viewer/extensioncolumnforms"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Extension Column Search Groups",
                        url: "#/module/insights-viewer/extensioncolumngroups"
                    }));
                }
            }
            DataModel.DataModelActions = DataModelActions;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$tablesGrid", null);
                    this.state.set("$columnsGrid", null);
                    this.state.set("isListExtensions", null);
                }
                get columnsGrid() {
                    return this.state.get("$columnsGrid");
                }
                get columnsSelection() {
                    return _.first(this.columnsGrid.selections);
                }
                get tablesGrid() {
                    return this.state.get("$tablesGrid");
                }
                get tableSelection() {
                    return _.first(this.tablesGrid.selections);
                }
                get isListExtensions() {
                    return this.state.get("isListExtensions");
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/data-load": {
                            $columnsGrid: this.columnsGrid,
                            $tablesGrid: this.tablesGrid
                        }
                    }, { force: true });
                }
            }
            DataModel.DataModelCommand = DataModelCommand;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class DeleteColumnCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "column/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Delete the selected columns.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete | Columns",
                            message: "Delete the selected columns?",
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.deleteColumns();
                                }
                            }
                        });
                    }
                    deleteColumns(confirmation) {
                        let service = new PDJS.Services.DataModel.DataColumnService();
                        let ids = _.map(this.columnsGrid.selections, "id");
                        service.deleteColumns({
                            ids: ids,
                            confirmation: confirmation,
                            success: (e) => {
                                e.data.requiresConfirmation ?
                                    this.showConfirmationDialog(e.data.names, e.data.confirmation) :
                                    this.columnsGrid.refresh();
                            }
                        });
                    }
                    showConfirmationDialog(names, confirmation) {
                        Jade.UI.Dialogs.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            title: "Data Loss Warning",
                            header: `Deleting the columns listed below
                         will result in the loss of data.<br/><br/>
                         Continue with the deletion?`,
                            messages: names,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.deleteColumns(confirmation);
                                }
                            }
                        });
                    }
                }
                Columns.DeleteColumnCommand = DeleteColumnCommand;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class EditColumnCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "column/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit the selected column.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.columnsGrid.selections.length == 1;
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${this.columnsSelection.name}`,
                            height: "550px",
                            width: "500px",
                            args: {
                                targetId: this.columnsSelection.id,
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.ColumnArbiter",
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.ColumnUIO"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.columnsGrid.refresh();
                                }
                            }
                        });
                    }
                }
                Columns.EditColumnCommand = EditColumnCommand;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class NewColumnCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "column/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Add a new column to the selected extension.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.tablesGrid.selections.length == 1;
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `New | Column`,
                            height: "550px",
                            width: "500px",
                            args: {
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.ColumnArbiter",
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.ColumnUIO",
                                properties: {
                                    extensionId: this.tableSelection.id
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.columnsGrid.refresh({
                                        selections: [e.target.id]
                                    });
                                }
                            }
                        });
                    }
                }
                Columns.NewColumnCommand = NewColumnCommand;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class DeleteTableCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "table/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Delete the selected extension.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete | Extension",
                            message: `Delete the "${this.tableSelection.name}" extension?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.deleteTable();
                                }
                            }
                        });
                    }
                    deleteTable(confirmation = false) {
                        let service = new PDJS.Services.DataModel.DataTableService();
                        service.deleteTable({
                            id: this.tableSelection.id,
                            confirmation: confirmation,
                            success: (e) => {
                                e.data.requiresConfirmation ?
                                    this.showConfirmationDialog() :
                                    this.tablesGrid.refresh({ clear: true });
                            }
                        });
                    }
                    showConfirmationDialog() {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Data Loss Warning",
                            message: `The "${this.tableSelection.name}" extension contains data.
                          Deletion will result in the loss of this data.<br/><br/>
                          Continue with the deletion?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.deleteTable(true);
                                }
                            }
                        });
                    }
                }
                Tables.DeleteTableCommand = DeleteTableCommand;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class EditTableCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "table/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Edit the selected extension.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.tablesGrid.selections.length == 1;
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${this.tableSelection.name}`,
                            height: "400px",
                            width: "450px",
                            args: {
                                targetId: this.tableSelection.id,
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.ExtensionArbiter",
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.ExtensionUIO",
                                properties: {
                                    isList: this.isListExtensions
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.tablesGrid.refresh();
                                }
                            }
                        });
                    }
                }
                Tables.EditTableCommand = EditTableCommand;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/data-model");
                }
                registerCommands(e) {
                    e.commands.add(new DataModel.Columns.DeleteColumnCommand({}));
                    e.commands.add(new DataModel.Columns.EditColumnCommand({}));
                    e.commands.add(new DataModel.Columns.NewColumnCommand({}));
                    e.commands.add(new DataModel.Tables.DeleteTableCommand({}));
                    e.commands.add(new DataModel.Tables.EditTableCommand({}));
                    e.commands.add(new DataModel.Tables.NewTableCommand({}));
                }
            }
            DataModel.DataModelCommands = DataModelCommands;
            Jade.CommandGroups.add(DataModelCommands);
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get tablesViewStateId() {
                    return this.state.get("tablesViewStateId");
                }
                set tablesViewStateId(value) {
                    this.state.set("tablesViewStateId", value);
                }
                get columnsViewStateId() {
                    return this.state.get("columnsViewStateId");
                }
                set columnsViewStateId(value) {
                    this.state.set("columnsViewStateId", value);
                }
                get isListExtensions() {
                    return this.settings.moduleId === "data-model-list";
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-data-load">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                actions_init() {
                    this.m_actions = new DataModel.DataModelActions({
                        insertAt: "div[data-id=pane-3]"
                    });
                    this.controls.add(this.m_actions);
                }
                columnsGrid_init() {
                    this.m_columnsGrid = new DataModel.Columns.ColumnsGrid({
                        insertAt: "div[data-id=pane-2]",
                        viewStateId: this.columnsViewStateId,
                        isListExtensions: this.isListExtensions,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_columnsGrid);
                }
                tablesGrid_init() {
                    this.m_tablesGrid = new DataModel.Tables.TablesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.tablesViewStateId,
                        isListExtensions: this.isListExtensions,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.m_columnsGrid.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_tablesGrid);
                }
                module_init() {
                    let service = new PDJS.Services.DataModel.DataModelService();
                    service.index({
                        success: (e) => {
                            this.columnsViewStateId = e.data.columnsViewStateId;
                            this.tablesViewStateId = e.data.tablesViewStateId;
                            this.columnsGrid_init();
                            this.tablesGrid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "300px", scrollable: false },
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_tablesGrid != null &&
                        this.m_columnsGrid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/data-model": {
                            $columnsGrid: this.m_columnsGrid,
                            $tablesGrid: this.m_tablesGrid,
                            isListExtensions: this.isListExtensions,
                        }
                    }, { force: true });
                }
            }
            DataModel.DataModelModule = DataModelModule;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            let Events;
            (function (Events) {
                Events["SearchColumns"] = "data-model/search-columns";
            })(Events = DataModel.Events || (DataModel.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static searchColumnsPublish(args) {
                    this.current.publish(Events.SearchColumns, args);
                }
                static searchColumnsSubscribe(handler) {
                    return this.current.subscribe(Events.SearchColumns, handler);
                }
            }
            DataModel.EventsHub = EventsHub;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelSearch extends Jade.UI.Control {
                constructor(options = {}) {
                    super(options);
                }
                get searchButton() {
                    return this.node.find("button[role=search]");
                }
                get matchNode() {
                    return this.node.find("select[role=match]");
                }
                template() {
                    return `<div class="-pdjs-manage-data-model-search">
                        <div role="header"></div>
                        <div role="combo-box"></div>
                        <div>
                            <select role="match" style="box-sizing:border-box;width: 100%;padding: 3px;">
                                <option value="0">Search all names</option>
                                <option value="1">Search column name</option>
                                <option value="2">Search column custom ID</option>
                                <option value="3">Search column database name</option>
                            <select>
                        </div>
                        <div role="search-box"></div>
                        <div role="buttons">
                            <button role="search" class="-pdjs-button">Find</button>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.header_init();
                    this.comboBox_init();
                    this.searchBox_init();
                    this.searchButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.executeSearch();
                    });
                    this.matchNode.on(Jade.BrowserEvent.CHANGE, () => {
                        this.executeSearch();
                    });
                    this.node.css({ marginBottom: "10px" });
                }
                header_init() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        insertAt: "div[role=header]",
                        label: "Find Columns"
                    }));
                }
                comboBox_init() {
                    this.m_comboBox = new DataModel.DataModelSearchComboBox({
                        insertAt: "div[role=combo-box]",
                        mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                        defaultMask: "Filter by Entity Type...",
                        onSelectionChanged: (e) => {
                            this.executeSearch();
                        }
                    });
                    this.controls.add(this.m_comboBox);
                }
                searchBox_init() {
                    this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                        insertAt: "div[role=search-box]",
                        height: 100,
                        defaultMaskText: "Search for name...",
                        label: "Script Tags",
                        onSearch: (e) => {
                            this.executeSearch();
                        }
                    });
                    this.controls.add(this.m_searchBox);
                }
                executeSearch() {
                    DataModel.EventsHub.searchColumnsPublish({
                        searchTerm: !Jade.String.isNullOrWhiteSpace(this.m_searchBox.textValue) ?
                            this.m_searchBox.textValue : null,
                        match: parseInt(this.matchNode.val()),
                        entityTypeId: !Jade.String.isNullOrWhiteSpace(this.m_comboBox.textValue) ?
                            parseInt(this.m_comboBox.textValue) : null
                    });
                }
            }
            DataModel.DataModelSearch = DataModelSearch;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelSearchComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                onSelectionChange(selection) {
                    super.onSelectionChange(selection);
                    if (selection != null) {
                        this.iconValue = null;
                        this.textValue = selection.id.toString();
                        this.maskValue = selection.name;
                    }
                }
                createListItem(e) {
                    return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                        data: e,
                        uidMap: "id",
                        labelMap: "name",
                        iconMap: "icon"
                    });
                }
                onFilter(e) {
                    let service = new PDJS.Services.EntityTypes.EntityTypesService();
                    service.query({
                        term: this.textValue,
                        success: (e2) => {
                            e.result.addRange(e2.data.items);
                            e.complete();
                            this.list.resize(e2.data.items.length * 24);
                        }
                    });
                }
                onShowDialog(e) {
                    DataModel.DataModelSearchDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.selection = {
                                    id: e.id,
                                    icon: e.icon,
                                    name: e.name
                                };
                            }
                        }
                    });
                }
            }
            DataModel.DataModelSearchComboBox = DataModelSearchComboBox;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            class DataModelSearchDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get selection() {
                    return this.state.get("selection");
                }
                set selection(value) {
                    this.state.set("selection", value);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on("click", (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on("click", (e) => {
                        this.close();
                    });
                    this.startUp();
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Entity Type",
                        height: 350,
                        width: 500
                    };
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-tags-selection-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            mapping: (e) => {
                                return {
                                    icon: e.Icon,
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        change: (e) => {
                            this.selection = _.first(e.selections.toArray());
                        },
                        dblclick: (e) => {
                            this.selection = _.first(e.selections.toArray());
                            this.closeAndReturn();
                        }
                    });
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    if (this.viewStateId == null) {
                        service.getViewStateId({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.ENTITY_TYPE_SELECTION,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                            }
                        });
                    }
                }
                closeAndReturn() {
                    if (this.selection != null) {
                        this.close({
                            name: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "Nothing has been selected. Make a selection and try again."
                        });
                    }
                }
                static open(options) {
                    return new DataModelSearchDialog(options);
                }
            }
            DataModel.DataModelSearchDialog = DataModelSearchDialog;
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class ColumnsGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get filters() {
                        return this.state.get("filters", []);
                    }
                    set filters(value) {
                        this.state.set("filters", value);
                    }
                    get isListExtensions() {
                        return this.state.get("isListExtensions");
                    }
                    get searchTerm() {
                        return this.state.get("searchTerm");
                    }
                    set searchTerm(value) {
                        this.state.set("searchTerm", value);
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get table() {
                        return this.state.get("table");
                    }
                    set table(value) {
                        this.state.set("table", value);
                    }
                    get tableNameNode() {
                        return this.node.find("span[role=table-name]");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    load(table) {
                        this.table = table;
                        this.tableNameNode.text(this.table ? this.table.name : "Table");
                        this.refresh({ clear: true });
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-data-model-columns-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Columns for <span role="table-name"></span></div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                        this.subscriptions.add(DataModel.EventsHub.searchColumnsSubscribe(e => {
                            this.filters = [];
                            this.filters.push(PDJS.Core.Views.ExtensionsFilter.search({
                                entTypes: e.entityTypeId != null ? [e.entityTypeId] : null,
                                match: e.match,
                                term: e.searchTerm
                            }));
                            this.m_grid.refresh({ clear: true });
                        }));
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.DataModel.Columns.ColumnsGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "multiple",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No columns."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: parseInt(e.ObjectId),
                                        name: e.ColumnName,
                                        type: e.ColumnType
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/data-model:column/edit");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            needContext: (e) => {
                                var _a;
                                _.each(this.filters, (item) => {
                                    e.filters.push(item.toJSON());
                                });
                                e.filters.push({ id: "Extension", params: { extensionId: ((_a = this.table) === null || _a === void 0 ? void 0 : _a.id) ? this.table.id : -1 } });
                                e.filters.push({ id: "IsList", params: { isList: this.isListExtensions ? 1 : 0 } });
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Columns.ColumnsToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                }
                Columns.ColumnsGrid = ColumnsGrid;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class ColumnsGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/data-model";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:column/new`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:column/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:column/delete`
                        }));
                    }
                }
                Columns.ColumnsGridContextMenu = ColumnsGridContextMenu;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Columns;
            (function (Columns) {
                class ColumnsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/data-model";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:column/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:column/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:column/delete`
                        }));
                    }
                }
                Columns.ColumnsToolbar = ColumnsToolbar;
            })(Columns = DataModel.Columns || (DataModel.Columns = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class SelectionListsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get list() {
                        return this.state.get("list");
                    }
                    set list(value) {
                        this.state.set("list", value);
                    }
                    get listItem() {
                        return this.state.get("listItem");
                    }
                    set listItem(value) {
                        this.state.set("listItem", value);
                    }
                    loadList(list) {
                        this.list = list;
                    }
                    loadListItem(item) {
                        this.listItem = item;
                    }
                    template() {
                        return `<div class="-pdjs-manage-selection-lists-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addItems();
                    }
                    addItems() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Manage"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Property Data Extensions",
                            url: "#/module/data-model-properties"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "List Data Extensions",
                            url: "#/module/data-model-list"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Insights"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "All Selection Lists and Items",
                            url: "#/module/insights-viewer/selectionlistitemsall"
                        }));
                    }
                }
                SelectionLists.SelectionListsActions = SelectionListsActions;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class SelectionListsCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$listGrid", null);
                        this.state.set("$listItemGrid", null);
                    }
                    get listGrid() {
                        return this.state.get("$listGrid");
                    }
                    get listItemGrid() {
                        return this.state.get("$listItemGrid");
                    }
                    get listItemGridExists() {
                        return this.listItemGrid != null;
                    }
                    get listSelections() {
                        return this.listGrid.selections;
                    }
                    get listItemSelections() {
                        return this.listItemGrid.selections;
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/selection-lists": {
                                $listGrid: this.listGrid,
                                $listItemGrid: this.listItemGrid
                            }
                        }, { force: true });
                    }
                }
                SelectionLists.SelectionListsCommand = SelectionListsCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class DeleteListCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "list/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Delete the selected list.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.listSelections.length == 1;
                    }
                    execute(e) {
                        let list = _.first(this.listSelections);
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Selection List",
                            message: `Delete the "${list.name}" selection list?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeServiceCall();
                                }
                            }
                        });
                    }
                    executeServiceCall() {
                        let service = new PDJS.Services.DataModel.SelectionListService();
                        let list = _.first(this.listSelections);
                        service.deleteList({
                            id: list.id,
                            success: (e) => {
                                this.listGrid.refresh({ clear: true });
                            }
                        });
                    }
                }
                SelectionLists.DeleteListCommand = DeleteListCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class DeleteListItemCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "item/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Delete the selected list items.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.listItemGridExists && this.listItemSelections.length > 0;
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete List Items",
                            header: "Delete the selected list item(s)?",
                            messages: _.map(this.listItemGrid.selections, "name"),
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeServiceCall();
                                }
                            }
                        });
                    }
                    executeServiceCall(confirmation = null) {
                        let service = new PDJS.Services.DataModel.SelectionListService();
                        service.deleteListItems({
                            ids: this.listItemSelections.map(item => item.id),
                            confirmation: confirmation,
                            success: (e) => {
                                e.data.requiresConfirmation ?
                                    this.showConfirmationDialog(e.data.confirmation) :
                                    this.listItemGrid.refresh({ clear: true });
                            }
                        });
                    }
                    showConfirmationDialog(confirmation) {
                        let message = `
                Some of the selected list items are currently in use.<br/><br/>
                Continuing with deletion will result in the loss of data.
                Continue with the deletion?`;
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "List Item In Use",
                            message: message,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeServiceCall(confirmation);
                                }
                            }
                        });
                    }
                }
                SelectionLists.DeleteListItemCommand = DeleteListItemCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class EditListCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "list/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit the selected list.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.listSelections.length == 1;
                    }
                    execute(e) {
                        let list = _.first(this.listSelections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${list.name}`,
                            height: "450px",
                            width: "450px",
                            args: {
                                targetId: list.id,
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.listGrid.refresh();
                                }
                            }
                        });
                    }
                }
                SelectionLists.EditListCommand = EditListCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class EditListItemCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "item/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit the selected list item.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.listItemGridExists && this.listItemSelections.length == 1;
                    }
                    execute(e) {
                        let item = _.first(this.listItemSelections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${item.name}`,
                            height: "450px",
                            width: "450px",
                            args: {
                                targetId: item.id,
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListItemUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListItemArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.listItemGrid.refresh();
                                }
                            }
                        });
                    }
                }
                SelectionLists.EditListItemCommand = EditListItemCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class NewListCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "list/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Create a new selection list.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "New | Selection List",
                            height: "450px",
                            width: "450px",
                            args: {
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.listGrid.refresh({
                                        clear: true,
                                        selections: [e.target.id]
                                    });
                                }
                            }
                        });
                    }
                }
                SelectionLists.NewListCommand = NewListCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class NewListItemCommand extends SelectionLists.SelectionListsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "item/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Create a new selection list item.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.listGrid.selections.length == 1;
                    }
                    execute(e) {
                        let list = _.first(this.listSelections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "New | Selection List Item",
                            height: "450px",
                            width: "450px",
                            args: {
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListItemUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.SelectionListItemArbiter",
                                properties: {
                                    listId: list.id
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.listItemGrid.refresh({
                                        clear: true,
                                        selections: [e.target.id]
                                    });
                                }
                            }
                        });
                    }
                }
                SelectionLists.NewListItemCommand = NewListItemCommand;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class SelectionListsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/selection-lists");
                    }
                    registerCommands(e) {
                        e.commands.add(new SelectionLists.DeleteListCommand());
                        e.commands.add(new SelectionLists.DeleteListItemCommand());
                        e.commands.add(new SelectionLists.EditListCommand());
                        e.commands.add(new SelectionLists.EditListItemCommand());
                        e.commands.add(new SelectionLists.NewListCommand());
                        e.commands.add(new SelectionLists.NewListItemCommand());
                    }
                }
                SelectionLists.SelectionListsCommands = SelectionListsCommands;
                Jade.CommandGroups.add(SelectionListsCommands);
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class SelectionListsModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-selection-lists">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.actions_init();
                        this.module_init();
                    }
                    listGrid_init() {
                        this.m_listGrid = new SelectionLists.ListGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.m_actions.loadList(item);
                                this.m_listItemGrid.load(item);
                                this.setCommandState();
                            },
                            dblclick: (item) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/selection-lists:list/edit");
                            }
                        });
                        this.controls.add(this.m_listGrid);
                    }
                    listItemGrid_init() {
                        this.m_listItemGrid = new SelectionLists.ListItemGrid({
                            insertAt: "div[data-id=pane-2]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.m_actions.loadListItem(item);
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_listItemGrid);
                    }
                    actions_init() {
                        this.m_actions = new SelectionLists.SelectionListsActions({
                            insertAt: "div[data-id=pane-3]"
                        });
                        this.controls.add(this.m_actions);
                    }
                    module_init() {
                        let service = new PDJS.Services.DataModel.SelectionListService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.listGrid_init();
                                this.listItemGrid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, size: "300px", scrollable: false },
                                { resizable: true, scrollable: false },
                                { resizable: true, size: "300px", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_listGrid != null && this.m_listItemGrid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/selection-lists": {
                                $listGrid: this.m_listGrid,
                                $listItemGrid: this.m_listItemGrid
                            }
                        }, { force: true });
                    }
                }
                SelectionLists.SelectionListsModule = SelectionListsModule;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class SelectListDialog extends Jade.UI.Dialogs.DialogOf {
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.selections;
                    }
                    template() {
                        return super.template(`
                <div class="-fb-lde-selection-editor-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.startUp();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Selection List",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    grid_init() {
                        this.m_grid = new SelectionLists.ListGrid({
                            insertAt: "div[role=grid]",
                            header: false,
                            viewStateId: this.viewStateId,
                            dblclick: (item) => {
                                this.closeAndReturn();
                            },
                            change: (item) => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: {
                                    items: this.selections
                                }
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Selection List Selected",
                                message: "No list data extension has been selected. Select an list data extension and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/selection-lists": {
                                $listGrid: this.m_grid
                            }
                        }, { force: true });
                    }
                    startUp() {
                        let service = new PDJS.Services.Views.ViewService();
                        service.getViewStateId({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.SELECTION_LISTS,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    static open(options) {
                        return new SelectListDialog(options);
                    }
                }
                SelectionLists.SelectListDialog = SelectListDialog;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get dblclickCallback() {
                        return this.state.get("dblclick", () => { });
                    }
                    get header() {
                        return this.state.get("header", true);
                    }
                    get headerNode() {
                        return this.node.find("div[role=head]");
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-selection-lists-list-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Selection Lists</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                        if (!this.header) {
                            this.headerNode.remove();
                            this.node.css({
                                gridTemplateRows: "max-content auto"
                            });
                        }
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new SelectionLists.ListGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No selection lists."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.ListName
                                    };
                                }
                            },
                            dblclick: (e) => {
                                this.dblclickCallback(e.selection);
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.DataModel.SelectionLists.ListGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                SelectionLists.ListGrid = ListGrid;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/selection-lists";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:list/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:list/delete`
                        }));
                    }
                }
                SelectionLists.ListGridContextMenu = ListGridContextMenu;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/selection-lists";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:list/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:list/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:list/delete`
                        }));
                    }
                }
                SelectionLists.ListGridToolbar = ListGridToolbar;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListItemGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return ((_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray()) || [];
                    }
                    get list() {
                        return this.state.get("list");
                    }
                    set list(value) {
                        this.state.set("list", value);
                    }
                    get listNameNode() {
                        return this.node.find("span[role=list-name]");
                    }
                    load(list) {
                        this.list = list;
                        this.listNameNode.text(this.list ? this.list.name : "List");
                        this.refresh({ clear: true });
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-selection-lists-list-item-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">List Items for <span role="list-name"></span></div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new SelectionLists.ListItemGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: `[id=${this.ID}] [role=grid]`,
                            pk: "id",
                            selectOnRightClick: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.id,
                                        name: e.name
                                    };
                                }
                            },
                            dragAndDrop: {
                                drop: (e) => {
                                    this.moveListItems(e);
                                }
                            },
                            resizable: true,
                            modules: [
                                "PD.Web.UI.Controls.GridDragModule",
                                "PD.Web.UI.Controls.GridDropModule"
                            ],
                            dataSource: {
                                schema: {
                                    data: "data"
                                },
                                transport: {
                                    read: {
                                        url: Jade.Path.resolve("~/manage/selectionlist/listitems"),
                                        data: () => {
                                            var _a;
                                            return {
                                                listId: (_a = this.list) === null || _a === void 0 ? void 0 : _a.id
                                            };
                                        }
                                    }
                                }
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/selection-lists:item/edit");
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "icon"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name",
                                    width: "200px"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "value",
                                    title: "Value",
                                    width: "200px"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "customID",
                                    title: "Custom ID",
                                    width: "200px"
                                }),
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "inUse",
                                    titleText: "In Use?",
                                    titleIcon: "SIGN_WARNING.PNG",
                                    tooltip: "Item Is In Use",
                                    transform: function (data) {
                                        return (data.inUse ? "SIGN_WARNING.PNG" : null);
                                    }
                                }),
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "isDisabled",
                                    titleText: "Disabled?",
                                    titleIcon: "SIGN_FORBIDDEN.PNG",
                                    tooltip: "Item Is Disabled",
                                    transform: function (data) {
                                        return (data.isDisabled ? "SIGN_FORBIDDEN.PNG" : null);
                                    }
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ],
                            contextMenu: (e) => {
                                this.contextMenu_init(e);
                            }
                        });
                    }
                    contextMenu_init(e) {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: e,
                            segments: [{
                                    type: "PDJS.Manage.DataModel.SelectionLists.ListItemGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                    moveListItems(e) {
                        let service = new PDJS.Services.DataModel.SelectionListService();
                        if (e.selections.count() > 0) {
                            service.moveListItems({
                                listId: this.list.id,
                                itemIds: e.selections.toIDs().toArray(),
                                targetId: e.item.id,
                                success: (e) => {
                                    this.m_grid.refresh();
                                }
                            });
                        }
                    }
                }
                SelectionLists.ListItemGrid = ListItemGrid;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListItemGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/selection-lists";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:item/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:item/delete`
                        }));
                    }
                }
                SelectionLists.ListItemGridContextMenu = ListItemGridContextMenu;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var SelectionLists;
            (function (SelectionLists) {
                class ListItemGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/selection-lists";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:item/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:item/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:item/delete`
                        }));
                    }
                }
                SelectionLists.ListItemGridToolbar = ListItemGridToolbar;
            })(SelectionLists = DataModel.SelectionLists || (DataModel.SelectionLists = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class TablesGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get filters() {
                        return this.state.get("filters", []);
                    }
                    set filters(value) {
                        this.state.set("filters", value);
                    }
                    get isListExtensions() {
                        return this.state.get("isListExtensions");
                    }
                    get searchTerm() {
                        return this.state.get("searchTerm");
                    }
                    set searchTerm(value) {
                        this.state.set("searchTerm", value);
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-data-model-tables-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Extensions</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                        this.subscriptions.add(DataModel.EventsHub.searchColumnsSubscribe(e => {
                            this.filters = [];
                            this.filters.push(PDJS.Core.Views.ExtensionsFilter.search({
                                entTypes: e.entityTypeId != null ? [e.entityTypeId] : null,
                                match: e.match,
                                term: e.searchTerm
                            }));
                            this.m_grid.refresh({ clear: true });
                        }));
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Tables.TablesToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            defaultSelectionEnabled: true,
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No extensions."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: parseInt(e.ObjectId),
                                        name: e.ExtensionName
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/data-model:table/edit");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            needContext: (e) => {
                                _.each(this.filters, (item) => {
                                    e.filters.push(item.toJSON());
                                });
                                e.filters.push({ id: "IsList", params: { isList: this.isListExtensions ? 1 : 0 } });
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.DataModel.Tables.TablesGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                Tables.TablesGrid = TablesGrid;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class TablesGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/data-model";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:table/new`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:table/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:table/delete`
                        }));
                    }
                }
                Tables.TablesGridContextMenu = TablesGridContextMenu;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class TablesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/data-model";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:table/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:table/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:table/delete`
                        }));
                    }
                }
                Tables.TablesToolbar = TablesToolbar;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataModel;
        (function (DataModel) {
            var Tables;
            (function (Tables) {
                class NewTableCommand extends DataModel.DataModelCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "table/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Create a new extension.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "New | Extension",
                            height: "400px",
                            width: "450px",
                            args: {
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Extensions.ExtensionArbiter",
                                targetType: "ProspectDirector.Web.Manage.Modules.Extensions.ExtensionUIO",
                                properties: {
                                    isList: this.isListExtensions
                                }
                            },
                            select: {
                                ok: (sender, e) => {
                                    this.tablesGrid.refresh({
                                        selections: [e.target.id],
                                        clear: true
                                    });
                                }
                            }
                        });
                    }
                }
                Tables.NewTableCommand = NewTableCommand;
            })(Tables = DataModel.Tables || (DataModel.Tables = {}));
        })(DataModel = Manage.DataModel || (Manage.DataModel = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get documentType() {
                    return this.state.get("documentType");
                }
                set documentType(value) {
                    this.state.set("documentType", value);
                }
                load(documentType) {
                    this.documentType = documentType;
                }
                template() {
                    return `<div class="-pdjs-manage-document-types-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Types",
                        url: "#/module/entity-types"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Insights"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Form Fields",
                        url: "#/module/insights-viewer/formfields"
                    }));
                }
            }
            DocumentTypes.DocumentTypesActions = DocumentTypesActions;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/document-types": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            DocumentTypes.DocumentTypesCommand = DocumentTypesCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DeleteDocumentTypeCommand extends DocumentTypes.DocumentTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "document-type/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete a document type.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    let inUse = this.selections
                        .filter(i => i.fileCount > 0);
                    inUse.length == 0 ?
                        this.showDefaultPrompt() :
                        this.showInUsePrompt(inUse);
                }
                showInUsePrompt(inUse) {
                    let header = `
                    Delete the selected document types?<br/><br/>
                    <b>WARNING:</b> This document type is currently in use.
                    Proceeding with deletion will remove this document type assignment
                    from all documents to which it is currently assigned.`;
                    Jade.UI.Dialogs.MultiMessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Document Type",
                        header: header,
                        messages: inUse.map(i => i.name),
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.deleteDocumentTypes();
                            }
                        }
                    });
                }
                showDefaultPrompt() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Delete | Document Type",
                        message: "Delete the selected document types?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.deleteDocumentTypes();
                            }
                        }
                    });
                }
                deleteDocumentTypes() {
                    let service = new PDJS.Services.DocumentTypes.DocumentTypeService();
                    service.deleteDocumentType({
                        documentTypeId: this.selection.id,
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            DocumentTypes.DeleteDocumentTypeCommand = DeleteDocumentTypeCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class EditCanvasCommand extends DocumentTypes.DocumentTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "canvas/edit",
                        label: "Edit Canvas",
                        icon: "form.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the canvas associated with<br/>the selected document type.",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    window.location.href = `#/module/canvas-editor/${this.selection.canvasId}`;
                }
            }
            DocumentTypes.EditCanvasCommand = EditCanvasCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class EditDocumentTypeCommand extends DocumentTypes.DocumentTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "document-type/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the selected document type.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${this.selection.name}`,
                        height: "550px",
                        width: "550px",
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Shared.Modules.DocumentTypes.DocumentTypeUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.DocumentTypes.DocumentTypeArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            DocumentTypes.EditDocumentTypeCommand = EditDocumentTypeCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class EditSearchGroupsCommand extends DocumentTypes.DocumentTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "search-groups/edit",
                        label: "Search Groups",
                        icon: "magnifying_glass.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: `Configure Search Groups for the selected Document Type.<br/><br/>
                            Search groups control what data associated with this
                            Document Type is available for inclusion in Views and Charts.`,
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Manage.Views.SearchGroupsDialog.open({
                        title: `Search Groups | ${this.selection.name}`,
                        documentTypeId: this.selection.id
                    });
                }
            }
            DocumentTypes.EditSearchGroupsCommand = EditSearchGroupsCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class NewDocumentTypeCommand extends DocumentTypes.DocumentTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "document-type/new",
                        label: "New Document Type",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new document type.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Document Type",
                        height: "550px",
                        width: "550px",
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.DocumentTypes.DocumentTypeUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.DocumentTypes.DocumentTypeArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            DocumentTypes.NewDocumentTypeCommand = NewDocumentTypeCommand;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/document-types");
                }
                registerCommands(e) {
                    e.commands.add(new DocumentTypes.DeleteDocumentTypeCommand());
                    e.commands.add(new DocumentTypes.EditCanvasCommand());
                    e.commands.add(new DocumentTypes.EditDocumentTypeCommand());
                    e.commands.add(new DocumentTypes.EditSearchGroupsCommand());
                    e.commands.add(new DocumentTypes.NewDocumentTypeCommand());
                }
            }
            DocumentTypes.DocumentTypesCommands = DocumentTypesCommands;
            Jade.CommandGroups.add(DocumentTypesCommands);
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-document-types-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Document Types</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new DocumentTypes.DocumentTypesToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        defaultSelectionEnabled: true,
                        messaging: {
                            noRecordsMessage: "No document types."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name,
                                    canvasId: e.CanvasId,
                                    fileCount: e.FileCount
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/document-types:document-type/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.DocumentTypes.DocumentTypesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            DocumentTypes.DocumentTypesGrid = DocumentTypesGrid;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/document-types";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:document-type/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:document-type/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:document-type/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:canvas/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:search-groups/edit`
                    }));
                }
            }
            DocumentTypes.DocumentTypesGridContextMenu = DocumentTypesGridContextMenu;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-document-types">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new DocumentTypes.DocumentTypesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new DocumentTypes.DocumentTypesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.DocumentTypes.DocumentTypeService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/document-types": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            DocumentTypes.DocumentTypesModule = DocumentTypesModule;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/document-types";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:document-type/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:document-type/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:document-type/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:canvas/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:search-groups/edit`
                    }));
                }
            }
            DocumentTypes.DocumentTypesToolbar = DocumentTypesToolbar;
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class RestrictAssignmentToDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get clearButtonNode() {
                    return this.node.find("button[data-command=clear]");
                }
                get multiSelectNode() {
                    return this.node.find("[role=multi-select]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get selections() {
                    return this.state.get("selections", []);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.init_multiselect();
                    this.cancelButtonNode.on("click", (e) => {
                        this.close();
                    });
                    this.okButtonNode.on("click", (e) => {
                        this.okAndClose();
                    });
                    this.clearButtonNode.on("click", (e) => {
                        this.multiSelectNode.find("input[type=checkbox]").removeAttr("checked");
                    });
                }
                template() {
                    return super.template(`
                <div class="-pdjs-restrict-assignement-to-dialog">
                    <div role="instructions">
                        Restrict assignment of the document type to only the selected entity types listed below.
                    </div>
                    <div role="multi-select"></div>
                    <div role="buttons-dock">
                        <div role="button-dock-l">
                            <button data-command="clear" class="-jadeui-dialog-button">Clear</button>
                        </div>
                        <div role="button-dock-r">
                            <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Restrict Assignment To",
                        height: "400px",
                        width: "400px"
                    };
                }
                init_multiselect() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve("~/Manage/EntityTypes/List"),
                        error: (e) => {
                            this.close();
                        },
                        success: (e) => {
                            _.each(e, (item) => {
                                let icon = Jade.IconSet.get("pd").resolve(item.icon, Jade.IconSetSizeSpecificDirectory.x16);
                                let node = $(`
                            <label role="item" data-id="${item.id}">
                                <input type="checkbox"/>
                                <div role="item-label" style="background-image:url(${icon})">${item.name}</div>
                            </label>`);
                                node.data("data", item);
                                this.multiSelectNode.append(node);
                            });
                            _.each(this.selections, (item) => {
                                this.multiSelectNode.find(`label[data-id=${item.id}] input[type=checkbox]`).prop("checked", true);
                            });
                        }
                    });
                }
                okAndClose() {
                    let selections = [];
                    this.multiSelectNode
                        .find("label input:checked")
                        .each((index, elem) => {
                        let item = $(elem).closest("label").data("data");
                        selections[selections.length] = {
                            id: item.id,
                            name: item.name,
                            icon: item.icon
                        };
                    });
                    this.close({
                        name: "ok",
                        data: {
                            items: selections
                        }
                    });
                }
                static open(options) {
                    return new RestrictAssignmentToDialog(options);
                }
            }
            Views.RestrictAssignmentToDialog = RestrictAssignmentToDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class RestrictAssignmentEditor extends FeatureBlendJS.Views.MicroEditorBase {
                get listNode() {
                    return this.node.find("DIV[role=list]");
                }
                get buttonNode() {
                    return this.node.find("input[type=button]");
                }
                template() {
                    return `<div class="-fb-restrict-assignment-editor">
                        <div role="list"></div>
                        <div>
                            <input type="button" value="...">
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.buttonNode.on(Jade.BrowserEvent.CLICK, () => { this.button_onClick(); });
                    this.populate();
                }
                button_onClick() {
                    PDJS.Manage.Views.RestrictAssignmentToDialog.open({
                        title: "Entity Type Selection",
                        selections: this.source.getFeaturePrimaryValue([]),
                        select: {
                            ok: (sender, e) => {
                                this.source.setFeaturePrimaryValue(e.items);
                                this.populate();
                            }
                        }
                    });
                }
                populate() {
                    let items = this.source.getFeaturePrimaryValue([]);
                    this.listNode.empty();
                    _.each(items, (item) => {
                        let node = $(`<div role="list-item${item.icon ? "-w-icon" : ""}">${item.name}</div>`);
                        if (item.icon) {
                            node.css({
                                backgroundImage: `url(${Jade.IconSet.get("pd").resolve(item.icon, Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                        }
                        this.listNode.append(node);
                    });
                }
            }
            DocumentTypes.RestrictAssignmentEditor = RestrictAssignmentEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.RestrictAssignmentToEditor", RestrictAssignmentEditor);
            });
        })(DocumentTypes = Manage.DocumentTypes || (Manage.DocumentTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class EditorCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.initialLoadComplete = false;
                    this.state.set("$editor", null);
                }
                get editor() {
                    return this.state.get("$editor");
                }
                setState(state) {
                    super.setState(state);
                    if (this.editor != null && !this.initialLoadComplete) {
                        this.onInitialLoad();
                    }
                }
                updateCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/editor": {
                            editor: this.editor
                        }
                    }, { force: true });
                }
                onInitialLoad() {
                }
            }
            Editor.EditorCommand = EditorCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class FontSizeCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/font-size",
                        label: "Font Size",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.settings.fontSize = `${e.selection}px`;
                }
                onInitialLoad() {
                    super.onInitialLoad();
                    let fontSize = this.editor.settings.fontSize;
                    if (!Jade.String.isNullOrWhiteSpace(fontSize)) {
                        this.value = parseInt(fontSize);
                    }
                }
            }
            Editor.FontSizeCommand = FontSizeCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class ToggleFindCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/find",
                        label: "Find",
                        icon: "binocular.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.finder.showFind();
                }
            }
            Editor.ToggleFindCommand = ToggleFindCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class ToggleIndentsCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-indents",
                        label: "Toggle Indents",
                        icon: "code.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showIndents;
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showIndents = this.checked;
                }
            }
            Editor.ToggleIndentsCommand = ToggleIndentsCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class ToggleInvisiblesCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-invisibles",
                        label: "Toggle Invisibles",
                        icon: "symbol_paragraph.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showInvisibles;
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showInvisibles = this.checked;
                }
            }
            Editor.ToggleInvisiblesCommand = ToggleInvisiblesCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class ToggleLineNumbersCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-line-numbers",
                        label: "Toggle Line Numbers",
                        icon: "list_style_numbered.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showLineNumbers;
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showLineNumbers = this.checked;
                }
            }
            Editor.ToggleLineNumbersCommand = ToggleLineNumbersCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class ToggleReplaceCommand extends Editor.EditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/replace",
                        label: "Replace",
                        icon: "search_replace.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.finder.showReplace();
                }
            }
            Editor.ToggleReplaceCommand = ToggleReplaceCommand;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class EditorCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/resources/editor");
                }
                registerCommands(e) {
                    e.commands.add(new Editor.FontSizeCommand());
                    e.commands.add(new Editor.ToggleFindCommand());
                    e.commands.add(new Editor.ToggleIndentsCommand());
                    e.commands.add(new Editor.ToggleInvisiblesCommand());
                    e.commands.add(new Editor.ToggleLineNumbersCommand());
                    e.commands.add(new Editor.ToggleReplaceCommand());
                }
            }
            Editor.EditorCommands = EditorCommands;
            Jade.CommandGroups.add(EditorCommands);
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get contentNode() {
                        return this.node.children("*:first");
                    }
                    get overflowed() {
                        return this.state.get("overflowed", false);
                    }
                    set overflowed(value) {
                        this.state.set("overflowed", value);
                    }
                    get overflowedChanged() {
                        return this.state.hasChanged("overflowed");
                    }
                    get allowOverflow() {
                        return this.state.get("allowOverflow", true);
                    }
                    set allowOverflow(value) {
                        this.state.set("allowOverflow", value);
                    }
                    get toolbar() {
                        return this.m_toolbar;
                    }
                    set toolbar(value) {
                        this.m_toolbar = value;
                    }
                    createCopy() {
                        let result = new ToolbarItem(this.state.toJSON());
                        result.toolbar = this.toolbar;
                        return result;
                    }
                    template() {
                        return `<div role="item">${this.content()}</div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.overflowed ?
                            this.node.attr("data-overflowed", "") :
                            this.node.removeAttr("data-overflowed");
                    }
                    content() {
                        return `<div></div>`;
                    }
                }
                Controls.ToolbarItem = ToolbarItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarCommandItem extends Controls.ToolbarItem {
                    constructor(options) {
                        super(options);
                    }
                    get commandId() {
                        return this.state.get("commandId");
                    }
                    get commander() {
                        return this.m_commander;
                    }
                    set commander(value) {
                        this.m_commander = value;
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    createCopy() {
                        return new ToolbarCommandItem(this.state.toJSON());
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.commander = new UI.ControlCommander({
                            commandId: this.commandId,
                            change: () => {
                                this.onPropertiesChanged();
                            }
                        });
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.node.attr("command", this.commandId);
                        this.onPropertiesChanged();
                        this.createTooltip();
                    }
                    onPropertiesChanged() {
                        this.node.css({
                            paddingRight: this.commander.visible && !this.overflowed ? "5px" : ""
                        });
                    }
                    createTooltip() {
                        PDJS.Shared.PopOver.tooltipMenu(this.node, { title: this.commander.label, description: this.commander.tooltip }, {
                            position: this.overflowed ? "left" : "bottommiddle"
                        });
                    }
                    hideTooltip() {
                        if (this.node != null) {
                            PDJS.Shared.PopOver.hide(this.node);
                        }
                    }
                }
                Controls.ToolbarCommandItem = ToolbarCommandItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarCommandList extends Controls.ToolbarCommandItem {
                    constructor(options) {
                        super(options);
                    }
                    get items() {
                        return this.state.get("items", []);
                    }
                    set items(value) {
                        this.state.set("items", value);
                    }
                    get iconNode() {
                        return this.contentNode
                            .children("div[role=icon]");
                    }
                    get listNode() {
                        return this.contentNode
                            .children("div[role=list]");
                    }
                    get inputNode() {
                        return this.listNode
                            .children("select");
                    }
                    get textNode() {
                        return this.contentNode
                            .children("div[role=text]");
                    }
                    content() {
                        return `<div class="-pdjs-shared-ui-controls-toolbar-list">
                        <div role="text"></div>
                        <div role="list">
                            <select></select>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.items.forEach(item => {
                            this.inputNode.append(`<option value="${item.value}">${item.label}</option>`);
                        });
                        this.inputNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.commander.execute({
                                selection: this.inputNode.val()
                            });
                        });
                    }
                    onPropertiesChanged() {
                        super.onPropertiesChanged();
                        this.commander.isLabelVisible || this.overflowed ?
                            this.textNode.html(`${this.commander.label}: `) :
                            this.textNode.html("");
                    }
                }
                Controls.ToolbarCommandList = ToolbarCommandList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Editor;
        (function (Editor) {
            class FontSizeItem extends PDJS.Shared.UI.Controls.ToolbarCommandList {
                constructor(options) {
                    super(options);
                }
                onInit(e) {
                    super.onInit(e);
                    this.items = [];
                    [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 32, 36].forEach(item => {
                        this.items.push({ label: `${item} px`, value: item });
                    });
                }
                onPropertiesChanged() {
                    super.onPropertiesChanged();
                    if (this.commander.value != null) {
                        this.inputNode.val(this.commander.value);
                    }
                }
            }
            Editor.FontSizeItem = FontSizeItem;
        })(Editor = Manage.Editor || (Manage.Editor = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                template() {
                    return `<div class="-pdjs-manage-entities-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addEntitiesItems();
                }
                addEntitiesItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Types",
                        url: "#/module/entity-types"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Recycle Bin",
                        url: "#/module/recycle-bin"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Rules"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Manage Rules",
                        url: "#/module/rules"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Rule Script...",
                        click: (e) => {
                            PDJS.Manage.Rules.RuleEditing.create();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Manage Tags",
                        url: "#/module/tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Tag...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewTagDialog.open();
                        }
                    }));
                }
            }
            Entities.EntitiesActions = EntitiesActions;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$list", null);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get list() {
                    return this.state.get("$list");
                }
                get entityType() {
                    return this.list.selection;
                }
                get entities() {
                    return this.grid.selections;
                }
                get entityIds() {
                    return this.grid.selections.map(item => {
                        return item.id;
                    });
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entities": {
                            $grid: this.grid,
                            $list: this.list
                        }
                    }, { force: true });
                }
            }
            Entities.EntitiesCommand = EntitiesCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeStatusCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Entities.ChangeStatusDialog.open({
                        select: (sender, e) => {
                            this.executeTask(e.selection.value);
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/change-status",
                        tooltip: "Change the status of the selected entities.",
                        label: "Change Status",
                        icon: "contrast.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeTask(status) {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Change Status",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.changeStatus({
                                ids: this.entityIds,
                                status: status,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Entities.ChangeStatusCommand = ChangeStatusCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeTagsCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Entities.ChangeTagsDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeTask(e);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/change-tags",
                        tooltip: "Add/Remove tags from the selected entities.",
                        label: "Change Tags",
                        icon: "tags.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeTask(items) {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    let add = items.filter(item => {
                        return item.type == PDJS.Shared.UI.Controls.TagItemType.add;
                    }).map(item => item.text);
                    let remove = items.filter(item => {
                        return item.type == PDJS.Shared.UI.Controls.TagItemType.remove;
                    }).map(item => item.text);
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Entities | Change Tags",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.changeTags({
                                ids: this.entityIds,
                                add: add,
                                remove: remove,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Entities.ChangeTagsCommand = ChangeTagsCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class CreateEntityCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entityType != null;
                    this.tooltip = this.entityType != null ?
                        `Create a new ${this.entityType.name} entity.` :
                        `Create a new entity of the selected type.`;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Entities.EntityDialogs.showCreate({
                        entityTypeId: this.entityType.id,
                        promptToOpen: false,
                        allowPrompts: false,
                        allowRedirects: false,
                        onCreate: (sender, e) => {
                            this.grid.refresh({
                                clear: true,
                                selections: [e.target.id]
                            });
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/create",
                        tooltip: "Create a new entity of the selected type.",
                        label: "New",
                        icon: "add.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Entities.CreateEntityCommand = CreateEntityCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class DeleteEntityCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let message = this.entities.length > 1 ?
                        `Send the ${this.entities.length} selected entities to the recycle bin?` :
                        `Send the selected entity to the recycle bin?`;
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Entities | Send to Recycle Bin",
                        message: message,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeTask();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/delete",
                        tooltip: "Send the selected entities to the recycle bin.",
                        label: "Send to Recycle Bin",
                        icon: "garbage.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                executeTask() {
                    let service = new PDJS.Services.RecycleBin.RecycleBinService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Send to Recycle Bin",
                        enableClose: false,
                        taskStart: (e) => {
                            service.sendTo({
                                ids: this.entityIds,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({
                                clear: true
                            });
                        }
                    });
                }
            }
            Entities.DeleteEntityCommand = DeleteEntityCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class OpenEntityCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let entity = _.first(this.entities);
                    window.open(Jade.Path.resolve(`~/Explore/${entity.id}`));
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/open",
                        tooltip: "Open the selected entity in the explorer.",
                        label: "Open in Explorer",
                        icon: "folder_open.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Entities.OpenEntityCommand = OpenEntityCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class MoveEntityCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Entities.EntityBrowserDialog.open({
                        dialogTitle: "Move | Select Parent",
                        dialogMessage: "From the list below, select an entity to assign as the new parent.",
                        filters: [PDJS.Core.Views.EntityFilter.parentFilter([this.entityType.id])],
                        select: {
                            ok: (sender, e) => {
                                this.executeTask(e.entityId);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/move",
                        tooltip: "Move the selected entities to a new parent.",
                        label: "Move",
                        icon: "folder_into.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeTask(parentId) {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Entities | Move",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.move({
                                ids: this.entityIds,
                                parentId: parentId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                            PDJS.Shared.MessageStack.instance;
                        }
                    });
                }
            }
            Entities.MoveEntityCommand = MoveEntityCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class RunScriptCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Manage.Rules.RuleScriptSelectionDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.confirmTask(e.id, e.name);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/run-script",
                        tooltip: "Runs a script against one or more selected entities.",
                        label: "Run Script",
                        icon: "media_play.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                confirmTask(scriptId, scriptName) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Entities | Execute Script",
                        message: `Execute the "${scriptName}" script against the ${this.entities.length} selected entities?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeTask(scriptId, scriptName);
                            }
                        }
                    });
                }
                executeTask(scriptId, scriptName) {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Entities | Run Script",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.runScript({
                                ids: this.entityIds,
                                scriptId: scriptId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                            PDJS.Shared.MessageStack.instance
                                .success(`Executed the "${scriptName}" script against the ${this.entities.length} entities successfully.`);
                        }
                    });
                }
            }
            Entities.RunScriptCommand = RunScriptCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class UpdateEntityCommand extends Entities.EntitiesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.entities.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let entity = _.first(this.entities);
                    PDJS.Entities.EntityDialogs.showProperties({
                        entityId: entity.id,
                        allowRedirect: false,
                        onSave: (sender, e) => {
                            this.grid.refresh();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/update",
                        tooltip: "Edit the properties of the selected entity.",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Entities.UpdateEntityCommand = UpdateEntityCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/entities");
                }
                registerCommands(e) {
                    e.commands.add(new Entities.ChangeStatusCommand());
                    e.commands.add(new Entities.ChangeTagsCommand());
                    e.commands.add(new Entities.CreateEntityCommand());
                    e.commands.add(new Entities.DeleteEntityCommand());
                    e.commands.add(new Entities.OpenEntityCommand());
                    e.commands.add(new Entities.MoveEntityCommand());
                    e.commands.add(new Entities.RunScriptCommand());
                    e.commands.add(new Entities.UpdateEntityCommand());
                }
            }
            Entities.EntitiesCommands = EntitiesCommands;
            Jade.CommandGroups.add(EntitiesCommands);
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get headerNode() {
                    return this.node.children("div[role=head]");
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                update(entityType) {
                    if (entityType == null) {
                        this.addMessage("No entity type has been selected.");
                        return;
                    }
                    this.removeMessage();
                    this.headerNode.html(`${entityType.name} List`);
                    this.m_grid.setViewState(entityType.viewStateId);
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-entities-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Entity List</div>
                        <div role="grid" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: []
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No entities of this type found."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/entities:entity/update");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Entities.EntitiesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
                addMessage(text) {
                    this.removeMessage();
                    let message = new PDJS.Shared.UI.Controls.Message({
                        message: text
                    });
                    if (message != null) {
                        this.controls.add(message);
                    }
                }
                removeMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                        message.destroy();
                    }
                }
            }
            Entities.EntitiesGrid = EntitiesGrid;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/entities";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/update`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/move`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/open`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/change-status`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/change-tags`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity/run-script`
                    }));
                }
            }
            Entities.EntitiesGridContextMenu = EntitiesGridContextMenu;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesList extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selection() {
                    return _.first(this.m_list.selected.toArray().map(item => {
                        return {
                            id: item.data.value,
                            name: item.data.label,
                            icon: item.data.icon,
                            viewStateId: item.data.get("viewStateId")
                        };
                    }));
                }
                template() {
                    return `<div class="-pdjs-manage-entities-list ${Manage.CssClass.NavigationPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Entity Types</div>
                        <div role="list" class="${Manage.CssClass.ModuleSectionBody}" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.populateList();
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                        binding: {
                            value: "id",
                            label: "name"
                        },
                        data: [],
                        height: "100%",
                        iconSet: "pd",
                        noItemsMessage: "No entity types have been defined.",
                        change: (items) => {
                            if (this.m_list != null) {
                                this.changeCallback(this.selection);
                            }
                        }
                    });
                    this.controls.add(this.m_list);
                }
                populateList() {
                    let service = new PDJS.Services.Entities.EntitiesService();
                    service.getEntityTypes({
                        success: (e) => {
                            let firstId = null;
                            e.data.forEach(item => {
                                firstId == null ?
                                    firstId = item.id : null;
                                this.m_list.addItem(item);
                            });
                            if (firstId != null) {
                                this.m_list.select([firstId]);
                            }
                            else {
                                this.changeCallback(this.selection);
                            }
                        }
                    });
                }
            }
            Entities.EntitiesList = EntitiesList;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-entities">
                        <div role="toolbar"></div>
                        <div>
                            <div role="splitter">
                                <div data-id="pane-1"></div>
                                <div data-id="pane-2"></div>
                                <div data-id="pane-3"></div>
                            </div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.grid_init();
                    this.list_init();
                    this.menu_init();
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    if (this.m_grid != null) {
                        this.m_grid.refresh();
                    }
                }
                menu_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Entities.EntitiesToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                list_init() {
                    this.m_list = new Entities.EntitiesList({
                        insertAt: "div[data-id=pane-1]",
                        change: (item) => {
                            this.m_grid.update(this.m_list.selection);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_list);
                }
                grid_init() {
                    this.m_grid = new Entities.EntitiesGrid({
                        insertAt: "div[data-id=pane-2]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Entities.EntitiesActions({
                        insertAt: "div[data-id=pane-3]"
                    });
                    this.controls.add(this.m_actions);
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false, size: "300px" },
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/entities": {
                            $grid: this.m_grid,
                            $list: this.m_list
                        }
                    }, { force: true });
                }
            }
            Entities.EntitiesModule = EntitiesModule;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class EntitiesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/entities";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/create`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/update`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/move`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/open`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/change-status`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/change-tags`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity/run-script`
                    }));
                }
            }
            Entities.EntitiesToolbar = EntitiesToolbar;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeStatusDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(options) {
                    return new ChangeStatusDialog({
                        height: 270,
                        resizable: false,
                        title: "Entities | Change Status",
                        header: "What status would you like to assign to the selected entities?",
                        items: [
                            {
                                title: "Set to Active",
                                message: `Entities that are set to an "active" state will be made available to end users of the system, subject to security settings.`,
                                value: 1,
                                selected: true
                            },
                            {
                                title: "Set to Inactive",
                                message: `Entities that are set to an "inactive" state will no longer be accessible to end users of the system and will only be accessible to users granted manage permissions to the entity type.`,
                                value: 2
                            }
                        ],
                        select: (sender, e) => {
                            sender.close();
                            if (sender.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                if (e.selection != null && options.select instanceof Function) {
                                    options.select(sender, e);
                                }
                            }
                        }
                    });
                }
            }
            Entities.ChangeStatusDialog = ChangeStatusDialog;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeTagsDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get selectNode() {
                    return this.node.find("select");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-entity-management-change-tags-dialog">
                        <div role="toolbar"></div>
                        <div role="editor"></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Entities | Change Tags",
                        height: 250,
                        width: 450,
                        maximized: false,
                        resizable: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.editor_init();
                    this.toolbar_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Entities.ChangeTagsDialogToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.UI.Controls.TagEditorBatch({
                        insertAt: "div[role=editor]"
                    });
                    this.controls.add(this.m_editor);
                }
                closeAndReturn() {
                    this.close({
                        name: "ok",
                        data: this.m_editor.items
                    });
                }
                setCommandState() {
                    let setState = this.m_editor != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/entities/change-tags-dialog": {
                            $editor: this.m_editor
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new ChangeTagsDialog(options);
                }
            }
            Entities.ChangeTagsDialog = ChangeTagsDialog;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeTagsDialogCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$editor", null);
                }
                get editor() {
                    return this.state.get("$editor");
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/entities/change-tags-dialog": {
                            $editor: this.editor
                        }
                    }, { force: true });
                }
            }
            Entities.ChangeTagsDialogCommand = ChangeTagsDialogCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class AddTagsCommand extends Entities.ChangeTagsDialogCommand {
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Manage.Tags.TagsSelectionDialog.open({
                        title: "Select | Tags to Add",
                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                        select: {
                            ok: (sender, e) => {
                                this.editor.addTag(e.tags);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "tags/add",
                        tooltip: "Add tags to be added to the selected entities.",
                        label: "Add Tags",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Entities.AddTagsCommand = AddTagsCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class RemoveTagsCommand extends Entities.ChangeTagsDialogCommand {
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Manage.Tags.TagsSelectionDialog.open({
                        title: "Select | Tags to Remove",
                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                        select: {
                            ok: (sender, e) => {
                                this.editor.removeTag(e.tags);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "tags/remove",
                        tooltip: "Add tags to be removed from the selected entities.",
                        label: "Remove Tags",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Entities.RemoveTagsCommand = RemoveTagsCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class RemoveTagsPatternCommand extends Entities.ChangeTagsDialogCommand {
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Manage.Tags.TagPatternDialog.open({
                        pattern: "",
                        select: {
                            ok: (sender, e) => {
                                this.editor.removeTag([e.newPattern]);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "tags/remove-pattern",
                        tooltip: "Add pattern to remove tags in batch.",
                        label: "Remove Tags with Pattern",
                        icon: "magic_wand.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Entities.RemoveTagsPatternCommand = RemoveTagsPatternCommand;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeTagsDialogCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/entities/change-tags-dialog");
                }
                registerCommands(e) {
                    e.commands.add(new Entities.AddTagsCommand());
                    e.commands.add(new Entities.RemoveTagsCommand());
                    e.commands.add(new Entities.RemoveTagsPatternCommand());
                }
            }
            Entities.ChangeTagsDialogCommands = ChangeTagsDialogCommands;
            Jade.CommandGroups.add(ChangeTagsDialogCommands);
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Entities;
        (function (Entities) {
            class ChangeTagsDialogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/entities/change-tags-dialog";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:tags/add`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:tags/remove`
                    }));
                }
            }
            Entities.ChangeTagsDialogToolbar = ChangeTagsDialogToolbar;
        })(Entities = Manage.Entities || (Manage.Entities = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            let CssClass;
            (function (CssClass) {
                CssClass["EntityTypeModule"] = "-pdjs-manage-module-entity-type";
                CssClass["EntityTypeActions"] = "-pdjs-manage-module-entity-type-actions";
                CssClass["EntityTypeEditor"] = "-pdjs-manage-module-entity-type-editor";
                CssClass["EntityTypeExplorer"] = "-pdjs-manage-module-entity-type-explorer";
                CssClass["ExplorerModelTree"] = "-pdjs-manage-module-entity-type-explorer-model-tree";
            })(CssClass = EntityType.CssClass || (EntityType.CssClass = {}));
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeActions extends PDJS.Shared.UI.Controls.PanelMenu {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return this.modelNode.entityTypeId;
                }
                get entityTypeName() {
                    return this.modelNode.entityTypeName;
                }
                get modelNode() {
                    return this.m_modelNode;
                }
                set modelNode(value) {
                    this.m_modelNode = value;
                }
                load(modelNode) {
                    this.modelNode = modelNode;
                    this.controls.clear();
                    this.addItems();
                }
                template() {
                    return `<div class="${EntityType.CssClass.EntityTypeActions} ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                addItems() {
                    switch (true) {
                        case this.modelNode.formTypeId === "canvas":
                            this.addCanvasItems();
                            break;
                        case this.modelNode.formTypeId === "list.data":
                            this.addListDataExtensionItems();
                            break;
                    }
                    this.addGlobalItems();
                }
                addCanvasItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Extensions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/data-model-properties",
                        label: "Manage Property Data Extensions"
                    }));
                }
                addListDataExtensionItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Extensions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/data-model-list",
                        label: "Manage List Data Extensions"
                    }));
                }
                addGlobalItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Entity Type"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#",
                        label: "Manage Search Groups",
                        click: (e) => {
                            PDJS.Manage.Views.SearchGroupsDialog.open({
                                title: `Manage | Search Groups for ${this.entityTypeName}`,
                                entityTypeId: this.entityTypeId
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#",
                        label: "Assign Folder Expressions",
                        click: (e) => {
                            PDJS.Manage.EntityTypes.ExpressionAssignmentDialog.open({
                                title: "Assign | Folder Expressions",
                                entityTypeId: this.entityTypeId
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Tag...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewTagDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tags",
                        label: "Manage Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Expression...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewExpressionDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tag-expressions",
                        label: "Manage Expressions"
                    }));
                }
            }
            EntityType.EntityTypeActions = EntityTypeActions;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeCommandBase extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$editor", null);
                    this.state.set("$explorer", null);
                    this.state.set("$module", null);
                    this.state.set("$targetNodeId", null);
                }
                get nodes() {
                    return this.explorer.explorerModel;
                }
                get explorer() {
                    return this.state.get("$explorer");
                }
                get editor() {
                    return this.state.get("$editor");
                }
                get module() {
                    return this.state.get("$module");
                }
                get selectedModelNode() {
                    return this.contextMenuNode || this.explorer.selectedModelNode;
                }
                get contextMenuNode() {
                    this.ensureContextMenuNode();
                    return this.m_contextMenuNode;
                }
                get contextMenuNodeId() {
                    return this.state.get("$targetNodeId");
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type": {
                            $editor: this.editor,
                            $explorer: this.explorer,
                            $module: this.module,
                            $targetNodeId: this.contextMenuNodeId
                        }
                    }, { force: true });
                }
                ensureContextMenuNode() {
                    if (this.contextMenuNodeId != null) {
                        this.m_contextMenuNode =
                            this.nodes.getNode(this.contextMenuNodeId);
                    }
                }
            }
            EntityType.EntityTypeCommandBase = EntityTypeCommandBase;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class AddNodeCommand extends EntityType.EntityTypeCommandBase {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.module.monitor.go({
                        directive: () => {
                            this.showAddDialog();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/add",
                        tooltip: "Add a new explorer folder to the selected explorer folder.",
                        label: "New",
                        icon: "add.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                addNodeSuccess(nodeOptions) {
                    let node = new EntityType.ExplorerModel.Node(nodeOptions);
                    let parent = this.selectedModelNode;
                    parent.nodes.add(node);
                    this.explorer.tree.addNode({
                        modelNode: node,
                        parent: parent
                    });
                    setTimeout(() => {
                        this.explorer.tree.select(node, false);
                        this.setCommandState();
                    }, 100);
                }
                showAddDialog() {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Folder",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.ExplorerModel.ExplorerFolderUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.ExplorerModel.ExplorerFolderArbiter",
                            properties: {
                                parentId: this.selectedModelNode.id
                            }
                        },
                        select: {
                            "ok": (sender, data) => {
                                this.addNodeSuccess(_.extend(data.target, { type: "folder" }));
                            }
                        }
                    });
                }
            }
            EntityType.AddNodeCommand = AddNodeCommand;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class DeleteNodeCommand extends EntityType.EntityTypeCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(state) {
                    var _a;
                    super.onStateChanged(state);
                    this.enabled = ((_a = this.selectedModelNode) === null || _a === void 0 ? void 0 : _a.type) == "folder";
                }
                onExecute(e) {
                    super.onExecute(e);
                    let message = this.selectedModelNode.nodes.count == 0 ?
                        `Delete the "${this.selectedModelNode.name}" explorer folder?` :
                        `Delete the "${this.selectedModelNode.name}" explorer folder and all its children?`;
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Explorer Folder",
                        message: message,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.deleteNode();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/delete",
                        tooltip: "Delete the selected explorer folder.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                deleteNode() {
                    let service = new PDJS.Services.Manage.EntityTypes.ExplorerModelService();
                    service.deleteNode({
                        nodeId: this.selectedModelNode.id,
                        success: (e) => {
                            this.deleteNodeSuccess();
                        },
                        complete: (e) => {
                            this.setCommandState();
                        }
                    });
                }
                deleteNodeSuccess() {
                    let node = this.selectedModelNode;
                    this.selectedModelNode.remove();
                    this.explorer.tree.removeNode(node);
                    this.setCommandState();
                }
            }
            EntityType.DeleteNodeCommand = DeleteNodeCommand;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class SaveNodeCommand extends EntityType.EntityTypeCommandBase {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    let module = PDJS.Manage.Modules.instance.current;
                    this.editor.commit({
                        success: (e) => {
                            this.updateNode(e.target);
                            if (e.target.isRoot != undefined) {
                                this.publishEntityNameChange(e.target);
                            }
                            if (e.target.formTypeId == "canvas") {
                                this.publishFolderNameChange(e.target.form.canvasId, e.target.name);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/save",
                        tooltip: "Save changes made to the selected explorer folder.",
                        label: "Save",
                        icon: "floppy_disk.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                updateNode(target) {
                    this.selectedModelNode.name = target.name;
                    this.selectedModelNode.icon = target.icon;
                    this.selectedModelNode.isActive = target.isActive;
                    this.selectedModelNode.isTab = target.isTab;
                    this.selectedModelNode.isHidden = target.isHidden;
                    this.explorer.tree.applyTemplate(this.selectedModelNode.id);
                }
                publishEntityNameChange(e) {
                    EntityType.EventsHub.entityTypeRenamedPublish({
                        entityTypeId: e.id,
                        entityTypeName: e.name
                    });
                    this.publishFolderNameChange(e.createCanvasId, `Create Dialog`);
                    this.publishFolderNameChange(e.propertiesCanvasId, `Properties Dialog`);
                }
                publishFolderNameChange(id, name) {
                    Manage.Canvas.EventsHub.canvasRenamedPublish({
                        canvasId: id,
                        canvasName: name
                    });
                }
            }
            EntityType.SaveNodeCommand = SaveNodeCommand;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            let DropType;
            (function (DropType) {
                DropType["over"] = "over";
                DropType["before"] = "before";
                DropType["after"] = "after";
            })(DropType || (DropType = {}));
            class MoveNodeCommand extends EntityType.EntityTypeCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selectedModelNode != null;
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.moveNode(e);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/move",
                        tooltip: "Move",
                        label: "Move",
                        icon: "undo.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                moveNode(args) {
                    let service = new PDJS.Services.Manage.EntityTypes.ExplorerModelService();
                    service.moveNode({
                        sourceId: args.srcNodeId,
                        destinationId: args.dstNodeId,
                        dropType: this.getDropTypeInteger(args.dropType),
                        complete: (e) => {
                            this.setCommandState();
                        }
                    });
                }
                getDropTypeInteger(dropType) {
                    switch (dropType) {
                        case "over":
                            return 0;
                        case "before":
                            return 1;
                        case "after":
                            return 2;
                    }
                }
            }
            EntityType.MoveNodeCommand = MoveNodeCommand;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeCommands extends Jade.CommandGroup {
                constructor() {
                    super("manage/entity-type");
                }
                registerCommands(e) {
                    e.commands.add(new EntityType.AddNodeCommand());
                    e.commands.add(new EntityType.DeleteNodeCommand());
                    e.commands.add(new EntityType.SaveNodeCommand());
                    e.commands.add(new EntityType.MoveNodeCommand());
                }
            }
            EntityType.EntityTypeCommands = EntityTypeCommands;
            Jade.CommandGroups.add(EntityTypeCommands);
            class EntityTypeContextMenuCommands extends Jade.CommandGroup {
                constructor() {
                    super("manage/entity-type/context-menu");
                }
                registerCommands(e) {
                    e.commands.add(new EntityType.AddNodeCommand());
                    e.commands.add(new EntityType.DeleteNodeCommand());
                    e.commands.add(new EntityType.SaveNodeCommand());
                    e.commands.add(new EntityType.MoveNodeCommand());
                }
            }
            EntityType.EntityTypeContextMenuCommands = EntityTypeContextMenuCommands;
            Jade.CommandGroups.add(EntityTypeContextMenuCommands);
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get modelNode() {
                    return this.m_modelNode;
                }
                set modelNode(value) {
                    this.m_modelNode = value;
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get onCommitCallback() {
                    return this.state.get("onCommit", () => { });
                }
                template() {
                    return `<div class="${EntityType.CssClass.EntityTypeEditor}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Settings</div>
                        <div role="menu"></div>
                        <div data-controls></div>
                    </div>`;
                }
                load(node) {
                    this.modelNode = node;
                    switch (node.type) {
                        case "entity-type":
                            this.entityType_load();
                            break;
                        case "folder":
                            this.folder_load();
                            break;
                    }
                }
                commit(args = {}) {
                    let successFunction = (args.success || (() => { }));
                    let wrappedFunction = (e) => {
                        successFunction(e);
                        this.onCommitCallback();
                    };
                    args.success = wrappedFunction;
                    this.m_editor.commit(args);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                    this.menu_init();
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Features.FeatureEditor({
                        onFeatureValueChanged: (e) => {
                            this.onChangeCallback();
                        },
                        onCommitSuccess: (e) => {
                            PDJS.Shared
                                .MessageStack
                                .instance
                                .success("Changes Saved");
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new EntityType.EntityTypeEditorToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                entityType_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.modelNode.entityTypeId,
                            targetType: "ProspectDirector.Web.Shared.Modules.EntityTypes.EntityTypeUIO",
                            type: "ProspectDirector.Web.Manage.Modules.EntityTypes.EntityTypeArbiter"
                        },
                        initialized: false
                    });
                }
                folder_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.modelNode.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.ExplorerModel.ExplorerFolderUIO",
                            type: "ProspectDirector.Web.Manage.Modules.ExplorerModel.ExplorerFolderArbiter"
                        },
                        initialized: false
                    });
                }
            }
            EntityType.EntityTypeEditor = EntityTypeEditor;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "manage/entity-type:node/save"
                    }));
                }
            }
            EntityType.EntityTypeEditorToolbar = EntityTypeEditorToolbar;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeExplorer extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get selectedModelNode() {
                    var _a;
                    return (_a = this.m_tree) === null || _a === void 0 ? void 0 : _a.selectedModelNode;
                }
                get explorerModel() {
                    return this.state.get("explorerModel");
                }
                get tree() {
                    return this.m_tree;
                }
                template() {
                    return `<div class="${EntityType.CssClass.EntityTypeExplorer} ${Manage.CssClass.NavigationPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Explorer Model</div>
                        <div role="menu"></div>
                        <div class="${Manage.CssClass.ModuleSectionBody}" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.tree_init();
                }
                tree_init() {
                    this.m_tree = new EntityType.ExplorerModelTree({
                        entityTypeId: this.entityTypeId,
                        explorerModel: this.explorerModel,
                        onChange: (e) => {
                            this.onChangeCallback(e.modelNode);
                        }
                    });
                    this.controls.add(this.m_tree);
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new EntityType.EntityTypeExplorerToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
            }
            EntityType.EntityTypeExplorer = EntityTypeExplorer;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeExplorerContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "manage/entity-type/context-menu:node/add"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "manage/entity-type/context-menu:node/delete"
                    }));
                }
                onOpen(e) {
                    super.onOpen(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type/context-menu": {
                            $targetNodeId: e.target.data("id")
                        }
                    }, { force: true });
                }
            }
            EntityType.EntityTypeExplorerContextMenu = EntityTypeExplorerContextMenu;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeExplorerToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "manage/entity-type:node/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "manage/entity-type:node/delete"
                    }));
                }
            }
            EntityType.EntityTypeExplorerToolbar = EntityTypeExplorerToolbar;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            class EntityTypeModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return parseInt(this.settings.targetId);
                }
                get explorerModel() {
                    this.ensureExplorerModel();
                    return this.m_explorerModel;
                }
                get explorerNode() {
                    return this.node.find("div[role=explorer]");
                }
                get editorNode() {
                    return this.node.find("div[role=editor]");
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} ${EntityType.CssClass.EntityTypeModule}">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.addSubscribers();
                }
                onModuleLoad(e) {
                    super.onModuleLoad(e);
                    e.addStep(() => this.module_init());
                }
                actions_init() {
                    this.m_actions = new EntityType.EntityTypeActions({
                        insertAt: "div[data-id=pane-3]",
                        entityTypeId: this.entityTypeId
                    });
                    this.controls.add(this.m_actions);
                }
                addSubscribers() {
                    this.subscriptions.add(EntityType.EventsHub.entityTypeRenamedSubscribe(e => {
                        if (this.settings.targetId == e.entityTypeId.toString()) {
                            this.settings.label = e.entityTypeName;
                        }
                    }));
                }
                editor_init() {
                    this.m_editor = new EntityType.EntityTypeEditor({
                        insertAt: "div[data-id=pane-2]",
                        onCommit: (e) => {
                            this.settings.hasChanges = false;
                        },
                        onChange: (e) => {
                            this.settings.hasChanges = true;
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                ensureExplorerModel() {
                    if (!this.m_explorerModel) {
                        this.m_explorerModel = new EntityType.ExplorerModel.ExplorerModel({
                            nodes: [this.state.get("explorerModel")]
                        });
                    }
                }
                explorer_init() {
                    this.m_explorer = new EntityType.EntityTypeExplorer({
                        insertAt: "div[data-id=pane-1]",
                        entityTypeId: this.entityTypeId,
                        explorerModel: this.explorerModel,
                        onChange: (e) => {
                            this.m_actions.load(e);
                            this.m_editor.load(e);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_explorer);
                }
                module_init() {
                    return this.modulePromise((resolve, reject) => {
                        let service = new PDJS.Services.EntityTypes.EntityTypeService();
                        service.index({
                            entityTypeId: parseInt(this.settings.targetId),
                            success: (e) => {
                                this.state.set("explorerModel", e.data.explorerModel);
                                this.editor_init();
                                this.explorer_init();
                                this.setCommandState();
                                this.settings.label = e.data.entityTypeName;
                                resolve();
                            },
                            error: (e) => { reject(e); }
                        });
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "300px" },
                            { resizable: true },
                            { resizable: true, size: "300px" }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type": {
                            $editor: this.m_editor,
                            $explorer: this.m_explorer,
                            $module: this,
                            $targetNodeId: null
                        }
                    }, { force: true });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type/context-menu": {
                            $editor: this.m_editor,
                            $explorer: this.m_explorer,
                            $module: this,
                            $targetNodeId: null
                        }
                    }, { force: true });
                }
            }
            EntityType.EntityTypeModule = EntityTypeModule;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            let Events;
            (function (Events) {
                Events["EntityTypeRenamed"] = "entity-type/renamed";
                Events["ExplorerFolderRenamed"] = "entity-type/explorer-folder/renamed";
            })(Events = EntityType.Events || (EntityType.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static entityTypeRenamedPublish(args) {
                    this.global.publish(Events.EntityTypeRenamed, args);
                }
                static explorerFolderRenamedPublish(args) {
                    this.global.publish(Events.ExplorerFolderRenamed, args);
                }
                static entityTypeRenamedSubscribe(handler) {
                    return this.global.subscribe(Events.EntityTypeRenamed, handler);
                }
                static explorerFolderRenamedSubscribe(handler) {
                    return this.global.subscribe(Events.ExplorerFolderRenamed, handler);
                }
            }
            EntityType.EventsHub = EventsHub;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class CanvasEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get linkNode() {
                        return this.node.find("a");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get canvasType() {
                        return this.source.state.get("canvasType");
                    }
                    get isFileBased() {
                        return this.source.state.get("isFileBased");
                    }
                    get isListBased() {
                        return this.source.state.get("isListBased");
                    }
                    get documentTypeId() {
                        return this.source.getFeatureValueByProp("documentTypeIdProp");
                    }
                    get entityTypeId() {
                        return this.source.getFeatureValueByProp("entityTypeIdProp");
                    }
                    get extensionId() {
                        return this.source.getFeatureValueByProp("extensionIdProp");
                    }
                    template() {
                        return `<div class="-fb-canvas-editor">
                    <div>
                        <a href="#">Click here to edit the canvas</a>
                    </div>
                    <div>
                        <button ${this.source.readOnly ? "readonly" : ""}>...</button>
                    </div>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.button_onClick, this));
                        this.linkNode.on(Jade.BrowserEvent.CLICK, _.bind(this.button_onClick, this));
                    }
                    button_onClick(e) {
                        window.location.href = `#/module/canvas-editor/${this.source.getFeaturePrimaryValue()}`;
                        return false;
                    }
                }
                Editors.CanvasEditor = CanvasEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.Manage.Modules.ExplorerModel.CanvasEditor", CanvasEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            let CssSelectors;
            (function (CssSelectors) {
                CssSelectors["node"] = "li[data-uid]";
                CssSelectors["innerNode"] = "li[data-uid] span.k-in";
                CssSelectors["topMidBot"] = ".k-top, .k-mid, .k-bot";
            })(CssSelectors || (CssSelectors = {}));
            class ExplorerModelTree extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get explorerModel() {
                    return this.state.get("explorerModel");
                }
                get tree() {
                    return this.m_tree;
                }
                get treeNode() {
                    return this.node.children("div[role=tree]");
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get selectedModelNode() {
                    return this.getSelectedModelNode();
                }
                get selectedNode() {
                    return this.tree.select();
                }
                select(modelNode, expand = false) {
                    let node = this.getNodeById(modelNode.id);
                    if (node.length > 0) {
                        this.tree.select(node);
                        if (expand) {
                            this.tree.expand(node);
                        }
                    }
                }
                template() {
                    return `<div class="${EntityType.CssClass.ExplorerModelTree}">
                        <div role="tree"></div>
                    </div>`;
                }
                addNode(e) {
                    var _a;
                    let parentNode = this.getNodeById((_a = e.parent) === null || _a === void 0 ? void 0 : _a.id) ||
                        this.selectedNode;
                    let addedNode = this.tree.append(e.modelNode.toKendoJSON(), parentNode);
                    this.tree.expand(parentNode);
                    if (addedNode.length > 0) {
                        this.tree.select(addedNode);
                        addedNode.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                    }
                }
                removeNode(node) {
                    let removeNode = this.getNodeById(node.id);
                    let fallbackNode = null;
                    fallbackNode = removeNode.next(CssSelectors.node);
                    if (fallbackNode.length == 0) {
                        fallbackNode = removeNode.prev(CssSelectors.node);
                    }
                    if (fallbackNode.length == 0) {
                        fallbackNode = removeNode.parent().closest(CssSelectors.node);
                    }
                    this.tree.remove(removeNode);
                    if (fallbackNode.length > 0) {
                        this.tree.select(fallbackNode);
                        fallbackNode.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                    }
                }
                applyTemplate(modelNodeId) {
                    var _a;
                    let modelNode = this.explorerModel.getNode(modelNodeId);
                    if (modelNode == null) {
                        return;
                    }
                    let uid = (_a = this.tree.dataSource.get(modelNode.id)) === null || _a === void 0 ? void 0 : _a.uid;
                    let span = $(modelNode.toMarkup());
                    let node = this.tree.findByUid(uid);
                    let kin = node.find(".k-in").first();
                    node.attr("data-id", modelNode.id);
                    node.attr("data-type", modelNode.type);
                    kin.empty();
                    kin.html(span[0].outerHTML);
                    span.hide();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.select(this.explorerModel.nodes.first(), true);
                    this.contextMenu_init();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                }
                contextMenu_init() {
                    if (this.m_treeContextMenu) {
                        return;
                    }
                    this.m_treeContextMenu =
                        new PDJS.Shared.UI.Controls.TreeViewContextMenu({
                            tree: this.tree,
                            segments: [
                                {
                                    type: "PDJS.Manage.EntityType.EntityTypeExplorerContextMenu"
                                }
                            ]
                        });
                    this.controls.add(this.m_treeContextMenu);
                }
                getSelectedModelNode() {
                    let result = null;
                    let item = this.tree.dataItem(this.tree.select());
                    if (item) {
                        result = this.explorerModel.getNode(item.id);
                    }
                    return result;
                }
                tree_init() {
                    let data;
                    this.m_tree = this.treeNode.kendoTreeView({
                        dataTextField: "name",
                        change: _.bind(this.tree_change, this),
                        dragAndDrop: true,
                        dataSource: new kendo.data.HierarchicalDataSource({
                            schema: {
                                model: {
                                    children: "nodes",
                                    hasChildren: (e) => {
                                        return e.nodes && e.nodes.length > 0;
                                    }
                                }
                            }
                        }),
                        dataBound: _.bind(this.tree_dataBound, this),
                        drop: _.bind(this.tree_drop, this),
                        template: _.bind(this.tree_template, this)
                    }).data("kendoTreeView");
                    this.tree.templates.dragClue = (data) => {
                        return `<div class="k-header k-drag-clue -pdjs-manage-process-tree-drag-hint">
                            <span class="k-drag-icon">
                                <span class="k-icon k-drag-status" />
                            </span>
                            <span class="k-drag-text">
                                ${data.item.name}
                            </span>
                        </div>`;
                    };
                    data = this.explorerModel.nodes.toKendoJSON();
                    this.tree.dataSource.data(data);
                    new PDJS.Shared.Navigate.TreeViewProxy({
                        tree: this.m_tree
                    });
                }
                tree_change(e) {
                    this.onChangeCallback({
                        modelNode: this.selectedModelNode,
                        node: this.selectedNode
                    });
                }
                tree_dataBound(e) {
                    if (!this.tree) {
                        return;
                    }
                    let item = e.node ?
                        this.tree.dataItem(e.node) :
                        this.tree.dataSource.get(this.explorerModel.nodes.first().id);
                    if (item) {
                        this.initializeNodes(item.id);
                    }
                }
                tree_drop(e) {
                    let srcNode = $(e.sourceNode).closest(".k-item");
                    let dstNode = $(e.dropTarget).closest(".k-item");
                    let srcData = this.tree.dataItem(srcNode);
                    let dstData = this.tree.dataItem(dstNode);
                    let srcType = (srcData === null || srcData === void 0 ? void 0 : srcData.type) || "unknown";
                    let dstType = (dstData === null || dstData === void 0 ? void 0 : dstData.type) || "unknown";
                    let dropType = e.dropPosition;
                    e.valid =
                        e.valid &&
                            !this.m_treeMoveSuspended &&
                            (this.isValidAdd(srcType, dstType, dropType) ||
                                this.isValidInsert(srcType, dstType, dropType));
                    if (e.valid) {
                        this.m_treeMoveSuspended = true;
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("manage/entity-type:node/move", {
                            srcNodeId: srcData.id,
                            dstNodeId: dstData.id,
                            dropType: dropType
                        });
                        setTimeout(() => { this.m_treeMoveSuspended = false; }, 1000);
                    }
                }
                tree_template(e) {
                    let modelNode = this.explorerModel.getNode(e.item.id);
                    let result = modelNode != null ?
                        modelNode.toMarkup() : "render error";
                    return result;
                }
                initializeNodes(id) {
                    let node = this.explorerModel.getNode(id);
                    let data = node.nodes.toJSON() || [];
                    if (node) {
                        this.applyTemplate(node.id);
                    }
                    data.forEach(item => {
                        this.initializeNodes(item.id);
                    });
                }
                getNodeById(id) {
                    let result = null;
                    let data = this.tree.dataSource.get(id);
                    if (data) {
                        result = this.tree.findByUid(data.uid);
                    }
                    return result;
                }
                isValidAdd(srcType, dstType, dropType) {
                    return (dropType == "add" || dropType == "over");
                }
                isValidInsert(srcType, dstType, dropType) {
                    let isInsert = (dropType == "insert-top" ||
                        dropType == "insert-middle" ||
                        dropType == "insert-bottom" ||
                        dropType == "before" ||
                        dropType == "after");
                    return isInsert && dstType != "entity-type";
                }
            }
            EntityType.ExplorerModelTree = ExplorerModelTree;
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            var ExplorerModel;
            (function (ExplorerModel) {
                let CssClass;
                (function (CssClass) {
                    CssClass["Node"] = "-pdjs-manage-entity-type-explorer-model-node";
                })(CssClass = ExplorerModel.CssClass || (ExplorerModel.CssClass = {}));
            })(ExplorerModel = EntityType.ExplorerModel || (EntityType.ExplorerModel = {}));
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            var ExplorerModel;
            (function (ExplorerModel_2) {
                class ExplorerModel extends PDJS.Core.EntityTypes.ExplorerModel.ExplorerModel {
                    toKendoJSON() {
                        return {
                            nodes: this.nodes.toKendoJSON()
                        };
                    }
                    getCheckedNodes() {
                        let result = [];
                        this.forEachNode((node) => {
                            if (node.checked) {
                                result.push(node);
                            }
                        });
                        return result;
                    }
                    forEachNode(callback, source = null) {
                        let nodes = source ? source.nodes : this.nodes;
                        nodes.each((item) => {
                            this.forEachNode(callback, item);
                        });
                    }
                    createNodeCollection(nodes) {
                        return new ExplorerModel_2.NodeCollection({
                            explorerModel: this,
                            parent: null,
                            nodes: nodes
                        });
                    }
                }
                ExplorerModel_2.ExplorerModel = ExplorerModel;
            })(ExplorerModel = EntityType.ExplorerModel || (EntityType.ExplorerModel = {}));
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            var ExplorerModel;
            (function (ExplorerModel) {
                class Node extends PDJS.Core.EntityTypes.ExplorerModel.Node {
                    constructor(options) {
                        super(options);
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get entityTypeName() {
                        return this.state.get("entityTypeName");
                    }
                    get formTypeId() {
                        return this.state.get("formTypeId");
                    }
                    get isHidden() {
                        return this.state.get("isHidden");
                    }
                    set isHidden(value) {
                        this.state.set("isHidden", value);
                    }
                    get isTab() {
                        return this.state.get("isTab");
                    }
                    set isTab(value) {
                        this.state.set("isTab", value);
                    }
                    get isActive() {
                        return this.state.get("isActive");
                    }
                    set isActive(value) {
                        this.state.set("isActive", value);
                    }
                    get checked() {
                        return this.state.get("isActive");
                    }
                    set checked(value) {
                        this.state.set("checked", value);
                    }
                    toJSON() {
                        return super.toJSON();
                    }
                    toKendoJSON() {
                        return _.extend({
                            hasChildren: this.nodes.count > 0
                        }, this.toJSON());
                    }
                    toMarkup() {
                        return `<div class="${ExplorerModel.CssClass.Node}" ${this.isTab ? "tabbed" : ""} ${this.isActive === false ? "disabled" : ""}>
                        <div role="icon"><img src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                    }
                    createNodeCollection(nodes) {
                        return new ExplorerModel.NodeCollection({
                            nodes: nodes,
                            explorerModel: this.explorerModel,
                            parent: this
                        });
                    }
                }
                ExplorerModel.Node = Node;
            })(ExplorerModel = EntityType.ExplorerModel || (EntityType.ExplorerModel = {}));
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityType;
        (function (EntityType) {
            var ExplorerModel;
            (function (ExplorerModel) {
                class NodeCollection extends PDJS.Core.EntityTypes.ExplorerModel.NodeCollection {
                    constructor(options) {
                        super(options);
                    }
                    toKendoJSON() {
                        return this.transform((item) => {
                            return item.toKendoJSON();
                        });
                    }
                    createNode(data) {
                        return new ExplorerModel.Node(data);
                    }
                }
                ExplorerModel.NodeCollection = NodeCollection;
            })(ExplorerModel = EntityType.ExplorerModel || (EntityType.ExplorerModel = {}));
        })(EntityType = Manage.EntityType || (Manage.EntityType = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get entityType() {
                    return this.state.get("tag");
                }
                set entityType(value) {
                    this.state.set("tag", value);
                }
                load(entityType) {
                    this.entityType = entityType;
                }
                template() {
                    return `<div class="-pdjs-manage-tags-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Management",
                        url: "#/module/entity-management"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Type Relationships",
                        url: "#/module/entity-type-relationships"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Document Types",
                        url: "#/module/document-types"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Tag...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewTagDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tags",
                        label: "Manage Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Expression...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewExpressionDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tag-expressions",
                        label: "Manage Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Insights"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Type Security",
                        url: "#/module/insights-viewer/enttypesecurity"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Explorer Models",
                        url: "#/module/insights-viewer/explorermodel"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Form Fields",
                        url: "#/module/insights-viewer/formfields"
                    }));
                }
            }
            EntityTypes.EntityTypesActions = EntityTypesActions;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selected() {
                    return _.first(this.grid.selections);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/entity-types": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            EntityTypes.EntityTypesCommand = EntityTypesCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class DeleteEntityTypeCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected entity type.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        title: "Delete | Entity Type",
                        message: `Delete the "${this.selected.name}" entity type?`,
                        select: (e) => {
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                            e.close();
                        }
                    });
                }
                executeDelete() {
                    let service = new PDJS.Services.EntityTypes.EntityTypesService();
                    service.deleteEntityType({
                        id: this.selected.id,
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            EntityTypes.DeleteEntityTypeCommand = DeleteEntityTypeCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EditEntityTypeCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the properties of the selected entity type.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let entityType = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${entityType.name}`,
                        height: 550,
                        width: 500,
                        args: {
                            targetId: entityType.id,
                            targetType: "ProspectDirector.Web.Shared.Modules.EntityTypes.EntityTypeUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.EntityTypes.EntityTypeArbiter",
                            properties: {
                                isDialog: true
                            }
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                Manage.EntityType.EventsHub.entityTypeRenamedPublish({
                                    entityTypeId: e.target.id,
                                    entityTypeName: e.target.name
                                });
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            EntityTypes.EditEntityTypeCommand = EditEntityTypeCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class NewEntityTypeCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type/new",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new entity type.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Entity Type",
                        height: 550,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.EntityTypes.EntityTypeUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.EntityTypes.EntityTypeArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            EntityTypes.NewEntityTypeCommand = NewEntityTypeCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class OpenEntityTypeCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type/open",
                        label: "Open",
                        icon: "arrow_right_green.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Open the selected entity type.",
                        iconSetId: "pd"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    window.location.hash = `/module/entity-type/${this.selected.id}`;
                }
            }
            EntityTypes.OpenEntityTypeCommand = OpenEntityTypeCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class OpenExpressionsCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "expressions/open",
                        label: "Expressions",
                        icon: "formula.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: `Assign expressions to explorer model folders of the selected entity type.<br/><br/>
                          Expressions control the visibility of explorer model folders based on the presence or absence of tags on an entity.`,
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let entityType = _.first(this.selections);
                    PDJS.Manage.EntityTypes.ExpressionAssignmentDialog.open({
                        title: `${entityType.name} | Assign Expressions`,
                        entityTypeId: entityType.id
                    });
                }
            }
            EntityTypes.OpenExpressionsCommand = OpenExpressionsCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class OpenSearchGroupsCommand extends EntityTypes.EntityTypesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "search-groups/open",
                        label: "Search Groups",
                        icon: "magnifying_glass.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: `Configure Search Groups for the selected Entity Type.<br/><br/>
                          Search groups control what data associated with this Entity Type is available for inclusion in Views and Charts.`,
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let entityType = _.first(this.selections);
                    PDJS.Manage.Views.SearchGroupsDialog.open({
                        title: `Manage | Search Groups for ${entityType.name}`,
                        entityTypeId: entityType.id
                    });
                }
            }
            EntityTypes.OpenSearchGroupsCommand = OpenSearchGroupsCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/entity-types");
                }
                registerCommands(e) {
                    e.commands.add(new EntityTypes.DeleteEntityTypeCommand());
                    e.commands.add(new EntityTypes.EditEntityTypeCommand());
                    e.commands.add(new EntityTypes.NewEntityTypeCommand());
                    e.commands.add(new EntityTypes.OpenEntityTypeCommand());
                    e.commands.add(new EntityTypes.OpenExpressionsCommand());
                    e.commands.add(new EntityTypes.OpenSearchGroupsCommand());
                }
            }
            EntityTypes.EntityTypesCommands = EntityTypesCommands;
            Jade.CommandGroups.add(EntityTypesCommands);
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-entity-types-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Entity Types</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new EntityTypes.EntityTypesGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No entity types."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/entity-types:entity-type/open");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.EntityTypes.EntityTypesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            EntityTypes.EntityTypesGrid = EntityTypesGrid;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/entity-types";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity-type/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity-type/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity-type/open`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:entity-type/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:search-groups/open`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:expressions/open`
                    }));
                }
            }
            EntityTypes.EntityTypesGridContextMenu = EntityTypesGridContextMenu;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/entity-types";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity-type/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity-type/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity-type/open`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:entity-type/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:search-groups/open`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:expressions/open`
                    }));
                }
            }
            EntityTypes.EntityTypesGridToolbar = EntityTypesGridToolbar;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-tags">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new EntityTypes.EntityTypesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new EntityTypes.EntityTypesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.EntityTypes.EntityTypesService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/entity-types": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            EntityTypes.EntityTypesModule = EntityTypesModule;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class ExpressionAssignmentDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get closeButtonNode() {
                    return this.node.find("button[data-command=close]");
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.explorerModel_init();
                    this.toolbar_init();
                    this.closeButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                }
                getDefaultOptions() {
                    return {
                        title: "Expression Assigment",
                        height: "450px",
                        width: "800px"
                    };
                }
                template() {
                    return super.template(`
                <div class="-pdjs-expression-assignment-dialog">
                    <div role="toolbar"></div>
                    <div role="tree"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="close" class="-jadeui-dialog-button">Close</button>
                    </div>
                </div>`);
                }
                onResize() {
                    if (this.m_explorerModel) {
                        this.m_explorerModel.resize();
                    }
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new EntityTypes.ExpressionAssignmentToolbarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                explorerModel_init() {
                    this.m_explorerModel = new EntityTypes.ExpressionAssignmentExplorerModel({
                        insertAt: "[role=tree]",
                        entityTypeId: this.entityTypeId
                    });
                    this.controls.add(this.m_explorerModel);
                }
                okButton_onClick() {
                    let assignments = this.m_explorerModel.getAssignments();
                    let service = new PDJS.Services.Tags.ExpressionService();
                    if (assignments.length > 0) {
                        service.setFolderExpressions({
                            assignments: assignments,
                            success: (e) => {
                                this.close();
                            }
                        });
                    }
                    else {
                        this.close();
                    }
                }
                static open(options) {
                    return new ExpressionAssignmentDialog(options);
                }
            }
            EntityTypes.ExpressionAssignmentDialog = ExpressionAssignmentDialog;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class ExpressionAssignmentExplorerModel extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get tree() {
                    return this.m_tree;
                }
                get treeNode() {
                    return this.node.children("div[role=tree]");
                }
                get checkboxNodes() {
                    return this.treeNode.find("input[type=checkbox][role=folder-checkbox]");
                }
                resize() {
                    if (this.tree != null) {
                        this.tree.refresh();
                    }
                }
                template() {
                    return `<div class="-pdjs-manage-expression-assignment-explorer-model">
                        <div role="tree" style="border-width:0;"></div>
                    </div>`;
                }
                getAssignments() {
                    let result = [];
                    let view = this.tree.dataSource.view();
                    view.forEach((item) => {
                        if (item.get("changed")) {
                            result[result.length] = item.toJSON();
                        }
                    });
                    return result;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("expression/assign", _.bind(this.setFolderExpressions, this)));
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("expression/select-all-folders", _.bind(this.setAllFoldersSelectState, this)));
                    this.treeNode.on(Jade.BrowserEvent.CLICK, "input[role=folder-checkbox]", _.bind(this.tree_checkbox_click, this));
                }
                tree_init() {
                    let x;
                    this.m_tree = this.treeNode.kendoTreeList({
                        height: "100%",
                        columns: [
                            {
                                field: "folderName",
                                title: "Folder",
                                width: 350,
                                attributes: { style: "position:relative;" },
                                template: (e) => {
                                    return `<label role="gridcellcontent">
                                        <div>
                                            <input role="folder-checkbox" data-folder-id="${e.folderId}" type="checkbox" ${e.selected ? "checked" : ""}/>
                                        </div>
                                        <div>
                                            <img src="${Jade.IconSet.get("pd").resolve(e.folderIcon, Jade.IconSetSizeSpecificDirectory.x16)}" />
                                        </div>
                                        <div>
                                            ${e.folderName}
                                        </div>
                                    </label>`;
                                }
                            },
                            {
                                field: "expressionName",
                                title: "Expression",
                                template: (e) => {
                                    return `<div style="color:${e.updated ? "var(--visiv-success-fore-color)" : "var(--visiv-theme-base-1-text-color)"};">${e.expressionName}</div>`;
                                }
                            }
                        ],
                        dataSource: this.tree_dataSource(),
                        resizable: true
                    }).data("kendoTreeList");
                }
                tree_dataSource() {
                    return new kendo.data.TreeListDataSource({
                        transport: {
                            read: ((e) => {
                                let data = e.data;
                                let folderId = e.data.id;
                                let service = new PDJS.Services.Tags.ExpressionService();
                                service.getFolderExpressions({
                                    entityTypeId: this.entityTypeId,
                                    folderId: folderId,
                                    success: (args) => {
                                        if (folderId == undefined) {
                                            args.data.forEach((item) => {
                                                item.parentId = null;
                                            });
                                        }
                                        args.data.forEach((item) => {
                                            item.expressionName = item.expressionName == null ? "" : item.expressionName;
                                        });
                                        e.success(args.data);
                                    }
                                });
                            })
                        },
                        schema: {
                            model: {
                                id: "folderId",
                                parentId: "parentId",
                                fields: {
                                    folderIcon: { type: "string" },
                                    folderName: { type: "string" },
                                    isTab: { type: "boolean" },
                                    expressionId: { type: "string" },
                                    expressionName: { type: "string" },
                                    selected: { type: "boolean" }
                                }
                            }
                        }
                    });
                }
                tree_checkbox_click(e) {
                    let node = $(e.target);
                    let record = this.tree.dataSource.get(node.data("folder-id"));
                    if (record != null) {
                        record.set("selected", node.is(":checked"));
                        record.set("selected", node.is(":checked"));
                    }
                }
                setFolderExpressions(e) {
                    let view = this.tree.dataSource.view();
                    view.forEach((item) => {
                        item.set("updated", false);
                        if (item.get("selected")) {
                            item.set("selected", false);
                            item.set("expressionId", e.expressionId);
                            item.set("expressionName", e.expressionName);
                            item.set("updated", true);
                            item.set("changed", true);
                        }
                    });
                }
                setAllFoldersSelectState(selected) {
                    let view = this.tree.dataSource.view();
                    view.forEach((item) => {
                        item.set("selected", selected);
                    });
                }
            }
            EntityTypes.ExpressionAssignmentExplorerModel = ExpressionAssignmentExplorerModel;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class ExpressionAssignmentToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "expression-assignment/dialog:expression/assign"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "expression-assignment/dialog:expression/remove"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "expression-assignment/dialog:expression/select-all"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "expression-assignment/dialog:expression/deselect-all"
                    }));
                }
            }
            EntityTypes.ExpressionAssignmentToolbarSegment = ExpressionAssignmentToolbarSegment;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class AssignExpressionsCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/assign",
                        label: "Assign Expression",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                }
                onExecute(e) {
                    PDJS.Manage.Tags.ExpressionsSelectionDialog.open({
                        select: {
                            ok: (sender, e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish("expression/assign", e);
                            }
                        }
                    });
                }
            }
            EntityTypes.AssignExpressionsCommand = AssignExpressionsCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class DeselectAllFolderCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/deselect-all",
                        label: "Deselect All",
                        icon: "checkbox_unchecked.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onExecute(e) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("expression/select-all-folders", false);
                }
            }
            EntityTypes.DeselectAllFolderCommand = DeselectAllFolderCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class ExpressionAssignmentDialogCommands extends Jade.CommandGroup {
                constructor() {
                    super("expression-assignment/dialog");
                }
                registerCommands(e) {
                    e.commands.add(new EntityTypes.AssignExpressionsCommand({}));
                    e.commands.add(new EntityTypes.RemoveExpressionsCommand({}));
                    e.commands.add(new EntityTypes.SelectAllFolderCommand({}));
                    e.commands.add(new EntityTypes.DeselectAllFolderCommand({}));
                }
            }
            EntityTypes.ExpressionAssignmentDialogCommands = ExpressionAssignmentDialogCommands;
            Jade.Application.onStart(() => {
                Jade.CommandGroups.add(ExpressionAssignmentDialogCommands);
            });
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class RemoveExpressionsCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/remove",
                        label: "Remove Expression",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                }
                onExecute(e) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("expression/assign", {
                        expressionId: null,
                        expressionName: ""
                    });
                }
            }
            EntityTypes.RemoveExpressionsCommand = RemoveExpressionsCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class SelectAllFolderCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/select-all",
                        label: "Select All",
                        icon: "checkbox.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onExecute(e) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("expression/select-all-folders", true);
                }
            }
            EntityTypes.SelectAllFolderCommand = SelectAllFolderCommand;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class RelationshipsDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get closeButtonNode() {
                    return this.node.find("button[data-command=close]");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.closeButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-entity-types-relationships-dialog">
                    <div role="tabs"></div>
                    <div role="editor"></div>
                    <div role="viewer"></div>
                    <div role="deck">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="close" class="-jadeui-dialog-button">Close</button>
                    </div>
                </div>`);
                }
                static open(options) {
                    return new RelationshipsDialog(options);
                }
            }
            EntityTypes.RelationshipsDialog = RelationshipsDialog;
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class PopUpEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get clearButtonNode() {
                        return this.node.find("button[role=clear]");
                    }
                    get text() {
                        return this.source.getFeatureValueByProp("textProperty") || "";
                    }
                    set text(value) {
                        this.source.setFeatureValueByProp("textProperty", value);
                    }
                    get defaultText() {
                        return this.source.getFeatureValueByProp("defaultTextProperty") || "";
                    }
                    get defaultTextEnabled() {
                        return this.source.isPropertyDefined("defaultTextProperty");
                    }
                    get emptyText() {
                        return "None";
                    }
                    get hasDefaultText() {
                        return !Jade.String.isNullOrWhiteSpace(this.defaultText);
                    }
                    get hasValue() {
                        return !Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    get popupButtonNode() {
                        return this.node.find("button[role=popup]");
                    }
                    get isClearButtonVisible() {
                        return this.clearButtonNode.is(":visible");
                    }
                    get isPopupButtonVisible() {
                        return this.popupButtonNode.is(":visible");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get imageNode() {
                        return this.node.find("img[role=image]");
                    }
                    get imageVisible() {
                        return this.imageNode.is(":visible");
                    }
                    get maskNode() {
                        return this.node.find("div[role=mask]");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get wasPreviouslyAssignedValue() {
                        return this.m_wasPreviouslyAssignedValue;
                    }
                    set wasPreviouslyAssignedValue(value) {
                        this.m_wasPreviouslyAssignedValue = value;
                    }
                    template() {
                        return `
            <div class="-pdjs-fb-popup-editor">
                <div>
                    <img src="" role="image" />
                </div>
                <div>
                    <input type="text" readonly />
                    <div role="mask"></div>
                </div>
                <div role="buttons">
                    <div>
                        <button ${this.source.readOnly ? "disabled" : ""} role="clear" title="Clear">
                            <i class="icofont-close"></i>
                        </button>
                        <button ${this.source.readOnly ? "disabled" : ""} role="popup" title="Edit">...</button>
                    </div>
                </div>
            </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    clearButton_onClick() {
                    }
                    input_onBlur() {
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.wasPreviouslyAssignedValue = this.hasValue;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.showImage(false);
                        this.showClearButton(false);
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.input_onBlur();
                        });
                        this.clearButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.clearButton_onClick();
                        });
                        this.popupButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.popupButton_onClick();
                        });
                    }
                    popupButton_onClick() {
                    }
                    showClearButton(show) {
                        show ? this.clearButtonNode.show()
                            : this.clearButtonNode.hide();
                    }
                    showImage(show) {
                        show ? this.imageNode.show()
                            : this.imageNode.hide();
                    }
                    showPopUpButton(show) {
                        show ? this.popupButtonNode.show()
                            : this.popupButtonNode.hide();
                    }
                    getDefaultText() {
                        return this.defaultTextEnabled ? this.defaultText : this.emptyText;
                    }
                    setInputText(text) {
                        let isNull = !this.hasValue;
                        let isNullWithDefault = isNull && this.defaultTextEnabled;
                        let isNullWithoutDefault = isNull && !this.defaultTextEnabled;
                        this.clearState();
                        switch (true) {
                            case isNullWithoutDefault:
                                this.inputNode.val(this.getDefaultText());
                                this.toggleState("error");
                                break;
                            case isNullWithDefault:
                                this.inputNode.val(this.getDefaultText());
                                break;
                            default:
                                this.inputNode.val(text !== null && text !== void 0 ? text : this.text);
                                this.toggleState("ok");
                                break;
                        }
                    }
                    toggleState(state) {
                        this.clearState();
                        switch (state) {
                            case "error":
                                this.inputNode.addClass("-fb-grid-input-status-error");
                                break;
                            case "ok":
                                this.inputNode.addClass("-fb-grid-input-status-ok");
                                break;
                        }
                    }
                    clearState() {
                        this.inputNode.removeClass("-fb-grid-input-status-error");
                        this.inputNode.removeClass("-fb-grid-input-status-ok");
                    }
                }
                Editors.PopUpEditor = PopUpEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            class AccessControlEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get acl() {
                    return this.m_acl;
                }
                set acl(value) {
                    this.m_acl = value;
                }
                get aces() {
                    return this.feature.getValue("aces");
                }
                set aces(value) {
                    this.feature.setValue("aces", value);
                }
                get permissions() {
                    return this.feature.getValue("permissions");
                }
                get securableId() {
                    return this.feature.getValue("securableId");
                }
                get enabled() {
                    return this.feature.getValue("enabled");
                }
                get isAdvancedAllowed() {
                    return this.feature.getValue("isAdvancedAllowed");
                }
                focus() {
                    super.focus();
                    if (this.m_editor) {
                        this.m_editor.resize();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.acl_init();
                }
                onViewResized() {
                    if (this.m_editor != null) {
                        this.m_editor.resize();
                    }
                }
                acl_init() {
                    this.acl = new PDJS.Core.Security.AccessControlList({
                        aces: this.aces,
                        permissions: this.permissions,
                        commit: () => {
                            this.aces = this.acl.aces.toJSON();
                        }
                    });
                    this.m_editor =
                        new PDJS.Shared.Security.AccessContol({
                            acl: this.acl,
                            readOnly: !this.enabled,
                            securableId: this.securableId,
                            enableAdvanced: this.isAdvancedAllowed,
                            enableEffectivePermissions: this.isAdvancedAllowed
                        });
                    this.controls.add(this.m_editor);
                }
            }
            EntityTypes.AccessControlEditor = AccessControlEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.EntityTypes.AccessControlEditor", AccessControlEditor);
            });
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                let Events;
                (function (Events) {
                    Events["TargetChanged"] = "Relationships:TargetChanged";
                    Events["RelationshipsChanged"] = "Relationships:Changed";
                })(Events = Relationships.Events || (Relationships.Events = {}));
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static targetChangedPublish(args) {
                        this.current.publish(Events.TargetChanged, args);
                    }
                    static targetChangedSubscribe(handler) {
                        return this.current.subscribe(Events.TargetChanged, handler);
                    }
                }
                Relationships.EventsHub = EventsHub;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class RelationshipsCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$ancestorList", null);
                        this.state.set("$childrenList", null);
                        this.state.set("$relationshipsMap", null);
                        this.state.set("$typesList", null);
                    }
                    get parentList() {
                        return this.state.get("$ancestorList");
                    }
                    get childList() {
                        return this.state.get("$childrenList");
                    }
                    get relationshipsMap() {
                        return this.state.get("$relationshipsMap");
                    }
                    get typesList() {
                        return this.state.get("$typesList");
                    }
                    updateCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/relationships": {
                                $ancestorList: this.parentList,
                                $childrenList: this.childList,
                                $relationshipsMap: this.relationshipsMap,
                                $typesList: this.typesList
                            }
                        }, { force: true });
                    }
                }
                Relationships.RelationshipsCommand = RelationshipsCommand;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class AddRelationshipCommand extends Relationships.RelationshipsCommand {
                    constructor(options) {
                        super(options);
                    }
                    get type() {
                        return this.props.get("type");
                    }
                    execute() {
                        super.execute();
                        Relationships.AvailableTypesDialog.open({
                            entityTypeId: this.typesList.selected.id,
                            entityTypeName: this.typesList.selected.name,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.type == "parent" ?
                                        this.addParentRelationship(e) :
                                        this.addChildRelationship(e);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            label: "Add",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pdv2"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                    }
                    addParentRelationship(items) {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let item = _.first(items);
                        service.addRelationship({
                            parentId: item.id,
                            childId: this.typesList.selected.id,
                            success: (e) => {
                                this.parentList.add(items);
                                this.relationshipsMap.refresh();
                                this.updateCommandState();
                            }
                        });
                    }
                    addChildRelationship(items) {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let item = _.first(items);
                        service.addRelationship({
                            parentId: this.typesList.selected.id,
                            childId: item.id,
                            success: (e) => {
                                this.childList.add(items);
                                this.relationshipsMap.refresh();
                                this.updateCommandState();
                            }
                        });
                    }
                }
                Relationships.AddRelationshipCommand = AddRelationshipCommand;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class RemoveRelationshipCommand extends Relationships.RelationshipsCommand {
                    constructor(options) {
                        super(options);
                    }
                    get type() {
                        return this.props.get("type");
                    }
                    execute(value) {
                        super.execute(value);
                        let message = this.type == "parent" ?
                            this.getParentMessage() :
                            this.getChildMessage();
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            title: "Remove | Relationships",
                            message: message,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.type == "parent" ?
                                        this.removeParentRelationship() :
                                        this.removeChildRelationship();
                                }
                            }
                        });
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.type == "parent" ?
                            this.parentList.selected.length > 0 :
                            this.childList.selected.length > 0;
                    }
                    getDefaultValuesForProps() {
                        return {
                            label: "Remove",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pdv2",
                            tooltip: "Remove child relationship."
                        };
                    }
                    getChildMessage() {
                        return this.childList.selected.length > 1 ?
                            `Remove the selected entity types as children of ${this.typesList.selected.name}?` :
                            `Remove the ${_.first(this.childList.selected).name} as a child of ${this.typesList.selected.name}?`;
                    }
                    getParentMessage() {
                        return this.parentList.selected.length > 1 ?
                            `Remove the selected entity types as parents of ${this.typesList.selected.name}?` :
                            `Remove the ${_.first(this.parentList.selected).name} as a parent of ${this.typesList.selected.name}?`;
                    }
                    removeChildRelationship() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let item = _.first(this.childList.selected);
                        service.deleteRelationship({
                            parentId: this.typesList.selected.id,
                            childId: item.id,
                            success: (e) => {
                                this.childList.refresh();
                                this.relationshipsMap.refresh();
                                this.updateCommandState();
                            }
                        });
                    }
                    removeParentRelationship() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let item = _.first(this.parentList.selected);
                        service.deleteRelationship({
                            parentId: item.id,
                            childId: this.typesList.selected.id,
                            success: (e) => {
                                this.parentList.refresh();
                                this.relationshipsMap.refresh();
                                this.updateCommandState();
                            }
                        });
                    }
                }
                Relationships.RemoveRelationshipCommand = RemoveRelationshipCommand;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class RelationshipsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/relationships");
                    }
                    registerCommands(e) {
                        e.commands.add(new Relationships.AddRelationshipCommand({
                            id: "relationship/parent/add",
                            tooltip: "Add parent relationship.",
                            type: "parent"
                        }));
                        e.commands.add(new Relationships.AddRelationshipCommand({
                            id: "relationship/child/add",
                            tooltip: "Add child relationship.",
                            type: "child"
                        }));
                        e.commands.add(new Relationships.RemoveRelationshipCommand({
                            id: "relationship/parent/remove",
                            tooltip: "Remove parent relationship.",
                            type: "parent"
                        }));
                        e.commands.add(new Relationships.RemoveRelationshipCommand({
                            id: "relationship/child/remove",
                            tooltip: "Add child relationship.",
                            type: "child"
                        }));
                    }
                }
                Relationships.RelationshipsCommands = RelationshipsCommands;
                Jade.CommandGroups.add(RelationshipsCommands);
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class RelationshipsModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get splitter1Node() {
                        return this.node.children("div[role=splitter-1]");
                    }
                    resize() {
                        if (this.m_spliiter1) {
                            this.m_spliiter1.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-entity-types-relationships">
                        <div role="splitter-1">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2">
                                <div role="assigned" style="position: absolute;inset:0;display:grid;grid-template-rows: 1fr 1fr; grid-gap:10px;">
                                    <div role="ancestor" style="position: relative;overflow:hidden;"></div>
                                    <div role="children" style="position: relative;overflow:hidden;"></div>
                                </div>
                            </div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter1_init();
                        this.module_init();
                        this.subscriptions.add(PDJS.ApplicationEventsHub.windowResizedSubscribe(() => {
                            if (this.focused) {
                                this.splitter1_size();
                            }
                        }));
                    }
                    typesList_init() {
                        this.m_typesList = new Relationships.TypesList({
                            insertAt: "div[data-id=pane-1]",
                            change: (item) => {
                                if (item == null) {
                                    this.setCommandState();
                                    return;
                                }
                                Relationships.EventsHub.targetChangedPublish(item);
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_typesList);
                    }
                    ancestorList_init() {
                        this.m_ancestorList = new Relationships.AncestorList({
                            insertAt: "div[role=ancestor]",
                            change: () => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_ancestorList);
                    }
                    childrenList_init() {
                        this.m_childrenList = new Relationships.ChildrenList({
                            insertAt: "div[role=children]",
                            change: () => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_childrenList);
                    }
                    module_init() {
                        this.ancestorList_init();
                        this.childrenList_init();
                        this.relationshipsTree_init();
                        this.typesList_init();
                        this.setCommandState();
                    }
                    relationshipsTree_init() {
                        this.m_relationshipsMap = new Relationships.RelationshipsMap({
                            insertAt: "div[data-id=pane-3]"
                        });
                        this.controls.add(this.m_relationshipsMap);
                    }
                    splitter1_init() {
                        if (this.m_spliiter1 != null) {
                            this.m_spliiter1.destroy();
                            this.splitter1Node.children(".k-splitbar").remove();
                        }
                        this.m_spliiter1 = this.splitter1Node.kendoSplitter({
                            panes: [
                                { resizable: true, size: "25%", scrollable: false },
                                { resizable: true, size: "50%", scrollable: false },
                                { resizable: true, size: "25%", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    splitter1_size() {
                        this.m_spliiter1.size("div[data-id=pane-1]", "25%");
                        this.m_spliiter1.size("div[data-id=pane-2]", "50%");
                        this.m_spliiter1.size("div[data-id=pane-3]", "25%");
                    }
                    setCommandState() {
                        let setState = this.m_ancestorList != null &&
                            this.m_childrenList != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/relationships": {
                                $ancestorList: this.m_ancestorList,
                                $childrenList: this.m_childrenList,
                                $relationshipsMap: this.m_relationshipsMap,
                                $typesList: this.m_typesList
                            }
                        }, { force: true });
                    }
                }
                Relationships.RelationshipsModule = RelationshipsModule;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class AncestorList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get selected() {
                        var _a, _b;
                        return (((_b = (_a = this.m_list) === null || _a === void 0 ? void 0 : _a.selected) === null || _b === void 0 ? void 0 : _b.toArray()) || [])
                            .map(item => item.toJSON());
                    }
                    get targetId() {
                        return this.state.get("targetId");
                    }
                    set targetId(value) {
                        this.state.set("targetId", value);
                    }
                    get title() {
                        return this.node.find(".-pdjs-manage-module-section-title").html();
                    }
                    set title(value) {
                        this.node.find(".-pdjs-manage-module-section-title").html(value);
                    }
                    add(types) {
                        types.forEach(type => {
                            this.m_list.addItem(_.extend({
                                icon: "graph_node.png"
                            }, type));
                        });
                    }
                    clear() {
                        this.m_list.removeAll();
                    }
                    load(types) {
                        this.m_list.removeAll();
                        this.add(types);
                    }
                    remove(ids) {
                        ids.forEach(id => {
                            this.m_list.removeItem(id);
                        });
                    }
                    refresh() {
                        this.list_fill();
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-child-list">
                        <div>
                            <div class="-pdjs-manage-module-section-title">
                                Parent Types
                            </div>
                            <div role="buttons">

                            </div>
                        </div>
                        <div role="list"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.list_fill();
                        this.buttons_init();
                        this.subscriptions.add(Relationships.EventsHub.targetChangedSubscribe((e) => {
                            this.targetId = e.id;
                            this.title = `Parent Types for <span role="target-name">${e.name}</span>`;
                            this.list_fill();
                        }));
                    }
                    list_init() {
                        this.m_list = new PDJS.Shared.UI.Controls.ListView({
                            insertAt: "div[role=list]",
                            height: "100%",
                            binding: { value: "id", label: "name" },
                            iconSet: "pd",
                            noItemsMessage: "No parent assigned.",
                            change: (items) => {
                                this.changeCallback();
                            },
                            createItem: (e) => {
                                return new PDJS.Shared.UI.Controls.ListViewItem(e);
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    list_fill() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        this.list.removeAll(true);
                        if (this.targetId == null) {
                            return;
                        }
                        service.getRelationships({
                            entityTypeId: this.targetId,
                            success: (e) => {
                                e.data.parents.forEach(item => {
                                    this.list.addItem({
                                        name: item.name,
                                        id: item.id,
                                        icon: item.icon
                                    });
                                });
                            }
                        });
                    }
                    buttons_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons]",
                            commandId: "pdjs/manage/relationships:relationship/parent/add"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons]",
                            commandId: "pdjs/manage/relationships:relationship/parent/remove"
                        }));
                    }
                }
                Relationships.AncestorList = AncestorList;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class ChildrenList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get selected() {
                        var _a, _b;
                        return (((_b = (_a = this.m_list) === null || _a === void 0 ? void 0 : _a.selected) === null || _b === void 0 ? void 0 : _b.toArray()) || [])
                            .map(item => item.toJSON());
                    }
                    get targetId() {
                        return this.state.get("targetId");
                    }
                    set targetId(value) {
                        this.state.set("targetId", value);
                    }
                    get title() {
                        return this.node.find(".-pdjs-manage-module-section-title").html();
                    }
                    set title(value) {
                        this.node.find(".-pdjs-manage-module-section-title").html(value);
                    }
                    add(types) {
                        types.forEach(type => {
                            this.m_list.addItem(_.extend({
                                icon: "graph_node.png"
                            }, type));
                        });
                    }
                    clear() {
                        this.m_list.removeAll();
                    }
                    load(types) {
                        this.m_list.removeAll();
                        this.add(types);
                    }
                    refresh() {
                        this.list_fill();
                    }
                    remove(ids) {
                        ids.forEach(id => {
                            this.m_list.removeItem(id);
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-parent-list">
                        <div>
                            <div class="-pdjs-manage-module-section-title">
                                Child Types
                            </div>
                            <div role="buttons">

                            </div>
                        </div>
                        <div role="list"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.list_fill();
                        this.buttons_init();
                        this.subscriptions.add(Relationships.EventsHub.targetChangedSubscribe((e) => {
                            this.targetId = e.id;
                            this.title = `Child Types for <span role="target-name">${e.name}</span>`;
                            this.list_fill();
                        }));
                    }
                    list_init() {
                        this.m_list = new PDJS.Shared.UI.Controls.ListView({
                            insertAt: "div[role=list]",
                            height: "100%",
                            binding: { value: "id", label: "name" },
                            iconSet: "pd",
                            noItemsMessage: "No children available.",
                            change: (items) => {
                                this.changeCallback();
                            },
                            createItem: (e) => {
                                return new PDJS.Shared.UI.Controls.ListViewItem(e);
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                    list_fill() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        this.list.removeAll(true);
                        if (this.targetId == null) {
                            return;
                        }
                        service.getRelationships({
                            entityTypeId: this.targetId,
                            success: (e) => {
                                e.data.children.forEach(item => {
                                    this.list.addItem({
                                        name: item.name,
                                        id: item.id,
                                        icon: item.icon
                                    });
                                });
                            }
                        });
                    }
                    buttons_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons]",
                            commandId: "pdjs/manage/relationships:relationship/child/add"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons]",
                            commandId: "pdjs/manage/relationships:relationship/child/remove"
                        }));
                    }
                }
                Relationships.ChildrenList = ChildrenList;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class RelationshipsMap extends Jade.UI.Control {
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    set entityTypeId(value) {
                        this.state.set("entityTypeId", value);
                    }
                    get gridNode() {
                        return this.node.find("div[role=grid]");
                    }
                    refresh() {
                        this.grid_fill();
                    }
                    select(entityTypeId) {
                        let uids = [];
                        let dataSource = this.m_grid.get_dataSource().get_instance();
                        dataSource.data().forEach((item) => {
                            item.id == entityTypeId ?
                                uids.push(item.uid) : null;
                        });
                        this.gridNode.find(`tr[data-uid] label[role=name-text]`).removeClass("-pdjs-selected");
                        uids.forEach(id => {
                            this.gridNode.find(`tr[data-uid=${id}] label[role=name-text]`).addClass("-pdjs-selected");
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-tree">
                        <div>
                            <div class="-pdjs-manage-module-section-title">
                                Relationships Map
                            </div>
                        </div>
                        <div role="grid">

                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.isBrowserResizeAware = true;
                        this.grid_init();
                        this.subscriptions.add(Relationships.EventsHub.targetChangedSubscribe((e) => {
                            this.entityTypeId = e.id;
                            this.grid_fill();
                        }));
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: `[id=${this.ID}] [role=grid]`,
                            height: "100%",
                            selectionMode: "none",
                            dataSource: {
                                storeAsLocalVariable: true
                            },
                            footer: {
                                visible: false
                            },
                            resizable: true,
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name",
                                    width: "200px",
                                    resizable: true,
                                    template: (e) => {
                                        return `<div role="name-cell" ${this.getNameCellInsetStyle(e.path)}>
                                        <label role="name-text">
                                           ${e.name}
                                        </label>
                                    </div>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "customId",
                                    title: "Custom ID",
                                    width: "200px",
                                    resizable: true
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ]
                        });
                        this.grid_fill();
                    }
                    grid_fill() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        service.getRelationshipTree({
                            success: (e) => {
                                this.m_grid.get_dataSource().data([]);
                                this.m_grid.get_dataSource().data(e.data);
                                if (this.entityTypeId) {
                                    this.select(this.entityTypeId);
                                }
                            }
                        });
                    }
                    getNameCellInsetStyle(path) {
                        let inset = path.split("/").length;
                        return ` style="${inset > 1 ? `padding-left:${(inset - 2) * 25}px` : ""}"`;
                    }
                }
                Relationships.RelationshipsMap = RelationshipsMap;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class TypesList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selected() {
                        return _.first(this.m_list.selected.toArray().map(item => item.toJSON()));
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-types-list">
                        <div>
                            <div class="-pdjs-manage-module-section-title">
                                Entity Types
                            </div>
                        </div>
                        <div role="list"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.list_fill();
                    }
                    list_init() {
                        this.list = new PDJS.Shared.UI.Controls.ListView({
                            insertAt: "div[role=list]",
                            noItemsMessage: "No Entity Types",
                            height: "100%",
                            selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                            iconSet: "pd",
                            change: (e) => {
                                let item = _.first(e.toArray().map(item => item.toJSON()));
                                Relationships.EventsHub.targetChangedPublish({
                                    id: item.value,
                                    name: item.name
                                });
                            },
                            binding: {
                                icon: "icon",
                                label: "name",
                                value: "value"
                            }
                        });
                        this.controls.add(this.list);
                    }
                    list_fill() {
                        let service = new PDJS.Services.EntityTypes.EntityTypesService();
                        this.list.removeAll(true);
                        service.list({
                            success: (e) => {
                                e.data.forEach((item, index) => {
                                    this.list.addItem({
                                        id: item.id,
                                        name: item.name,
                                        value: item.id,
                                        icon: item.icon
                                    });
                                    if (index == 0) {
                                        this.list.select([item.id]);
                                    }
                                });
                            }
                        });
                    }
                }
                Relationships.TypesList = TypesList;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EntityTypes;
        (function (EntityTypes) {
            var Relationships;
            (function (Relationships) {
                class AvailableTypesDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get entityTypeName() {
                        return this.state.get("entityTypeName");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-id=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=cancel]");
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-available-types-dialog">
                        <div role="grid"></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.closeAndReturn();
                        });
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                        this.grid_init();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Assign | Type",
                            height: "300px",
                            width: "500px",
                            maximized: false,
                            resizable: true
                        };
                    }
                    closeAndReturn() {
                        this.close({
                            name: "ok",
                            data: this.m_grid.getSelections().toArray().map(item => {
                                return {
                                    id: item.id,
                                    name: item.name,
                                    icon: item.icon
                                };
                            })
                        });
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: "div[role=grid]",
                            selectionMode: "single",
                            messaging: {
                                noRecordsMessage: "No entity types available to assign."
                            },
                            footer: {
                                visible: false
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            },
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "id",
                                    title: "",
                                    hidden: true,
                                }),
                                new PD.Web.UI.Controls.GridIconColumn({
                                    field: "icon",
                                    title: "&nbsp;"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name"
                                }),
                            ]
                        });
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        service.getRelationships({
                            entityTypeId: this.entityTypeId,
                            success: (e) => {
                                this.m_grid.get_dataSource().data(e.data.available);
                            }
                        });
                    }
                    static open(options) {
                        return new AvailableTypesDialog(options);
                    }
                }
                Relationships.AvailableTypesDialog = AvailableTypesDialog;
            })(Relationships = EntityTypes.Relationships || (EntityTypes.Relationships = {}));
        })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get jobId() {
                    return this.state.get("jobId");
                }
                set jobId(value) {
                    this.state.set("jobId", value);
                }
                load(jobId) {
                    this.jobId = jobId;
                }
                template() {
                    return `<div class="-pdjs-manage-event-log-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Application Log"
                    }));
                    let link = new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "View",
                        target: "_blank"
                    });
                    this.controls.add(link);
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Download",
                        url: "~/Manage/EventLog/DownloadApplicationLog"
                    }));
                    let service = new PDJS.Services.EventLog.EventLogService();
                    service.getApplicationLogUrl({
                        success: (e) => {
                            link.url = e.data.url;
                        }
                    });
                }
            }
            EventLog.EventLogActions = EventLogActions;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/event-log": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            EventLog.EventLogCommand = EventLogCommand;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class ClearLogCommand extends EventLog.EventLogCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "events/clear",
                        label: "Clear Log",
                        icon: "garbage.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Clear all the events in the log.",
                        iconSetId: "pd"
                    };
                }
                execute(e) {
                    EventLog.ClearLogDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeDelete(e.scope);
                            }
                        }
                    });
                }
                executeDelete(hours) {
                    let service = new PDJS.Services.EventLog.EventLogService();
                    service.clearLog({
                        hours: hours,
                        success: (e2) => {
                            this.grid.refresh({
                                clear: true
                            });
                        }
                    });
                }
            }
            EventLog.ClearLogCommand = ClearLogCommand;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class ViewEventCommand extends EventLog.EventLogCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "event/view",
                        label: "View Event",
                        icon: "MAGNIFYING_GLASS.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "View details for the selected event.",
                        iconSetId: "pd"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    let event = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "View | Event",
                        height: 550,
                        width: 650,
                        args: {
                            targetId: event.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Events.EventUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Events.EventArbiter"
                        }
                    });
                }
            }
            EventLog.ViewEventCommand = ViewEventCommand;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/event-log");
                }
                registerCommands(e) {
                    e.commands.add(new EventLog.ViewEventCommand());
                    e.commands.add(new EventLog.ClearLogCommand());
                }
            }
            EventLog.EventLogCommands = EventLogCommands;
            Jade.CommandGroups.add(EventLogCommands);
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/event-log";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:event/view`
                    }));
                }
            }
            EventLog.EventLogContextMenu = EventLogContextMenu;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-event-log-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Events</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new EventLog.EventLogToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No events."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/event-log:event/view");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.EventLog.EventLogContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            EventLog.EventLogGrid = EventLogGrid;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-event-log">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new EventLog.EventLogGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new EventLog.EventLogActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.EventLog.EventLogService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/event-log": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            EventLog.EventLogModule = EventLogModule;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class EventLogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/event-log";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:event/view`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:events/clear`
                    }));
                }
            }
            EventLog.EventLogToolbar = EventLogToolbar;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var EventLog;
        (function (EventLog) {
            class ClearLogDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options, windowOptions = {}) {
                    super(options);
                }
                get selectNode() {
                    return this.node.find("select");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-event-log-clear-log-dialog">
                        <div role="text">Clear all log entries that are older than:</div>
                        <div role="control">
                            <select>
                                <option value="672">One Month</option>
                                <option value="168">One Week</option>
                                <option value="24">24 Hours</option>
                                <option value="1">One Hour</option>
                                <option value="0">All Time</option>
                            </select>
                        </div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Clear | Event Log",
                        width: 300,
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                }
                closeAndReturn() {
                    this.close({
                        name: "ok",
                        data: {
                            scope: parseInt(this.selectNode.val())
                        }
                    });
                }
                static open(options) {
                    return new ClearLogDialog(options);
                }
            }
            EventLog.ClearLogDialog = ClearLogDialog;
        })(EventLog = Manage.EventLog || (Manage.EventLog = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get expression() {
                    return this.state.get("expression");
                }
                set expression(value) {
                    this.state.set("expression", value);
                }
                load(expression) {
                    this.expression = expression;
                }
                template() {
                    return `<div class="-pdjs-manage-expressions-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Tag...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewTagDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tags",
                        label: "Manage Tags"
                    }));
                }
            }
            Expressions.ExpressionsActions = ExpressionsActions;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/expressions": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Expressions.ExpressionsCommand = ExpressionsCommand;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class DeleteExpressionCommand extends Expressions.ExpressionsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected Expressions.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Expressions?",
                        message: `Delete the selected expressions?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startTask();
                            }
                        }
                    });
                }
                startTask(confirmed = false) {
                    let service = new PDJS.Services.Tags.ExpressionService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete | Expressions",
                        taskStart: (e) => {
                            service.delete({
                                ids: this.selectedIds,
                                confirmed: confirmed,
                                success: (e2) => {
                                    if (e2.data.requiresConfirmation && !confirmed) {
                                        this.showInUseDialog(e);
                                        return;
                                    }
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
                showInUseDialog(taskArgs) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        title: "Expressions In Use",
                        message: "Some of the expressions are in use. Proceed with the expression deletion?",
                        select: {
                            yes: (sender, e) => {
                                sender.close();
                                taskArgs.close();
                                this.startTask(true);
                            },
                            no: (sender, e) => {
                                sender.close();
                                taskArgs.close();
                            }
                        }
                    });
                }
            }
            Expressions.DeleteExpressionCommand = DeleteExpressionCommand;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class EditExpressionCommand extends Expressions.ExpressionsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the selected Expression.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let expression = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${expression.name}`,
                        height: 400,
                        width: 500,
                        args: {
                            targetId: expression.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            Expressions.EditExpressionCommand = EditExpressionCommand;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class NewExpressionCommand extends Expressions.ExpressionsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "expression/new",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new Expression.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Expression",
                        height: 400,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            Expressions.NewExpressionCommand = NewExpressionCommand;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/expressions");
                }
                registerCommands(e) {
                    e.commands.add(new Expressions.DeleteExpressionCommand());
                    e.commands.add(new Expressions.EditExpressionCommand());
                    e.commands.add(new Expressions.NewExpressionCommand());
                }
            }
            Expressions.ExpressionsCommands = ExpressionsCommands;
            Jade.CommandGroups.add(ExpressionsCommands);
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-expressions-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Expressions</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Expressions.ExpressionsGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No expressions."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/expressions:expression/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Expressions.ExpressionsGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Expressions.ExpressionsGrid = ExpressionsGrid;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/expressions";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:expression/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:expression/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:expression/delete`
                    }));
                }
            }
            Expressions.ExpressionsGridContextMenu = ExpressionsGridContextMenu;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/expressions";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:expression/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:expression/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:expression/delete`
                    }));
                }
            }
            Expressions.ExpressionsGridToolbar = ExpressionsGridToolbar;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Expressions;
        (function (Expressions) {
            class ExpressionsModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-expressions">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Expressions.ExpressionsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Expressions.ExpressionsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Tags.ExpressionService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/expressions": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Expressions.ExpressionsModule = ExpressionsModule;
        })(Expressions = Manage.Expressions || (Manage.Expressions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ExtensionColumns;
        (function (ExtensionColumns) {
            class FormUsageEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get containerNode() {
                    return this.node.find("div[role=container]");
                }
                get grid() {
                    return this.m_grid;
                }
                template() {
                    return `<div class="-fb-form-usage-editor">
                        <div role="container">
                        </div>
                    </div>`;
                }
                destroy() {
                    super.destroy();
                    if (this.grid != null) {
                        this.grid.destroy();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: `#${this.ID} DIV[role=container]`,
                        showToolbar: false,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            data: this.source.getFeatureValue("usage")
                        },
                        messaging: {
                            noRecordsMessage: "Column not referenced by any forms."
                        },
                        selectionMode: "none",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                field: "id",
                                width: "25px",
                                icon: "FORM_BLUE.png"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "type",
                                title: "Type",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
            }
            ExtensionColumns.FormUsageEditor = FormUsageEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.DataModel.ExtensionColumnFormUsageFeature", FormUsageEditor);
            });
        })(ExtensionColumns = Manage.ExtensionColumns || (Manage.ExtensionColumns = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ExtensionColumns;
        (function (ExtensionColumns) {
            class SearchGroupUsageEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get containerNode() {
                    return this.node.find("div[role=container]");
                }
                get grid() {
                    return this.m_grid;
                }
                template() {
                    return `<div class="-fb-search-group-usage-editor">
                        <div role="container">
                        </div>
                    </div>`;
                }
                destroy() {
                    super.destroy();
                    if (this.grid != null) {
                        this.grid.destroy();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: `#${this.ID} DIV[role=container]`,
                        showToolbar: false,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            data: this.source.getFeatureValue("usage")
                        },
                        messaging: {
                            noRecordsMessage: "Column not referenced by any search groups."
                        },
                        selectionMode: "none",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                field: "id",
                                width: "25px",
                                icon: "FORM_BLUE.png"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "type",
                                title: "Type",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
            }
            ExtensionColumns.SearchGroupUsageEditor = SearchGroupUsageEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.DataModel.ExtensionColumnSearchGroupsFeature", SearchGroupUsageEditor);
            });
        })(ExtensionColumns = Manage.ExtensionColumns || (Manage.ExtensionColumns = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var ExtensionColumns;
        (function (ExtensionColumns) {
            class SelectionListEditor extends PDJS.Shared.Features.Editors.PopUpEditor {
                constructor(options) {
                    super(options);
                }
                get emptyText() {
                    return "No Selection List Assigned";
                }
                get listId() {
                    return this.value;
                }
                set listId(value) {
                    this.value = value;
                }
                get listName() {
                    return this.text;
                }
                set listName(value) {
                    this.text = value;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.updateUI();
                }
                popupButton_onClick() {
                    PDJS.JS.PD.Manage.Modules.Extensions.SelectionListSelectorDialog.open({
                        callbacks: {
                            ok: (sender, e) => {
                                this.listId = e.id;
                                this.listName = e.name;
                                this.updateUI();
                            }
                        }
                    });
                }
                updateUI() {
                    if (this.wasPreviouslyAssignedValue) {
                        this.inputNode.prop("disabled", "disabled");
                        this.inputNode.prop("readonly", "readonly");
                    }
                    this.showImage(false);
                    this.showClearButton(false);
                    this.inputNode.val(this.listName || "");
                }
            }
            ExtensionColumns.SelectionListEditor = SelectionListEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.SelectionListEditor", SelectionListEditor);
            });
        })(ExtensionColumns = Manage.ExtensionColumns || (Manage.ExtensionColumns = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get jobId() {
                    return this.state.get("jobId");
                }
                set jobId(value) {
                    this.state.set("jobId", value);
                }
                get jobName() {
                    return this.state.get("jobName");
                }
                get historyList() {
                    return this.m_historyList;
                }
                get scheduleList() {
                    return this.m_scheduleList;
                }
                load(jobId) {
                    this.jobId = jobId;
                    this.addJobItems();
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addJobsItems();
                    this.addJobItems();
                    this.addRulesItems();
                }
                addRulesItems() {
                    let label = new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Rules"
                    });
                    this.controls.add(label);
                    label.node.css({
                        marginTop: "10px"
                    });
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/rules",
                        label: "Manage Rules"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Rule Script...",
                        click: (e) => {
                            PDJS.Manage.Rules.RuleEditing.create();
                        }
                    }));
                }
                addJobsItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Jobs"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Custom Schedules",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/jobs:jobs/open-custom-schedules");
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Advanced Settings",
                        click: (e) => {
                            PDJS.Shared.Features.FeatureDialogForNhib.open({
                                title: "Jobs | Advanced Settings",
                                width: 600,
                                height: 400,
                                args: {
                                    targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobSettingsUIO",
                                    arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobSettingsArbiter"
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/jobs-log",
                        label: "View Log"
                    }));
                }
                addJobItems() {
                    this.addControls();
                    this.jobId == null ?
                        this.historyList.node.hide() :
                        this.historyList.node.show();
                    this.jobId == null ?
                        this.scheduleList.node.hide() :
                        this.scheduleList.node.show();
                    if (this.jobId == null) {
                        return;
                    }
                    let service = new PDJS.Services.Jobs.JobService();
                    service.getJobData({
                        id: this.jobId,
                        success: (e) => {
                            this.historyList.removeAll();
                            e.data.history.forEach(data => {
                                data.dateStarted = new Date(data.dateStarted).toLocaleDateString(undefined, {
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                    hour: "numeric",
                                    minute: "2-digit"
                                });
                                this.historyList.addItem(data);
                            });
                            this.scheduleList.removeAll();
                            e.data.fireTimes.forEach(data => {
                                let item = {
                                    icon: "clock.png",
                                    value: data
                                };
                                item.label = new Date(data).toLocaleDateString(undefined, {
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                    hour: "numeric",
                                    minute: "2-digit"
                                });
                                this.scheduleList.addItem(item);
                            });
                        }
                    });
                }
                addJobHistory() {
                    this.m_historyList =
                        new PDJS.Shared.UI.Controls.ListView({
                            noItemsMessage: "Job has no history.",
                            binding: {
                                icon: "icon",
                                label: "dateStarted",
                                value: "eventId"
                            },
                            data: [],
                            height: "160px",
                            dblClick: (e) => {
                                let item = _.first(e.toArray());
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/jobs:event/view", {
                                    eventId: item.value
                                });
                            }
                        });
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Job History"
                    }));
                    this.controls.add(this.m_historyList);
                    return this.m_historyList;
                }
                addJobSchedule() {
                    this.m_scheduleList =
                        new PDJS.Shared.UI.Controls.ListView({
                            noItemsMessage: "Job has no schedule.",
                            height: "160px",
                            binding: {
                                icon: "icon",
                                label: "label",
                                value: "value"
                            },
                            selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.none
                        });
                    let label = new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Job Schedule"
                    });
                    this.controls.add(label);
                    this.controls.add(this.m_scheduleList);
                    label.node.css({
                        marginTop: "10px"
                    });
                    return this.m_scheduleList;
                }
                addControls() {
                    if (this.m_historyList == null) {
                        this.m_historyList =
                            this.addJobHistory();
                    }
                    if (this.m_scheduleList == null) {
                        this.m_scheduleList =
                            this.addJobSchedule();
                    }
                }
                showNotificationEditor(notificationId) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        height: "500px",
                        width: "700px",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobNotificationUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobNotificationArbiter",
                            properties: {
                                notificationId: notificationId
                            }
                        }
                    });
                }
            }
            Jobs.JobsActions = JobsActions;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Jobs.JobsCommand = JobsCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CreateJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Job",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobArbiter"
                        },
                        select: {
                            "ok": (sender, data) => {
                                this.grid.refresh({
                                    selections: [data.target.id],
                                    clear: true
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/create",
                        tooltip: "Create a new job.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.CreateJobCommand = CreateJobCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class DeleteJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Jobs",
                        message: `Delete the selected jobs?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/delete",
                        tooltip: "Delete the selected jobs",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeDelete() {
                    let service = new PDJS.Services.Jobs.JobService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete | Jobs",
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.deleteJobs({
                                ids: this.selections.map(job => job.id),
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Jobs.DeleteJobCommand = DeleteJobCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class UpdateJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let job = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${job.name}`,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobArbiter",
                            targetId: _.first(this.selections).id
                        },
                        select: {
                            "ok": (sender, data) => {
                                this.grid.refresh({
                                    reselect: true
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/update",
                        tooltip: "Edit the properties of the selected job.",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.UpdateJobCommand = UpdateJobCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class OpenCustomSchedulesCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jobs.CustomSchedulesDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.grid.refresh();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "jobs/open-custom-schedules",
                        tooltip: "Custom Schedules",
                        label: "Custom Schedules",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.OpenCustomSchedulesCommand = OpenCustomSchedulesCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class PauseJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                get hasPausedJobs() {
                    return this.selections.filter(item => item.paused).length > 0;
                }
                get hasActiveJobs() {
                    return this.selections.filter(item => !item.paused).length > 0;
                }
                get hasMixedJobs() {
                    return this.hasActiveJobs && this.hasPausedJobs;
                }
                get hasActiveJobsOnly() {
                    return !this.hasMixedJobs && this.hasActiveJobs;
                }
                get hasPausedJobsOnly() {
                    return !this.hasMixedJobs && this.hasPausedJobs;
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length > 0;
                    switch (true) {
                        case this.hasActiveJobsOnly:
                            this.handleActiveOnly();
                            break;
                        case this.hasPausedJobsOnly:
                            this.handlePausedOnly();
                            break;
                        default:
                            this.handleActivAndPaused();
                            break;
                    }
                }
                onExecute(e) {
                    super.onExecute(e);
                    switch (true) {
                        case this.hasActiveJobsOnly:
                            this.executeService(true);
                            break;
                        case this.hasPausedJobsOnly:
                            this.executeService(false);
                            break;
                        default:
                            this.showDialog();
                            break;
                    }
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/pause",
                        tooltip: "",
                        label: "",
                        icon: "media_pause_red.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeService(pause) {
                    let service = new PDJS.Services.Jobs.JobService();
                    pause ?
                        service.pauseJobs({
                            ids: this.selections.map(item => item.id),
                            success: (e) => {
                                this.grid.refresh({ reselect: true });
                                PDJS.Shared.MessageStack.instance
                                    .warning("Jobs have been paused.");
                            }
                        }) :
                        service.resumeJobs({
                            ids: this.selections.map(item => item.id),
                            success: (e) => {
                                this.grid.refresh({ reselect: true });
                                PDJS.Shared.MessageStack.instance
                                    .success("Jobs have been resumed.");
                            }
                        });
                }
                handleActivAndPaused() {
                    this.label = "Resume / Pause";
                    this.icon = "media_end_yellow.png";
                    this.tooltip = "Pause or Resume the selected jobs.";
                }
                handleActiveOnly() {
                    this.label = "Pause";
                    this.icon = "media_pause_red.png";
                    this.tooltip = "Pause the selected jobs.";
                }
                handlePausedOnly() {
                    this.label = "Resume";
                    this.icon = "media_play_green.png";
                    this.tooltip = "Resume the selected jobs.";
                }
                showDialog() {
                    Jobs.ResumePauseDialog.open({
                        all: false,
                        select: (sender, e) => {
                            this.executeService(e.selection.value);
                        }
                    });
                }
            }
            Jobs.PauseJobCommand = PauseJobCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class PauseAllJobsCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jobs.ResumePauseDialog.open({
                        all: true,
                        select: (sender, e) => {
                            this.executeService(e.selection.value);
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/pause-all",
                        tooltip: "Pause or resume all jobs.",
                        label: "Pause / Resume All",
                        icon: "media_end_blue.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeService(pause) {
                    let service = new PDJS.Services.Jobs.JobService();
                    pause ?
                        service.pauseJobs({
                            ids: this.selections.map(item => item.id),
                            all: true,
                            success: (e) => {
                                this.grid.refresh({ reselect: true });
                                PDJS.Shared.MessageStack.instance
                                    .warning("All jobs have been paused.");
                            }
                        }) :
                        service.resumeJobs({
                            ids: this.selections.map(item => item.id),
                            all: true,
                            success: (e) => {
                                this.grid.refresh({ reselect: true });
                                PDJS.Shared.MessageStack.instance
                                    .success("All jobs have been resumed.");
                            }
                        });
                }
            }
            Jobs.PauseAllJobsCommand = PauseAllJobsCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class RunJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let job = _.first(this.selections);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Run | Job",
                        message: `Run the "${job.name}" job?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeRun();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/run",
                        tooltip: "Run the selected job immediately (on demand).",
                        label: "Run",
                        icon: "media_play.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeRun() {
                    let service = new PDJS.Services.Jobs.JobService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Run | Job",
                        showDetail: true,
                        taskStart: (e) => {
                            service.executeJob({
                                id: _.first(this.selections).id,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskComplete: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Jobs.RunJobCommand = RunJobCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class EditScriptCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let selection = _.first(this.selections);
                    if (selection) {
                        PDJS.Manage.Rules.RuleEditing.editScript(selection.scriptId);
                    }
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/script/edit",
                        tooltip: "Edit the rule script associated with the selected job.",
                        label: "Edit Script",
                        icon: "edit.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Jobs.EditScriptCommand = EditScriptCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ViewEventCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "View | Job Event",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobEventUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobEventArbiter",
                            targetId: e.eventId
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "event/view",
                        tooltip: "View Event",
                        label: "View Event",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.ViewEventCommand = ViewEventCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/jobs");
                }
                registerCommands(e) {
                    e.commands.add(new Jobs.CreateJobCommand());
                    e.commands.add(new Jobs.DeleteJobCommand());
                    e.commands.add(new Jobs.EditScriptCommand());
                    e.commands.add(new Jobs.OpenCustomSchedulesCommand());
                    e.commands.add(new Jobs.PauseJobCommand());
                    e.commands.add(new Jobs.PauseAllJobsCommand());
                    e.commands.add(new Jobs.RunJobCommand());
                    e.commands.add(new Jobs.UpdateJobCommand());
                    e.commands.add(new Jobs.ViewEventCommand());
                }
            }
            Jobs.JobsCommands = JobsCommands;
            Jade.CommandGroups.add(JobsCommands);
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/jobs:job/update"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/jobs:job/delete"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/jobs:job/pause"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/jobs:job/run"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/jobs:job/script/edit"
                    }));
                }
            }
            Jobs.JobsContextMenu = JobsContextMenu;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Jobs</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Jobs.JobsToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No scheduled jobs."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.JobName,
                                    paused: e.Paused == "Yes",
                                    scriptId: e.ScriptId,
                                    scriptName: e.ScriptName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/jobs:job/update");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Jobs.JobsContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Jobs.JobsGrid = JobsGrid;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-jobs">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Jobs.JobsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Jobs.JobsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Jobs.JobService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Jobs.JobsModule = JobsModule;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/create"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/update"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/delete"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/pause"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/pause-all"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/run"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/script/edit"
                    }));
                }
            }
            Jobs.JobsToolbar = JobsToolbar;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ResumePauseDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(options) {
                    return new ResumePauseDialog({
                        title: "Jobs | Resume / Pause",
                        header: "Would you like to pause or resume the jobs?",
                        height: 260,
                        items: options.all ? this.getItemsAll() : this.getItemsSelected(),
                        select: (sender, e) => {
                            sender.close();
                            if (sender.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                if (e.selection != null && options.select instanceof Function) {
                                    options.select(sender, e);
                                }
                            }
                        }
                    });
                }
                static getItemsAll() {
                    return [
                        {
                            title: "Resume All Jobs",
                            message: `Resume all jobs in the system. All jobs will be immediately resumed and freed to run according to their defined schedule.`,
                            value: 0,
                            selected: true
                        },
                        {
                            title: "Pause All Jobs",
                            message: `Pause all jobs in the system. All jobs will be immediately paused and will no longer be run despite their defined schedule.`,
                            value: 1
                        }
                    ];
                }
                static getItemsSelected() {
                    return [
                        {
                            title: "Resume Selected Jobs",
                            message: `Resume all selected jobs. All jobs will be immediately resumed and freed to run according to their defined schedule.`,
                            value: 0,
                            selected: true
                        },
                        {
                            title: "Pause Selected Jobs",
                            message: `Pause all selected jobs. All jobs will be immediately paused and will no longer be run despite their defined schedule.`,
                            value: 1
                        }
                    ];
                }
            }
            Jobs.ResumePauseDialog = ResumePauseDialog;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CustomScheduleDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get data() {
                    return this.state.get("data");
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                get isUpdate() {
                    return this.data != null;
                }
                get hasNameChanged() {
                    var _a, _b;
                    return this.m_nameInput.value.toLowerCase()
                        !== ((_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.toLowerCase());
                }
                get hasExpressionChanged() {
                    var _a, _b;
                    return this.m_expressionInput.value.toLowerCase()
                        !== ((_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.expression) === null || _b === void 0 ? void 0 : _b.toLowerCase());
                }
                getDefaultOptions() {
                    return {
                        title: "Custom Schedule | Edit",
                        width: 300,
                        maximized: false,
                        resizable: false
                    };
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-jobs-custom-schedule-dialog">
                        <div data-controls>
                        </div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.nameInput_init();
                    this.expressionInput_init();
                    this.setWindowOptions({
                        title: `Custom Schedule | ${this.data != null ? "Edit" : "New"}`
                    });
                    this.center();
                }
                onComplete(e) {
                    super.onComplete(e);
                    if (this.data != null) {
                        this.m_nameInput.value = this.data.name;
                        this.m_expressionInput.value = this.data.expression;
                    }
                }
                onInputReturnKeystroke() {
                    super.onInputReturnKeystroke();
                    this.closeAndReturn();
                }
                closeAndReturn() {
                    this.validate(() => {
                        this.close({
                            name: "ok"
                        });
                        this.isUpdate ?
                            this.grid.update(this.data.id, {
                                expression: this.m_expressionInput.value,
                                name: this.m_nameInput.value
                            }) :
                            this.grid.add({
                                expression: this.m_expressionInput.value,
                                name: this.m_nameInput.value
                            }, true);
                    });
                }
                nameInput_init() {
                    this.m_nameInput = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Name",
                        required: true,
                        validateOnBlur: false
                    });
                    this.controls.add(this.m_nameInput);
                }
                expressionInput_init() {
                    this.m_expressionInput = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Expression",
                        required: true,
                        validateOnBlur: false
                    });
                    this.controls.add(this.m_expressionInput);
                }
                validate(success) {
                    success = success || (() => { });
                    this.m_nameInput.validate();
                    this.m_expressionInput.validate();
                    let matches = this.grid.matches(this.getSchedule());
                    let nameError = matches === Jobs.IExpressionMatchType.name ||
                        matches === Jobs.IExpressionMatchType.both;
                    let expressionError = matches === Jobs.IExpressionMatchType.expression ||
                        matches === Jobs.IExpressionMatchType.both;
                    ;
                    if (this.hasNameChanged && nameError) {
                        this.m_nameInput.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: "A schedule with this name already exists."
                        }));
                    }
                    if (this.hasExpressionChanged && expressionError) {
                        this.m_expressionInput.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: "A schedule with this expression already exists."
                        }));
                    }
                    if (!this.isValid()) {
                        return;
                    }
                    if (this.hasExpressionChanged) {
                        this.validateExpression(success);
                        return;
                    }
                    else {
                        success();
                    }
                }
                validateExpression(success) {
                    let service = new PDJS.Services.Jobs.JobService();
                    service.validateExpression({
                        expression: this.m_expressionInput.value,
                        success: (e) => {
                            success();
                        },
                        error: (e) => {
                            this.m_expressionInput.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                                message: _.first(e.xhr.responseJSON).message
                            }));
                            e.errorHandled = true;
                        }
                    });
                }
                isValid() {
                    return this.m_nameInput.isValid &&
                        this.m_expressionInput.isValid;
                }
                getSchedule() {
                    return {
                        name: this.m_nameInput.value,
                        expression: this.m_expressionInput.value
                    };
                }
                static open(options) {
                    return new CustomScheduleDialog(options);
                }
            }
            Jobs.CustomScheduleDialog = CustomScheduleDialog;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CustomSchedulesCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs/schedules": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Jobs.CustomSchedulesCommand = CustomSchedulesCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CreateScheduleCommand extends Jobs.CustomSchedulesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jobs.CustomScheduleDialog.open({
                        $grid: this.grid
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "schedule/create",
                        tooltip: "New",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.CreateScheduleCommand = CreateScheduleCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class DeleteScheduleCommand extends Jobs.CustomSchedulesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Custom Schedules | Delete",
                        message: `Delete the selected custom schedules?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "schedule/delete",
                        tooltip: "Delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeDelete() {
                    this.selections.forEach(item => {
                        this.grid.remove(item.id);
                    });
                }
            }
            Jobs.DeleteScheduleCommand = DeleteScheduleCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class PreviewScheduleCommand extends Jobs.CustomSchedulesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length === 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let selection = _.first(this.selections);
                    Jobs.PreviewScheduleDialog.open({
                        expression: selection.expression
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "schedule/preview",
                        tooltip: "Preview Schedule",
                        label: "Preview Schedule",
                        icon: "clock.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Jobs.PreviewScheduleCommand = PreviewScheduleCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class UpdateScheduleCommand extends Jobs.CustomSchedulesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.grid.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jobs.CustomScheduleDialog.open({
                        $grid: this.grid,
                        data: _.first(this.grid.selections)
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "schedule/update",
                        tooltip: "Edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.UpdateScheduleCommand = UpdateScheduleCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CustomSchedulesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/jobs/schedules");
                }
                registerCommands(e) {
                    e.commands.add(new Jobs.CreateScheduleCommand());
                    e.commands.add(new Jobs.DeleteScheduleCommand());
                    e.commands.add(new Jobs.PreviewScheduleCommand());
                    e.commands.add(new Jobs.UpdateScheduleCommand());
                }
            }
            Jobs.CustomSchedulesCommands = CustomSchedulesCommands;
            Jade.CommandGroups.add(CustomSchedulesCommands);
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CustomSchedulesDialog extends Jade.UI.Dialogs.Dialog {
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`<div class="-pdjs-manage-jobs-custom-schedules-dialog">
                    <div role="toolbar"></div>
                    <div role="grid"></div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.grid_init();
                    this.toolbar_init();
                    this.dialog_init();
                }
                getDefaultOptions() {
                    return {
                        title: "Custom Schedules | List",
                        width: 600,
                        height: 400,
                        maximized: false,
                        resizable: true
                    };
                }
                closeAndReturn() {
                    let service = new PDJS.Services.Jobs.JobService();
                    let items = this.m_grid.items;
                    service.saveExpressions({
                        expressions: items,
                        success: (e) => {
                            this.close({
                                name: "ok"
                            });
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Jobs.CustomSchedulesToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                grid_init() {
                    this.m_grid = new Jobs.CustomSchedulesGrid({
                        insertAt: "div[role=grid]",
                        select: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                dialog_init() {
                    let service = new PDJS.Services.Jobs.JobService();
                    service.loadExpressions({
                        success: (e) => {
                            e.data.forEach(item => {
                                this.m_grid.add(item);
                            });
                            this.setCommandState();
                        }
                    });
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs/schedules": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new CustomSchedulesDialog(options);
                }
            }
            Jobs.CustomSchedulesDialog = CustomSchedulesDialog;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            let IExpressionMatchType;
            (function (IExpressionMatchType) {
                IExpressionMatchType[IExpressionMatchType["none"] = 0] = "none";
                IExpressionMatchType[IExpressionMatchType["name"] = 1] = "name";
                IExpressionMatchType[IExpressionMatchType["expression"] = 2] = "expression";
                IExpressionMatchType[IExpressionMatchType["both"] = 3] = "both";
            })(IExpressionMatchType = Jobs.IExpressionMatchType || (Jobs.IExpressionMatchType = {}));
            class CustomSchedulesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get dataSource() {
                    return this.grid.get_dataSource().get_instance();
                }
                get selections() {
                    return this.grid.getSelections().toArray().map(item => item.toJSON());
                }
                get items() {
                    return this.grid.get_dataSource().data().map(item => item.toJSON());
                }
                get selectCallback() {
                    return this.state.get("select", () => { });
                    ;
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-custom-schedules-grid"></div>`;
                }
                add(schedule, select = false) {
                    if (!this.exists(schedule)) {
                        schedule.id = Jade.Guid.new();
                        this.dataSource.add(schedule);
                        if (select) {
                            this.grid.refresh({
                                clear: true,
                                selections: [schedule.id]
                            });
                        }
                    }
                }
                update(id, schedule) {
                    let item = this.dataSource.get(id);
                    if (item != null) {
                        item.set("name", schedule.name);
                        item.set("expression", schedule.expression);
                    }
                }
                remove(id) {
                    let item = this.dataSource.get(id);
                    if (item != null) {
                        this.dataSource.remove(item);
                    }
                }
                matches(schedule) {
                    let result = 0;
                    let matchedName = false;
                    let matchedExpression = false;
                    this.dataSource.data().toJSON()
                        .forEach((item) => {
                        var _a, _b, _c, _d;
                        let matchesName = ((_a = item.name) === null || _a === void 0 ? void 0 : _a.toLowerCase()) ==
                            ((_b = schedule.name) === null || _b === void 0 ? void 0 : _b.toLowerCase());
                        let matchesExpression = ((_c = item.expression) === null || _c === void 0 ? void 0 : _c.toLowerCase()) ==
                            ((_d = schedule.expression) === null || _d === void 0 ? void 0 : _d.toLowerCase());
                        !matchedName && matchesName ?
                            matchedName = true : null;
                        !matchedExpression && matchesExpression ?
                            matchedExpression = true : null;
                    });
                    result = (matchedName ? 1 : 0) +
                        (matchedExpression ? 2 : 0);
                    return result;
                }
                exists(schedule) {
                    return this.matches(schedule) != 0;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    let icon = Jade.IconSet.get("pdjs")
                        .resolve("clock.png", Jade.IconSetSizeSpecificDirectory.x16);
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        pk: "id",
                        container: this.node,
                        showToolbar: false,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            data: [],
                            storeAsLocalVariable: true,
                            sort: [
                                { field: "name", dir: "asc" }
                            ]
                        },
                        messaging: {
                            noRecordsMessage: "No custom schedules exist."
                        },
                        sortable: {
                            allowUnsort: true
                        },
                        selectionMode: "multiple",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                field: "id",
                                icon: icon
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "250px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "expression",
                                title: "Expression",
                                width: "200px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ],
                        change: (e) => {
                            if (this.m_grid != null) {
                                this.selectCallback();
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/jobs/schedules:schedule/update");
                        }
                    });
                }
            }
            Jobs.CustomSchedulesGrid = CustomSchedulesGrid;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class CustomSchedulesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/jobs/schedules";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:schedule/create`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:schedule/update`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:schedule/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:schedule/preview`
                    }));
                }
            }
            Jobs.CustomSchedulesToolbar = CustomSchedulesToolbar;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class PreviewScheduleDialog extends Jade.UI.Dialogs.Dialog {
                get expression() {
                    return this.state.get("expression");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                template() {
                    return super.template(`<div class="-pdjs-manage-jobs-preview-schedules-dialog">
                    <div role="grid" data-controls></div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.dialog_init();
                }
                getDefaultOptions() {
                    return {
                        title: "Preview | Schedule",
                        width: 250,
                        height: 250,
                        maximized: false,
                        resizable: false
                    };
                }
                list_init(data) {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        noItemsMessage: "No future schedule.",
                        binding: {
                            icon: "icon",
                            label: "date"
                        },
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.none,
                        data: data,
                        height: "100%"
                    });
                    this.controls.add(this.m_list);
                }
                dialog_init() {
                    let service = new PDJS.Services.Jobs.JobService();
                    service.previewSchedule({
                        expression: this.expression,
                        success: (e) => {
                            let values = e.data.map(item => {
                                return { date: kendo.toString(new Date(item), "MMM dd, yyyy, h:mm tt"), icon: "clock.png" };
                            });
                            this.list_init(values);
                        }
                    });
                }
                static open(options) {
                    return new PreviewScheduleDialog(options);
                }
            }
            Jobs.PreviewScheduleDialog = PreviewScheduleDialog;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ScheduleEditor extends FeatureBlendJS.Views.MicroEditorBase {
                get fixedNode() {
                    return this.node.find("select[role=fixed]");
                }
                get masked() {
                    return this.m_masked;
                }
                set masked(value) {
                    this.m_masked = value;
                }
                get value() {
                    return this.source.getFeaturePrimaryValue(null);
                }
                set value(value) {
                    this.source.setFeaturePrimaryValue(value);
                }
                get expressions() {
                    return this.source.getFeatureValueByProp("expressionsProperty", []);
                }
                get hasExpressions() {
                    return this.expressions.length > 0;
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-schedule-editor">
                        <div data-controls>
                            <select role="fixed" tabIndex="-1"></select>
                        </div>
                    </div>`;
                }
                focus() {
                    super.focus();
                    this.masked.showText();
                    this.masked.focusText();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.init_fixed();
                    this.init_masked();
                    this.fixedNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                        let text = this.fixedNode.find("option:selected").text();
                        this.masked.maskValue = text;
                        this.masked.textValue = this.fixedNode.val();
                        this.setValue(this.fixedNode.val());
                        this.fixedNode.val("");
                    });
                    this.masked.maskValue = this.value;
                    this.masked.textValue = this.value;
                    this.setValue(this.value);
                }
                init_fixed() {
                    this.fixedNode.append(`<option value=""></option>`);
                    this.expressions.forEach(item => {
                        this.fixedNode.append(`<option value="${item.expression}">${item.name}</option>`);
                    });
                }
                init_masked() {
                    this.masked = new PDJS.Shared.UI.Controls.MaskedTextBox({
                        autoTabIndex: true,
                        onMaskFocus: (e) => {
                            this.masked.showText();
                            this.masked.focusText();
                        },
                        onTextKeyUp: (e) => {
                            this.setCustomState(this.masked.textValue);
                        },
                        onTextBlur: (e) => {
                            this.setValue(this.masked.textValue);
                        }
                    });
                    this.controls.add(this.masked);
                    this.masked.node.css({
                        position: "absolute",
                        inset: 0,
                        right: this.hasExpressions ? "20px" : "0"
                    });
                }
                setCustomState(value) {
                    let highlight = this.isExpressionCustom(value);
                    this.setHighlightColor(this.masked.textNode, highlight);
                    this.setHighlightColor(this.masked.maskNode, highlight);
                }
                setValue(value) {
                    this.masked.textValue = value;
                    this.masked.maskValue = this.masked.textValue;
                    this.masked.showMask();
                    this.commitValue(this.masked.textValue);
                    let customExpression = this.getCustomExpression(value);
                    if (customExpression != null) {
                        this.masked.maskValue = customExpression.name;
                    }
                    this.setCustomState(value);
                }
                commitValue(value) {
                    this.value = value;
                }
                isExpressionCustom(value) {
                    return this.expressions
                        .filter(item => item.expression.toLowerCase() == (value === null || value === void 0 ? void 0 : value.toLowerCase()))
                        .length > 0;
                }
                getCustomExpression(value) {
                    return _.first(this.expressions.filter(item => {
                        return item.expression.toLowerCase() == (value === null || value === void 0 ? void 0 : value.toLowerCase());
                    }));
                }
                setHighlightColor(node, highlight) {
                    highlight ?
                        node.addClass("-pdjs-text-accent-color-1") :
                        node.removeClass("-pdjs-text-accent-color-1");
                }
            }
            Jobs.ScheduleEditor = ScheduleEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Jobs.ScheduleEditor", ScheduleEditor);
            });
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsLogCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs-log": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Jobs.JobsLogCommand = JobsLogCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ViewEventLogCommand extends Jobs.JobsLogCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    var _a;
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "View | Job Event",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobEventUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobEventArbiter",
                            targetId: (_a = _.first(this.selections)) === null || _a === void 0 ? void 0 : _a.id
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "event/view",
                        tooltip: "View the properties of the select Job Event.",
                        label: "View Event",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Jobs.ViewEventLogCommand = ViewEventLogCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ClearLogCommand extends Jobs.JobsLogCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jobs.ClearLogDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeDelete(e.scope);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "log/clear",
                        tooltip: "Clear events from the Jobs Log.",
                        label: "Clear Log",
                        icon: "eraser.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                executeDelete(scope) {
                    let service = new PDJS.Services.Jobs.JobsLogService();
                    service.delete({
                        scope: scope,
                        success: (e2) => {
                            this.grid.refresh({
                                clear: true
                            });
                        }
                    });
                }
            }
            Jobs.ClearLogCommand = ClearLogCommand;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsLogCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/jobs-log");
                }
                registerCommands(e) {
                    e.commands.add(new Jobs.ViewEventLogCommand());
                    e.commands.add(new Jobs.ClearLogCommand());
                }
            }
            Jobs.JobsLogCommands = JobsLogCommands;
            Jade.CommandGroups.add(JobsLogCommands);
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsLogGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-log-grid">
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Jobs.JobsLogToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "Jobs log is empty."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name,
                                    scriptId: e.ScriptId,
                                    scriptName: e.ScriptName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/jobs-log:event/view", e.selections[0]);
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        }
                    });
                }
            }
            Jobs.JobsLogGrid = JobsLogGrid;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsLogModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-jobs-log"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.settings.label = "Jobs | Log";
                    this.module_init();
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    if (this.m_grid) {
                        this.m_grid.refresh();
                    }
                }
                grid_init() {
                    this.m_grid = new Jobs.JobsLogGrid({
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                module_init() {
                    let service = new PDJS.Services.Jobs.JobsLogService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/jobs-log": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Jobs.JobsLogModule = JobsLogModule;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class JobsLogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs-log:event/view"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs-log:log/clear"
                    }));
                }
            }
            Jobs.JobsLogToolbar = JobsLogToolbar;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Jobs;
        (function (Jobs) {
            class ClearLogDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options, windowOptions = {}) {
                    super(options);
                }
                get selectNode() {
                    return this.node.find("select");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-jobs-clear-log-dialog">
                        <div role="text">Clear all log entries that are older than:</div>
                        <div role="control">
                            <select>
                                <option value="1">One Hour</option>
                                <option value="2">24 Hours</option>
                                <option value="3">One Week</option>
                                <option value="4">One Month</option>
                                <option value="5">One Year</option>
                                <option value="0">All Time</option>
                            </select>
                        </div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Clear | Jobs Log",
                        width: 300,
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                }
                closeAndReturn() {
                    this.close({
                        name: "ok",
                        data: {
                            scope: parseInt(this.selectNode.val())
                        }
                    });
                }
                static open(options) {
                    return new ClearLogDialog(options);
                }
            }
            Jobs.ClearLogDialog = ClearLogDialog;
        })(Jobs = Manage.Jobs || (Manage.Jobs = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get license() {
                    return this.state.get("license");
                }
                set license(value) {
                    this.state.set("license", value);
                }
                load(license) {
                    this.license = license;
                }
                template() {
                    return `<div class="-pdjs-manage-licenses-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Licenses"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Update Licenses",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/licensing:licenses/update");
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Download Licenses",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/licensing:licenses/download");
                        }
                    }));
                    this.controls.add(new Manage.Licensing.ReleaseReserveLink());
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Set License Key",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/licensing:licenses/set-license-key");
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Advanced Settings",
                        click: (e) => {
                            PDJS.Shared.Features.FeatureDialogForNhib.open({
                                title: `Licensing | Settings`,
                                height: 550,
                                width: 550,
                                args: {
                                    targetType: "ProspectDirector.Web.Manage.Modules.Licensing.LicensingSettingsUIO",
                                    arbiterType: "ProspectDirector.Web.Manage.Modules.Licensing.LicensingArbiter"
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                    this.controls.add(new Manage.Licensing.LicensingStatus());
                }
            }
            Licenses.LicensesActions = LicensesActions;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/licenses": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Licenses.LicensesCommand = LicensesCommand;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class ApplyLicenseCommand extends Licenses.LicensesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "license/apply",
                        label: "Apply Licenses",
                        icon: "plus.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Apply product licenses.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    PDJS.Manage.Licenses.ApplyLicenseDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.applyLicense(e.uploadId);
                            }
                        }
                    });
                }
                applyLicense(uploadId) {
                    let service = new PDJS.Services.Licenses.LicensesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Apply | Licenses",
                        showDetail: true,
                        taskStart: (e) => {
                            service.applyLicenses({
                                id: uploadId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskComplete: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Licenses.ApplyLicenseCommand = ApplyLicenseCommand;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class RemoveLicenseCommand extends Licenses.LicensesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "license/remove",
                        label: "Remove License",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Removes the license from the selected product.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Remove License?",
                        message: "Remove the selected license?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.removeLicense();
                            }
                        }
                    });
                }
                removeLicense() {
                    let service = new PDJS.Services.Licenses.LicensesService();
                    service.removeLicense({
                        id: this.selection.id,
                        success: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Licenses.RemoveLicenseCommand = RemoveLicenseCommand;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class ViewLicenseCommand extends Licenses.LicensesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "license/view",
                        label: "View License",
                        icon: "magnifying_glass.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "View the license for the selected product.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `License | ${this.selection.name}`,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Licensing.LicenseUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Licensing.LicenseArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                this.grid.refresh({ reselect: true });
                            }
                        }
                    });
                }
            }
            Licenses.ViewLicenseCommand = ViewLicenseCommand;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/licenses");
                }
                registerCommands(e) {
                    e.commands.add(new Licenses.ApplyLicenseCommand());
                    e.commands.add(new Licenses.RemoveLicenseCommand());
                    e.commands.add(new Licenses.ViewLicenseCommand());
                }
            }
            Licenses.LicensesCommands = LicensesCommands;
            Jade.CommandGroups.add(LicensesCommands);
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-licenses-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Licenses</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                    this.subscriptions.add(PDJS.Manage.Licensing.EventsHub.licensesUpdatedSubscribe(() => {
                        this.refresh();
                    }));
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Licenses.LicensesToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        defaultSelectionEnabled: true,
                        messaging: {
                            noRecordsMessage: "No licenses."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/licenses:license/view");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Licenses.LicensesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Licenses.LicensesGrid = LicensesGrid;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/licenses";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:license/view`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:license/remove`
                    }));
                }
            }
            Licenses.LicensesGridContextMenu = LicensesGridContextMenu;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    Manage.Licensing.EventsHub.moduleFocusPublish();
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-licenses">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Licenses.LicensesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Licenses.LicensesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Licenses.LicensesService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/licenses": {
                            $grid: this.m_grid
                        },
                        "pdjs/manage/licensing": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Licenses.LicensesModule = LicensesModule;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/licenses";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:license/apply`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:license/view`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:license/remove`
                    }));
                }
            }
            Licenses.LicensesToolbar = LicensesToolbar;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class ApplyLicenseDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options, windowOptions = {}) {
                    super(options);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                get uploadName() {
                    return this.state.get("uploadName");
                }
                set uploadName(value) {
                    this.state.set("uploadName", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`<div class="-pdjs-manage-licenses-apply-license-dialog">
                                        <div role="text">Select a license file (.lic or .licx) to apply.</div>
                                        <div role="progress"></div>
                                        <div role="buttons">
                                            <button class="-pdjs-dialog-button" data-id="ok" disabled>Apply</button>
                                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                                        </div>
                                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                uploadId: this.uploadId,
                                uploadName: this.uploadName
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                }
                getDefaultOptions() {
                    return {
                        title: "Apply | Licenses",
                        width: "400px",
                        maximized: false,
                        resizable: false
                    };
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=progress]",
                        mimeTypes: [
                            { title: "License File", extensions: "lic" },
                            { title: "License File", extensions: "licx" }
                        ],
                        onFileSelected: (e) => {
                        },
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.uploadName = e.name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options = {}) {
                    return new ApplyLicenseDialog(options);
                }
            }
            Licenses.ApplyLicenseDialog = ApplyLicenseDialog;
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licenses;
        (function (Licenses) {
            class LicensePropertiesEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get containerNode() {
                    return this.node.find("div[role=container]");
                }
                get grid() {
                    return this.m_grid;
                }
                template() {
                    return `<div class="-pdjs-manage-licenses-properties-editor">
                                <div role="container">
                                </div>
                            </div>`;
                }
                destroy() {
                    super.destroy();
                    if (this.grid != null) {
                        this.grid.destroy();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: `#${this.ID} DIV[role=container]`,
                        showToolbar: false,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            data: this.source.getFeatureValue("usage")
                        },
                        selectionMode: "none",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                field: "id",
                                width: "25px",
                                icon: "FORM_BLUE.png"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "type",
                                title: "Type",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
            }
            Licenses.LicensePropertiesEditor = LicensePropertiesEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Licenses.LicensePropertiesEditor", LicensePropertiesEditor);
            });
        })(Licenses = Manage.Licenses || (Manage.Licenses = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            let Events;
            (function (Events) {
                Events["ModuleFocus"] = "Module:Focus";
                Events["LicensesUpdated"] = "Licenses:Updated";
            })(Events = Licensing.Events || (Licensing.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static licensesUpdatedPublish() {
                    this.current.publish(Events.LicensesUpdated);
                }
                static moduleFocusPublish() {
                    this.current.publish(Events.ModuleFocus);
                }
                static licensesUpdatedSubscribe(handler) {
                    return this.current.subscribe(Events.LicensesUpdated, handler);
                }
                static moduleFocusSubscribe(handler) {
                    return this.current.subscribe(Events.ModuleFocus, handler);
                }
            }
            Licensing.EventsHub = EventsHub;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class LicensingCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/licensing": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Licensing.LicensingCommand = LicensingCommand;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class DownloadLicensesCommand extends Licensing.LicensingCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "licenses/download",
                        label: "Download Licenses",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: `Download your most recent licenses.`,
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    let service = new PDJS.Services.Licenses.LicensingService();
                    service.getGenerateUrl({
                        success: (e) => {
                            window.open(e.data.url);
                        }
                    });
                }
            }
            Licensing.DownloadLicensesCommand = DownloadLicensesCommand;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class SetLicenseKeyCommand extends Licensing.LicensingCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "licenses/set-license-key",
                        label: "Set License Key",
                        enabled: true,
                        display: "label",
                        tooltip: `Set the license key for your products.`,
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    Licensing.LicenseKeyDialog.open({
                        select: {
                            ok: (sender, e) => {
                                Licensing.EventsHub.licensesUpdatedPublish();
                            }
                        }
                    });
                }
            }
            Licensing.SetLicenseKeyCommand = SetLicenseKeyCommand;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class UpdateLicensesCommand extends Licensing.LicensingCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "licenses/update",
                        label: "Update Licenses",
                        enabled: true,
                        display: "label",
                        tooltip: `Update your products with the most recent licenses.`,
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    this.startTask();
                }
                startTask() {
                    let service = new PDJS.Services.Licenses.LicensingService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Licenses | Update",
                        taskStart: (e) => {
                            service.updateLicenses({
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        },
                        close: (e) => {
                            Licensing.EventsHub.licensesUpdatedPublish();
                        }
                    });
                }
            }
            Licensing.UpdateLicensesCommand = UpdateLicensesCommand;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class LicensingCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/licensing");
                }
                registerCommands(e) {
                    e.commands.add(new Licensing.DownloadLicensesCommand());
                    e.commands.add(new Licensing.SetLicenseKeyCommand());
                    e.commands.add(new Licensing.UpdateLicensesCommand());
                }
            }
            Licensing.LicensingCommands = LicensingCommands;
            Jade.CommandGroups.add(LicensingCommands);
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class LicensingStatus extends Jade.UI.Control {
                constructor(options = {}) {
                    super(options);
                }
                refresh() {
                    let service = new PDJS.Services.Licenses.LicensingService();
                    service.getRecentEvent({
                        success: (e) => {
                            this.setEventMessage(e.data.event);
                        },
                        error: (e) => {
                            e.errorHandled = true;
                            this.setEventMessage({
                                eventDate: new Date().toString(),
                                details: null,
                                eventId: -1,
                                message: "Connection Failed",
                                success: false,
                                url: null
                            });
                        }
                    });
                }
                template() {
                    return `<div class="-pdjs-manage-licensing-status"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.refresh();
                    this.subscriptions.add(Licensing.EventsHub.moduleFocusSubscribe(() => {
                        this.refresh();
                    }));
                    this.subscriptions.add(Licensing.EventsHub.licensesUpdatedSubscribe(() => {
                        this.refresh();
                    }));
                }
                setEventMessage(event) {
                    let text = "";
                    if (event == null) {
                        this.setMessage("Status Unknown");
                    }
                    let dateText = kendo.toString(new Date(event.eventDate), "MMMM dd, yyyy @ hh:mm:ss tt");
                    if (event.success) {
                        text += '<div role="text" level="Success">Connection to License Server Succeeded</div>';
                    }
                    else {
                        text += '<div role="text" level="Error">Connection to License Server Failed</div>';
                    }
                    text += `<div role="date">${dateText}</div>`;
                    this.setMessage(text);
                }
                setMessage(text) {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                    }
                    message = new PDJS.Shared.UI.Controls.Message({
                        message: text
                    });
                    this.controls.add(message);
                }
            }
            Licensing.LicensingStatus = LicensingStatus;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuLink extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get url() {
                        return this.state.get("url", "#");
                    }
                    set url(value) {
                        this.state.set("url", value);
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get description() {
                        return this.state.get("description");
                    }
                    set description(value) {
                        this.state.set("description", value);
                    }
                    get clickCallback() {
                        return this.state.get("click");
                    }
                    get largeText() {
                        return this.state.get("largeText", false);
                    }
                    get linkNode() {
                        return this.node.children("a");
                    }
                    get target() {
                        return this.state.get("target");
                    }
                    get dataId() {
                        return this.state.get("dataId", "");
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-link" data-id="${this.dataId}"><a href="#">${this.label}</a></div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setLinkUrl();
                        this.linkNode.text(this.label);
                        if (this.largeText) {
                            this.linkNode.css({
                                fontSize: "16px"
                            });
                        }
                        if (this.target != null) {
                            this.linkNode.attr("target", this.target);
                        }
                        this.ensureTooltip();
                    }
                    ensureTooltip() {
                        if (Jade.String.isNullOrWhiteSpace(this.description)) {
                            return;
                        }
                        PDJS.Shared.PopOver.tooltip(this.linkNode, this.description, {
                            fadeOut: 100,
                            hideAfter: 500,
                            hideDelay: 500,
                            hideOthers: true,
                            position: "leftmiddle",
                            radius: false,
                            showDelay: 0
                        });
                    }
                    setLinkUrl() {
                        let hasUrl = this.url != null &&
                            this.url != "#";
                        this.node.off(Jade.BrowserEvent.CLICK);
                        if (this.clickCallback != null) {
                            this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                                this.clickCallback(e);
                                e.preventDefault();
                                e.cancelBubble = true;
                                e.returnValue = false;
                                return false;
                            });
                            return;
                        }
                        if (hasUrl) {
                            this.linkNode.attr("href", Jade.Path.resolve(this.url));
                            return;
                        }
                    }
                }
                Controls.PanelMenuLink = PanelMenuLink;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class ReleaseReserveLink extends PDJS.Shared.UI.Controls.PanelMenuLink {
                constructor() {
                    super({
                        click: () => { this.click(); },
                        label: "Loading..."
                    });
                    this.m_service = new PDJS.Services.Licenses.LicensingService();
                }
                get action() {
                    return this.state.get("action");
                }
                set action(value) {
                    this.state.set("action", value);
                }
                get service() {
                    return this.m_service;
                }
                refresh() {
                    this.service.canReserve({
                        success: (e) => {
                            this.setReserveState(e.data.value);
                        }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.refresh();
                }
                click() {
                    if (this.action == "release") {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                            title: "Release Licenses",
                            message: "This action will release the licenses from this instance and free those licenses to be reserved by another instance.<br/><br/>Release the licences for this instance?",
                            select: {
                                yes: (e) => {
                                    e.close();
                                    this.release();
                                }
                            }
                        });
                        return;
                    }
                    if (this.action == "reserve") {
                        this.reserve();
                        return;
                    }
                }
                release() {
                    let error = (e) => {
                        e.errorHandled = true;
                        PDJS.Shared.MessageStack.instance
                            .error("This instance failed to release its licenses.");
                    };
                    let release = () => {
                        this.service.release({
                            success: (e) => {
                                PDJS.Shared.MessageStack.instance
                                    .success("This instance has released its licenses.");
                                this.setReserveState(true);
                                Licensing.EventsHub.licensesUpdatedPublish();
                            },
                            error: (e) => { error(e); }
                        });
                    };
                    this.service.getReleaseURL({
                        success: (e) => {
                            PDJS.Ajax.call({
                                url: e.data.url,
                                success: (e) => {
                                    release();
                                },
                                error: (e) => { error(e); }
                            });
                        }
                    });
                }
                reserve() {
                    let error = (e) => {
                        e.errorHandled = true;
                        PDJS.Shared.MessageStack.instance
                            .error("This instance failed to reserve its licenses.");
                    };
                    let reserve = () => {
                        this.service.reserve({
                            success: (e) => {
                                PDJS.Shared.MessageStack.instance
                                    .success("This instance has reserved its licenses.");
                                this.setReserveState(false);
                                Licensing.EventsHub.licensesUpdatedPublish();
                            },
                            error: (e) => { error(e); }
                        });
                    };
                    this.service.getReserveURL({
                        success: (e) => {
                            PDJS.Ajax.call({
                                url: e.data.url,
                                success: (e) => {
                                    reserve();
                                },
                                error: (e) => { error(e); }
                            });
                        }
                    });
                }
                setReserveState(value) {
                    if (value) {
                        this.label = "Reserve Licenses";
                        this.action = "reserve";
                    }
                    else {
                        this.label = "Release Licenses";
                        this.action = "release";
                    }
                }
            }
            Licensing.ReleaseReserveLink = ReleaseReserveLink;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class LicenseKeyDialog extends Jade.UI.Dialogs.Dialog {
                get field() {
                    return this.m_field;
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-license-key-dialog">
                        <div role="control" data-controls></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Set | License Key",
                        width: 400,
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    let service = new PDJS.Services.Licenses.LicensingService();
                    service.getLicenseKey({
                        success: (e) => {
                            this.field.value = e.data.licenseKey;
                        }
                    });
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.setLicenseKey();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.field_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    setTimeout(() => {
                        this.center();
                    }, 25);
                }
                field_init() {
                    this.m_field = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "License Key",
                        multiline: true,
                        height: 80
                    });
                    this.controls.add(this.m_field);
                }
                setLicenseKey() {
                    let service = new PDJS.Services.Licenses.LicensingService();
                    service.setLicenseKey({
                        licenseKey: this.field.value,
                        success: () => {
                            PDJS.Shared.MessageStack.instance.success("License key validated and applied.");
                            this.close();
                            Licensing.EventsHub.licensesUpdatedPublish();
                        }
                    });
                }
                static open(options = {}) {
                    return new LicenseKeyDialog(options);
                }
            }
            Licensing.LicenseKeyDialog = LicenseKeyDialog;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get mail() {
                    return this.state.get("tag");
                }
                set mail(value) {
                    this.state.set("tag", value);
                }
                load(mail) {
                    this.mail = mail;
                }
                template() {
                    return `<div class="-pdjs-manage-mail-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    let prefix = "pdjs/manage/mail";
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Mail Settings"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Manage",
                        click: (e) => {
                            PDJS.Application.instance
                                .contexts
                                .current
                                .commands
                                .execute(`${prefix}:mail-settings/edit`);
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Test Settings",
                        click: (e) => {
                            PDJS.Application.instance
                                .contexts
                                .current
                                .commands
                                .execute(`${prefix}:mail-settings/test`);
                        }
                    }));
                }
            }
            Mail.MailActions = MailActions;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/mail": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Mail.MailCommand = MailCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailDeleteAllCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail/delete-all",
                        label: "Delete All",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Delete all messages in the queue.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Queued Messages",
                        message: "Delete all the queued messages in the queue?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.deleteMail();
                            }
                        }
                    });
                }
                deleteMail() {
                    let service = new PDJS.Services.Mail.MailService();
                    service.deleteAll({
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Mail.MailDeleteAllCommand = MailDeleteAllCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailDeleteCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected messages.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Queued Message",
                        message: "Delete the selected mail message?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.deleteMail();
                            }
                        }
                    });
                }
                deleteMail() {
                    let service = new PDJS.Services.Mail.MailService();
                    service.deleteItem({
                        id: this.selection.id,
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Mail.MailDeleteCommand = MailDeleteCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailResendAllCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail/resend-all",
                        label: "Resend All",
                        icon: "mail_forward.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Resend all messages in the queue.",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Resend Queued Messages",
                        message: "Resend all the queued messages in the queue?",
                        select: (sender, e) => {
                            sender.close();
                            this.resendMail();
                        }
                    });
                }
                resendMail() {
                    let service = new PDJS.Services.Mail.MailService();
                    service.resendAll({
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Mail.MailResendAllCommand = MailResendAllCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailResendCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail/resend",
                        label: "Resend",
                        icon: "mail_forward.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Resend the selected messages.",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Resend Queued Message",
                        message: "Resend the selected mail message?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.resendMail();
                            }
                        }
                    });
                }
                resendMail() {
                    let service = new PDJS.Services.Mail.MailService();
                    service.resendItem({
                        id: this.selection.id,
                        success: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Mail.MailResendCommand = MailResendCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailSettingsCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail-settings/edit",
                        label: "Mail Settings",
                        icon: "server_mail.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Edit the settings using to send email.",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "Mail Settings",
                        minHeight: 500,
                        height: 570,
                        width: 500,
                        args: {
                            targetId: "mail.server.settings",
                            targetType: "ProspectDirector.Web.Manage.Modules.Mail.MailServerUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Mail.MailServerArbiter"
                        }
                    });
                }
            }
            Mail.MailSettingsCommand = MailSettingsCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailSettingsTestCommand extends Mail.MailCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "mail-settings/test",
                        label: "Test | Mail Settings",
                        icon: "server_mail.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Test the configured mail settings.",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    PDJS.Manage.Mail.TestMailSettingsDialog.open();
                }
            }
            Mail.MailSettingsTestCommand = MailSettingsTestCommand;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/mail");
                }
                registerCommands(e) {
                    e.commands.add(new Mail.MailDeleteAllCommand());
                    e.commands.add(new Mail.MailDeleteCommand());
                    e.commands.add(new Mail.MailResendAllCommand());
                    e.commands.add(new Mail.MailResendCommand());
                    e.commands.add(new Mail.MailSettingsCommand());
                    e.commands.add(new Mail.MailSettingsTestCommand());
                }
            }
            Mail.MailCommands = MailCommands;
            Jade.CommandGroups.add(MailCommands);
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-mail-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Mail</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Mail.TagsGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No mail."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId
                                };
                            }
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Mail.MailGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Mail.MailGrid = MailGrid;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/mail";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:mail/resend`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:mail/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:mail/resend-all`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:mail/delete-all`
                    }));
                }
            }
            Mail.MailGridContextMenu = MailGridContextMenu;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class TagsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/mail";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:mail/resend`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:mail/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:mail/resend-all`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:mail/delete-all`
                    }));
                }
            }
            Mail.TagsGridToolbar = TagsGridToolbar;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class MailModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-mail">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Mail.MailGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Mail.MailActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Mail.MailService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/mail": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Mail.MailModule = MailModule;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Mail;
        (function (Mail) {
            class TestMailSettingsDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get input() {
                    return this.m_input;
                }
                get inputNode() {
                    return this.node.find("input");
                }
                get sendButtonNode() {
                    return this.node.find("button[data-id=send]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-test-email-settings-dialog">
                    <div role="header">
                        Input one or more email addresses, separated by semicolons, 
                        into the 'Send To' field below and click 'Send Test Mail' to send 
                        a test email to the specified recepients.
                    </div>
                    <div role="input" data-controls></div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-id="send">Send Test Mail</button>
                        <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Mail Settings | Test",
                        width: 500,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.sendButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.input_init();
                }
                onInputReturnKeystroke() {
                    super.onInputReturnKeystroke();
                    this.closeAndReturn();
                }
                input_init() {
                    this.m_input = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Send To",
                        required: true,
                        maxLength: 1000,
                        validateOnBlur: false
                    });
                    this.controls.add(this.m_input);
                }
                closeAndReturn() {
                    this.input.validate();
                    if (!this.input.isValid) {
                        return;
                    }
                    this.close();
                    this.executeTest();
                }
                executeTest() {
                    let service = new PDJS.Services.Mail.MailService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Mail Settings | Send Test Mail",
                        showDetail: true,
                        autoCloseOnSuccess: false,
                        taskStart: (e) => {
                            service.testMailSettings({
                                sendTo: this.input.value,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        }
                    });
                }
                static open(options) {
                    return new TestMailSettingsDialog(options);
                }
            }
            Mail.TestMailSettingsDialog = TestMailSettingsDialog;
        })(Mail = Manage.Mail || (Manage.Mail = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceActions extends PDJS.Shared.UI.Controls.PanelMenu {
                constructor(options) {
                    super(options);
                }
                get startAt() {
                    return this.state.get("startAt");
                }
                template() {
                    return `<div class="-pdjs-manage-tags-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.addStatus();
                }
                addStatus() {
                    let status = new Maintenance.MaintenanceStatus({
                        startAtString: this.startAt
                    });
                    this.controls.add(status);
                }
            }
            Maintenance.MaintenanceActions = MaintenanceActions;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$status", null);
                    this.state.set("$usersGrid", null);
                    this.state.set("$preview", null);
                }
                get preview() {
                    return this.state.get("$preview");
                }
                get status() {
                    return this.state.get("$status");
                }
                get usersGrid() {
                    return this.state.get("$usersGrid");
                }
                get userSelections() {
                    var _a;
                    return ((_a = this.usersGrid) === null || _a === void 0 ? void 0 : _a.selections) || [];
                }
                get selectedUserIds() {
                    return this.userSelections.map(item => item.id);
                }
                get mode() {
                    var _a;
                    return ((_a = this.status) === null || _a === void 0 ? void 0 : _a.mode) || "stopped";
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/maintenance": {
                            $usersGrid: this.usersGrid
                        }
                    }, { force: true });
                }
            }
            Maintenance.MaintenanceCommand = MaintenanceCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class AddUsersCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "users/add",
                        label: "Add Users",
                        enabled: true,
                        icon: "plus.png",
                        display: "label icon",
                        tooltip: "Add users who should be allowed access to the application during the maintenance period.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                }
                execute(e) {
                    PDJS.Shared.Security.IdentityBrowserDialog.open({
                        title: "Select | Allowed Users",
                        filters: [
                            PDJS.Core.Views.IdentityFilter.activeOnly(),
                            PDJS.Core.Views.IdentityFilter.usersOnly(),
                            PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
                        ],
                        select: (sender, e) => {
                            sender.close();
                            this.addUsers(e.map(i => i.id));
                        }
                    });
                }
                addUsers(userIds) {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.addUsers({
                        ids: userIds,
                        success: (e) => {
                            this.usersGrid.load(e.data);
                        }
                    });
                }
            }
            Maintenance.AddUsersCommand = AddUsersCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class RemoveUsersCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "users/remove",
                        label: "Remove Users",
                        enabled: true,
                        icon: "delete.png",
                        display: "label icon",
                        tooltip: "Remove users who should not be allowed access to the application during the maintenance period.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    var _a;
                    super.onStateChanged(state);
                    this.enabled = ((_a = this.userSelections) === null || _a === void 0 ? void 0 : _a.length) > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Remove Users",
                        message: `Remove the selected users from the "Allowed Users" list?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.removeUsers();
                            }
                        }
                    });
                }
                removeUsers() {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.removeUsers({
                        ids: this.selectedUserIds,
                        success: (e) => {
                            this.usersGrid.load(e.data);
                        }
                    });
                }
            }
            Maintenance.RemoveUsersCommand = RemoveUsersCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class ResetMessageCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "message/reset",
                        label: "Reset Message",
                        enabled: true,
                        icon: "undo.png",
                        display: "label icon",
                        tooltip: "Reset the text of the maintenance message to the default text.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.setMessage({
                        content: null,
                        success: (e) => {
                            this.preview.update(null);
                        }
                    });
                }
            }
            Maintenance.ResetMessageCommand = ResetMessageCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class ScheduleMaintenanceCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "maintenance/schedule",
                        label: "Schedule",
                        enabled: true,
                        display: "label",
                        tooltip: "Schedule application maintenace to start at a future date and time."
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    let mode = this.mode;
                    this.visible =
                        mode === "scheduled" ||
                            mode === "stopped";
                    switch (mode) {
                        case "scheduled":
                            this.label = "Reschedule";
                            break;
                        case "stopped":
                            this.label = "Schedule";
                            break;
                    }
                }
                execute(e) {
                    Maintenance.ScheduleMaintenanceDialog.open({
                        startAt: this.status.startAt,
                        select: {
                            ok: (sender, e) => {
                                this.status.schedule(e.startAt);
                                this.setCommandState();
                            }
                        }
                    });
                }
            }
            Maintenance.ScheduleMaintenanceCommand = ScheduleMaintenanceCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class SetMessageCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "message/set",
                        label: "Edit Message",
                        enabled: true,
                        icon: "pencil.png",
                        display: "label icon",
                        tooltip: "Change the text of the maintenance message.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    let message = Jade.String.isNullOrWhiteSpace(this.preview.message) ?
                        this.preview.defaultMessage : this.preview.message;
                    Maintenance.MaintenanceMessageDialog.open({
                        content: message,
                        select: {
                            ok: (sender, e) => {
                                this.setMessage(e.value);
                            }
                        }
                    });
                }
                setMessage(content) {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.setMessage({
                        content: content,
                        success: (e) => {
                            this.preview.update(content);
                        }
                    });
                }
            }
            Maintenance.SetMessageCommand = SetMessageCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class StartMaintenanceCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "maintenance/start",
                        label: "Start Now",
                        enabled: true,
                        display: "label",
                        tooltip: "Start application maintenance immediately."
                    };
                }
                onStateChanged(state) {
                    var _a;
                    super.onStateChanged(state);
                    this.visible = ((_a = this.status) === null || _a === void 0 ? void 0 : _a.mode) == "stopped";
                }
                execute(e) {
                    this.showStartMaintenanceDialog();
                }
                showStartMaintenanceDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Start Maintenance Mode",
                        message: `Start maintenance mode?<br/><br/>
                            All users not in the "Allowed Users" list will be immediately locked out of the system.`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startMaintenance();
                            }
                        }
                    });
                }
                startMaintenance() {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.start({
                        success: (e) => {
                            this.status.start();
                            this.setCommandState();
                        }
                    });
                }
            }
            Maintenance.StartMaintenanceCommand = StartMaintenanceCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class StopMaintenanceCommand extends Maintenance.MaintenanceCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "maintenance/stop",
                        label: "Stop",
                        enabled: true,
                        display: "label",
                        tooltip: "Start application maintenance immediately."
                    };
                }
                onStateChanged(state) {
                    var _a, _b, _c;
                    super.onStateChanged(state);
                    this.visible =
                        ((_a = this.status) === null || _a === void 0 ? void 0 : _a.mode) === "started" ||
                            ((_b = this.status) === null || _b === void 0 ? void 0 : _b.mode) === "scheduled";
                    switch ((_c = this.status) === null || _c === void 0 ? void 0 : _c.mode) {
                        case "started":
                            this.label = "Stop";
                            break;
                        case "scheduled":
                            this.label = "Cancel";
                            break;
                    }
                }
                execute(e) {
                    if (this.status.mode == "started") {
                        this.showStopMaintenanceDialog();
                        return;
                    }
                    if (this.status.mode == "scheduled") {
                        this.showCancelMaintenanceDialog();
                        return;
                    }
                }
                showStopMaintenanceDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Stop Maintenance Mode",
                        message: `Stop maintenance mode?<br/><br/>
                            All users that are currently locked out of the system
                            will immediately be granted access to the system.`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.stopMaintenance();
                            }
                        }
                    });
                }
                showCancelMaintenanceDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Cancel Scheduled Maintenance",
                        message: `Cancel the currently scheduled maintenance?<br/><br/>
                            The scheduled maintence will be removed and the system will no longer
                            automatically enter maintenance at the currently prescribed date and time.`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.stopMaintenance();
                            }
                        }
                    });
                }
                stopMaintenance() {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.stop({
                        success: (e) => {
                            this.status.stop();
                            this.setCommandState();
                        }
                    });
                }
            }
            Maintenance.StopMaintenanceCommand = StopMaintenanceCommand;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/maintenance");
                }
                registerCommands(e) {
                    e.commands.add(new Maintenance.AddUsersCommand());
                    e.commands.add(new Maintenance.RemoveUsersCommand());
                    e.commands.add(new Maintenance.ResetMessageCommand());
                    e.commands.add(new Maintenance.ScheduleMaintenanceCommand());
                    e.commands.add(new Maintenance.SetMessageCommand());
                    e.commands.add(new Maintenance.StartMaintenanceCommand());
                    e.commands.add(new Maintenance.StopMaintenanceCommand());
                }
            }
            Maintenance.MaintenanceCommands = MaintenanceCommands;
            Jade.CommandGroups.add(MaintenanceCommands);
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceMessage extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeButton() {
                    return this.node.find("BUTTON[data-id=change]");
                }
                get defaultMessage() {
                    return this.state.get("defaultMessage");
                }
                get message() {
                    return this.state.get("message");
                }
                set message(value) {
                    this.state.set("message", value);
                }
                get preview() {
                    return this.state.get("preview");
                }
                get resetButton() {
                    return this.node.find("BUTTON[data-id=reset]");
                }
                update(message) {
                    this.message = message;
                    this.content_init();
                }
                reset() {
                    this.content_init();
                }
                template() {
                    return `<div class="-pdjs-manage-maintenance-message">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Message Preview</div>
                        <div role="menu"></div>
                        <div role="body" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.content_init();
                    this.menu_init();
                    this.setCommandState();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Maintenance.MaintenanceMessageToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                content_init() {
                    let content = this.controls.getByType(Maintenance.MaintenanceMessageContent).first();
                    if (content != null) {
                        this.controls.remove(content);
                    }
                    this.m_content = new Maintenance.MaintenanceMessageContent({
                        icon: this.preview.icon,
                        applicationName: this.preview.applicationName,
                        defaultMessage: this.defaultMessage,
                        message: this.message,
                        tagline: this.preview.tagline,
                        title: this.preview.title
                    });
                    this.controls.add(this.m_content);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/maintenance": {
                            $preview: this
                        }
                    }, { force: true });
                }
            }
            Maintenance.MaintenanceMessage = MaintenanceMessage;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceMessageContent extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get applicationName() {
                    return this.state.get("applicationName");
                }
                get defaultMessage() {
                    return this.state.get("defaultMessage");
                }
                get icon() {
                    return this.state.get("icon");
                }
                get iconPath() {
                    return Jade.IconSet.get("pdv2")
                        .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x256);
                }
                get message() {
                    return this.state.get("message");
                }
                get tagline() {
                    return this.state.get("tagline");
                }
                get title() {
                    return this.state.get("title");
                }
                template() {
                    let message = Jade.String.isNullOrWhiteSpace(this.message) ?
                        this.defaultMessage : this.message;
                    return `
                <div class="-pdjs-message-screen">
                    <div class="-pdjs-message-screen-box">
                        <div class="-pdjs-message-screen-box-title">
                            ${this.applicationName}
                        </div>
                        <div class="-pdjs-message-screen-box-content">
                            <div class="-pdjs-message-screen-box-icon-pane">
                                <div class="-pdjs-message-screen-box-icon">
                                    <img src="${this.iconPath}" />
                                </div>
                                <div class="-pdjs-message-screen-box-icon-text">
                                    ${this.tagline}
                                </div>
                            </div>
                            <div class="-pdjs-message-screen-box-text-pane">
                                <div class="-pdjs-message-screen-box-text-title">
                                    ${this.title}
                                </div>
                                <div class="-pdjs-message-screen-box-text">
                                    ${message}
                                </div>
                                <div class="-pdjs-message-screen-box-instruction">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`;
                }
            }
            Maintenance.MaintenanceMessageContent = MaintenanceMessageContent;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceMessageToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/maintenance";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:message/set`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:message/reset`
                    }));
                }
            }
            Maintenance.MaintenanceMessageToolbar = MaintenanceMessageToolbar;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-tags">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.module_init();
                }
                grid_init(e) {
                    this.m_grid = new Maintenance.MaintenanceUsersGrid({
                        insertAt: "div[data-id=pane-1]",
                        allowedUsers: e.allowedUsers,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                message_init(e) {
                    this.m_message = new Maintenance.MaintenanceMessage({
                        insertAt: "div[data-id=pane-2]",
                        preview: e.preview,
                        message: e.settings.message,
                        defaultMessage: e.settings.defaultMessage
                    });
                    this.controls.add(this.m_message);
                }
                actions_init(e) {
                    this.m_actions = new Maintenance.MaintenanceActions({
                        insertAt: "div[data-id=pane-3]",
                        startAt: e.settings.startAt
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.index({
                        success: (e) => {
                            this.message_init(e.data);
                            this.grid_init(e.data);
                            this.actions_init(e.data);
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "400px", scrollable: false },
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/maintenance": {
                            $usersGrid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Maintenance.MaintenanceModule = MaintenanceModule;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceStatus extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get startAt() {
                    return this.state.get("startAt");
                }
                set startAt(value) {
                    this.state.set("startAt", value);
                }
                get startAtString() {
                    return this.state.get("startAtString");
                }
                get mode() {
                    return this.m_mode || "stopped";
                }
                set mode(value) {
                    this.m_mode = value;
                }
                stop() {
                    this.mode = "stopped";
                    this.stopCountdown();
                    this.m_billboard.setStopped();
                }
                start() {
                    this.mode = "started";
                    this.startAt = new Date(Date.now());
                    this.startCountdown(this.startAt);
                    this.m_billboard.setStarted();
                }
                schedule(startAt) {
                    this.mode = "scheduled";
                    this.startAt = this.convertStringToDate(startAt);
                    this.startCountdown(this.startAt);
                    this.m_billboard.setScheduled(this.startAt);
                }
                template() {
                    return `<div class="-pdjs-manage-maintenance-status">
                        <div data-controls></div>
                        <div role="deck"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.billboard_init();
                    this.addButton("maintenance/start");
                    this.addButton("maintenance/stop");
                    this.addButton("maintenance/schedule");
                    this.setCommandState();
                    this.startAt = this.convertStringToDate(this.startAtString);
                    if (this.startAt != null) {
                        (this.startAt.getTime() < Date.now()) ?
                            this.start() : this.schedule(this.startAtString);
                    }
                    else {
                        this.stop();
                    }
                }
                addButton(commandId) {
                    let button = new PDJS.Shared.UI.Controls.CommandButton({
                        insertAt: "div[role=deck]",
                        commandId: `pdjs/manage/maintenance:${commandId}`
                    });
                    this.controls.add(button);
                }
                billboard_init() {
                    this.m_billboard = new Maintenance.MaintenanceBillboard({});
                    this.controls.add(this.m_billboard);
                }
                startCountdown(startAt) {
                    this.stopCountdown();
                    if (startAt == null) {
                        return;
                    }
                    countdown.setLabels("| sec| min| hrs| day| week| month| year|||", "| sec| min| hrs| days| weeks| months| years|||");
                    this.m_timerId = countdown(startAt, (ts) => {
                        this.updateCountdown(ts.start, ts);
                    }, countdown.DAYS |
                        countdown.HOURS |
                        countdown.MINUTES |
                        countdown.SECONDS);
                }
                updateCountdown(startAt, timeSpan) {
                    if (timeSpan == null) {
                        this.stopCountdown();
                        if (this.mode != "stopped") {
                            this.startCountdown(startAt);
                        }
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/maintenance": {
                            $status: this
                        }
                    }, { force: true });
                    this.m_billboard.update(this.mode, timeSpan);
                }
                stopCountdown() {
                    if (this.m_timerId != null) {
                        window.clearInterval(this.m_timerId);
                    }
                }
                convertStringToDate(value) {
                    return _.isDate(value) ? value :
                        _.isString(value) ? new Date(value) : null;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/maintenance": {
                            $status: this
                        }
                    }, { force: true });
                }
            }
            Maintenance.MaintenanceStatus = MaintenanceStatus;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceUsersGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get allowedUsers() {
                    return this.state.get("allowedUsers", []);
                }
                set allowedUsers(value) {
                    this.state.set("allowedUsers", value);
                }
                load(items) {
                    this.allowedUsers = items;
                    this.m_grid.get_dataSource().data([]);
                    this.m_grid.get_dataSource().data(items);
                    this.m_grid.refresh({ clear: true, selections: [] });
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-maintenance-users-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Allowed Users</div>
                        <div role="menu"></div>
                        <div role="title">Only users added to the list below will be allowed access to the system during maintenance. Members of the admminstrators group are always allowed access.</div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Maintenance.MaintenanceUsersGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: `[id=${this.ID}] [role=grid]`,
                        pk: "id",
                        dataSource: {
                            storeAsLocalVariable: true,
                            data: this.allowedUsers
                        },
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        defaultSelectionEnabled: true,
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.id,
                                    name: e.name,
                                    displayName: e.displayName
                                };
                            }
                        },
                        messaging: {
                            noRecordsMessage: "No non-admin users allowed access."
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                resizable: false
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Name",
                                field: "name"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "User ID",
                                field: "userId"
                            }),
                        ],
                        contextMenu: (e) => {
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Tags.TagsGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Maintenance.MaintenanceUsersGrid = MaintenanceUsersGrid;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceUsersGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/maintenance";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:users/add`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:users/remove`
                    }));
                }
            }
            Maintenance.MaintenanceUsersGridToolbar = MaintenanceUsersGridToolbar;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceBillboard extends Jade.UI.Control {
                get iconNode() {
                    return this.node.find(".-pdjs-manage-maintenance-billboard-icon").find("i");
                }
                get textNode() {
                    return this.node.find(".-pdjs-manage-maintenance-billboard-text");
                }
                get labelNode() {
                    return this.node.find(".-pdjs-manage-maintenance-billboard-text-label");
                }
                get timerNode() {
                    return this.node.find(".-pdjs-manage-maintenance-billboard-text-timer");
                }
                get startAt() {
                    return this.state.get("startAt");
                }
                set startAt(value) {
                    this.state.set("startAt", value);
                }
                setStopped() {
                    this.removeClasses();
                    this.node.addClass("-pdjs-manage-maintenance-stopped");
                    this.labelNode.text("System Is Operational");
                    this.timerNode.html("No maintenance pending.");
                    this.iconNode.addClass("icofont-check-circled");
                }
                setScheduled(startAt) {
                    this.startAt = startAt;
                    this.removeClasses();
                    this.node.addClass("-pdjs-manage-maintenance-scheduled");
                    this.labelNode.text("Maintenance Will Start In");
                    this.iconNode.addClass("icofont-warning");
                }
                setStarted() {
                    this.removeClasses();
                    this.node.addClass("-pdjs-manage-maintenance-started");
                    this.labelNode.text("System Under Maintenance");
                    this.iconNode.addClass("icofont-ban");
                }
                template() {
                    return `<div class="-pdjs-manage-maintenance-billboard">
                        <div class="-pdjs-manage-maintenance-billboard-icon">
                            <i></i>
                        </div>
                        <div class="-pdjs-manage-maintenance-billboard-text">
                            <div class="-pdjs-manage-maintenance-billboard-text-label"></div>
                            <div class="-pdjs-manage-maintenance-billboard-text-timer"></div>
                        </div>
                    </div>`;
                }
                update(mode, timeSpan = null) {
                    this.setTimerText(mode, timeSpan);
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                removeClasses() {
                    this.node.removeClass("-pdjs-manage-maintenance-stopped");
                    this.node.removeClass("-pdjs-manage-maintenance-started");
                    this.node.removeClass("-pdjs-manage-maintenance-scheduled");
                    this.iconNode.removeClass("icofont-check-circled");
                    this.iconNode.removeClass("icofont-warning");
                    this.iconNode.removeClass("icofont-error");
                }
                formatCountdownDate(startAt) {
                    return kendo.toString(startAt, "MMMM dd, yyyy @ h:mm tt");
                }
                setTimerText(mode, timeSpan) {
                    this.timerNode.empty();
                    switch (true) {
                        case mode != "stopped" && timeSpan != null:
                            var startDate = new Date(timeSpan.start);
                            this.timerNode.html(timeSpan.toHTML("strong") + "<br/>&nbsp;on&nbsp;<i>" + this.formatCountdownDate(startDate) + "</i>");
                            break;
                        case mode == "stopped":
                            this.timerNode.html("No maintenance pending.");
                            break;
                        default:
                            this.timerNode.html("<i>Calculating...</i>");
                            break;
                    }
                }
            }
            Maintenance.MaintenanceBillboard = MaintenanceBillboard;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class RichTextMceDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    get mce() {
                        return this.m_mce;
                    }
                    set mce(value) {
                        this.m_mce = value;
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-id=button-ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=button-cancel]");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-shared-controls-rich-text-mce-dialog">
                    <div role="mce"></div>
                    <div role="deck">
                        <button 
                            data-id="button-ok"  
                            class="-jadeui-dialog-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-jadeui-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.mce_init();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.closeAndReturn();
                        });
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                    }
                    getDefaultOptions() {
                        return {
                            title: "Text Editor",
                            height: 500,
                            width: 450,
                            minHeight: 250,
                            minWidth: 250
                        };
                    }
                    mce_init() {
                        this.mce = new Controls.RichTextMce({
                            insertAt: "div[role=mce]",
                            content: this.value,
                            theme: "manage",
                            change: (e) => {
                                this.value = e.value;
                            }
                        });
                        this.controls.add(this.mce);
                    }
                    closeAndReturn() {
                        this.close({
                            name: "ok",
                            data: {
                                value: this.mce.value
                            }
                        });
                    }
                    static open(options) {
                        return new RichTextMceDialog(options);
                    }
                }
                Controls.RichTextMceDialog = RichTextMceDialog;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceMessageDialog extends PDJS.Shared.UI.Controls.RichTextMceDialog {
                constructor(options) {
                    super(options);
                }
                static open(options) {
                    options.value = options.content;
                    return new MaintenanceMessageDialog(options);
                }
            }
            Maintenance.MaintenanceMessageDialog = MaintenanceMessageDialog;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Maintenance;
        (function (Maintenance) {
            class ScheduleMaintenanceDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get startAt() {
                    return this.state.get("startAt");
                }
                get okButton() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButton() {
                    return this.node.find("button[data-id=cancel]");
                }
                get dateInput() {
                    return this.node.find("input[role=date]");
                }
                get hourInput() {
                    return this.node.find("select[role=hour]");
                }
                get minuteInput() {
                    return this.node.find("select[role=minute]");
                }
                get meridiemInput() {
                    return this.node.find("select[role=meridiem]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-maintenance-scheduler-dialog">
                    <div>
                        Schedule a future date and time for the system to enter maintenance mode.
                    </div>
                    <div>
                        <div>Start Maintenance On:</div>
                        <div>
                            <input role="date" type="text" style="width:75px;" />
                        </div>
                        <div>@</div>
                        <div>
                            <select role="hour"></select>
                        </div>
                        <div>:</div>
                        <div>
                            <select role="minute"></select>
                        </div>
                        <div>
                            <select role="meridiem">
                                <option value="AM">AM</option>
                                <option value="PM">PM</option>
                            </select>
                        </div>
                        <div></div>
                    </div>
                    <div data-id="button-deck" style="height:26px">
                        <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.fillDate();
                    this.fillHours();
                    this.fillMinutes();
                    this.populateInputs();
                }
                getDefaultOptions() {
                    return {
                        title: "Schedule Maintenance",
                        resizable: false,
                        width: "400px"
                    };
                }
                onInputReturnKeystroke() {
                    super.onInputReturnKeystroke();
                    this.okAndEnter();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                okButton_onClick(e) {
                    this.okAndEnter();
                }
                okAndEnter() {
                    let service = new PDJS.Services.Maintenance.MaintenanceService();
                    service.schedule({
                        startAt: this.getResult(),
                        success: (e) => {
                            this.close({
                                name: "ok",
                                data: {
                                    startAt: this.getResult()
                                }
                            });
                        },
                        error: (e) => {
                            let item = _.first(e.xhr.responseJSON);
                            if ((item === null || item === void 0 ? void 0 : item.key) == "StartAt") {
                                e.errorHandled = true;
                                Jade.UI.Dialogs.MessageDialog.open({
                                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                    title: "Schedule Error",
                                    message: item.message
                                });
                            }
                        }
                    });
                }
                fillHours() {
                    _.times(12, (index) => {
                        let value = index + 1;
                        this.hourInput.append(`<option value="${value}">${value}</option>`);
                    });
                }
                fillMinutes() {
                    _.times(60, (index) => {
                        let value = index < 10 ? "0" + index : index;
                        this.minuteInput.append(`<option value="${value}">${value}</option>`);
                    });
                }
                fillDate() {
                    let current = new Date();
                    let dd = current.getDate();
                    let mm = current.getMonth() + 1;
                    let yy = current.getFullYear();
                    this.dateInput.val(`${mm}/${dd}/${yy}`);
                }
                getResult(convertToDate = false) {
                    let result = null;
                    let date = this.dateInput.val();
                    let hour = this.hourInput.val();
                    let minute = this.minuteInput.val();
                    let meridiem = this.meridiemInput.val();
                    if (!Jade.String.isNullOrWhiteSpace(date)) {
                        result = `${date} ${hour}:${minute}:00 ${meridiem}`;
                    }
                    return result;
                }
                populateInputs() {
                    let startAt = this.startAt == null ?
                        new Date(Date.now() + (1 * 60 * 60 * 1000)) : this.startAt;
                    let year = null;
                    let month = null;
                    let day = null;
                    let hour = null;
                    let minute = null;
                    let meridiem = null;
                    if (startAt instanceof Date) {
                        year = startAt.getFullYear();
                        month = startAt.getMonth() + 1;
                        day = startAt.getDate();
                        hour = startAt.getHours();
                        meridiem = hour < 12 ? "AM" : "PM";
                        hour = hour < 13 ? hour : hour - 12;
                        minute = startAt.getMinutes();
                        this.dateInput.val(`${month}/${day}/${year}`);
                        this.hourInput.val(hour == 0 ? 12 : hour);
                        this.minuteInput.val(minute < 10 ? "0" + minute : minute);
                        this.meridiemInput.val(meridiem);
                    }
                    else {
                        this.dateInput.val(this.getCurrentDate());
                    }
                    this.dateInput.select();
                    this.dateInput.focus();
                }
                getCurrentDate() {
                    let now = new Date();
                    let dd = now.getDate();
                    let mm = now.getMonth() + 1;
                    let yy = now.getFullYear();
                    return `${mm}/${dd}/${yy}`;
                }
                static open(options) {
                    return new ScheduleMaintenanceDialog(options);
                }
            }
            Maintenance.ScheduleMaintenanceDialog = ScheduleMaintenanceDialog;
        })(Maintenance = Manage.Maintenance || (Manage.Maintenance = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            let Events;
            (function (Events) {
                Events["RefreshModules"] = "RefreshModules";
            })(Events = Overview.Events || (Overview.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static refreshModulesPublish(args) {
                    this.current.publish(Events.RefreshModules, args);
                }
                static refreshModulesSubscribe(handler) {
                    return this.current.subscribe(Events.RefreshModules, handler);
                }
            }
            Overview.EventsHub = EventsHub;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewHeader extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get filterCallback() {
                    return this.state.get("filter", () => { });
                }
                get gridButton() {
                    return this.node.find("button[data-command=grid]");
                }
                get listButton() {
                    return this.node.find("button[data-command=list]");
                }
                get toggleCallback() {
                    return this.state.get("toggle", () => { });
                }
                template() {
                    return `<div class="-pdjs-manage-overview-module-header">
                        <div role="button">
                            <button data-command="grid" title="Switch to Tile View">
                                <i class="icofont-table"></i>
                            </button>
                        </div>
                        <div role="button">
                            <button data-command="list" title="Switch to List View">
                                <i class="icofont-listing-box"></i>
                            </button>
                        </div>
                        <div></div>
                        <div role="filter"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.gridButton.on(Jade.BrowserEvent.CLICK, _.bind(this.gridButton_onClick, this));
                    this.listButton.on(Jade.BrowserEvent.CLICK, _.bind(this.listButton_onClick, this));
                    this.filter_init();
                }
                filter_init() {
                    this.m_filter = new PDJS.Shared.UI.Controls.SearchBox({
                        insertAt: "div[role=filter]",
                        defaultMaskText: "Find module",
                        onSearch: (e) => {
                            this.filterCallback(e.term);
                        }
                    });
                    this.controls.add(this.m_filter);
                    this.m_filter.node.css({ position: "relative", width: "200px" });
                }
                gridButton_onClick(e) {
                    this.node.find(".-pdjs-selected")
                        .removeClass("-pdjs-selected");
                    this.gridButton.addClass("-pdjs-selected");
                    this.toggleCallback("tiles");
                }
                listButton_onClick(e) {
                    this.node.find(".-pdjs-selected")
                        .removeClass("-pdjs-selected");
                    this.listButton.addClass("-pdjs-selected");
                    this.toggleCallback("list");
                }
            }
            Overview.OverviewHeader = OverviewHeader;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewListGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get groupsData() {
                    return this.state.get("groupsData", []);
                }
                get footerNode() {
                    return this.node.children("div[role=foot]");
                }
                hide() {
                    this.node.css({
                        display: "none"
                    });
                }
                show() {
                    this.node.css({
                        display: "grid"
                    });
                    this.m_grid.redraw();
                }
                filter(term) {
                    this.removeFilter();
                    if (Jade.String.isNullOrWhiteSpace(term)) {
                        return;
                    }
                    this.addFilter(term);
                }
                template() {
                    return `<div class="-pdjs-manage-overview-module-list-grid">
                        <div role="grid"></div>
                        <div role="foot"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: `[id=${this.ID}] [role=grid]`,
                        pk: "id",
                        resizable: true,
                        sortable: true,
                        messaging: {
                            noRecordsMessage: `No modules match the search term.`
                        },
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            storeAsLocalVariable: true,
                            data: this.getGridData()
                        },
                        change: (e) => {
                            this.footerNode.empty();
                            this.footerNode.html(`<b>${e.selection.label}</b><br/>${e.selection.description || ""}`);
                        },
                        dblclick: function (e) {
                            window.location.hash = "/module/" + e.selection.id;
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                field: "icon",
                                iconDirectory: "~/Areas/Shared/Assets/Internal/Icons/16x16/"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "label",
                                title: "Module",
                                width: "200px",
                                attributes: {
                                    style: "font-weight:bold;"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "area",
                                title: "Area",
                                width: "200px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
                removeFilter() {
                    this.m_grid.get_dataSource().data([]);
                    this.m_grid.get_dataSource().data(this.getGridData());
                }
                addFilter(term) {
                    this.m_grid.get_dataSource().data([]);
                    this.m_grid.get_dataSource().data(this.getGridData(term));
                }
                getGridData(filterTerm = null) {
                    var result = [];
                    filterTerm = filterTerm === null || filterTerm === void 0 ? void 0 : filterTerm.toLowerCase();
                    this.groupsData.forEach(group => {
                        group.tiles.forEach(tile => {
                            if (filterTerm == null || tile.label.toLowerCase().indexOf(filterTerm) > -1) {
                                result.push({
                                    id: _.first(tile.moduleScripts).id,
                                    area: group.name,
                                    label: tile.label,
                                    icon: tile.icon,
                                    description: tile.description
                                });
                            }
                        });
                    });
                    return result;
                }
            }
            Overview.OverviewListGrid = OverviewListGrid;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                refresh() {
                    let service = new PDJS.Services.Overview.OverviewService();
                    service.index({
                        success: (e) => {
                            let data = [];
                            e.data.forEach(group => {
                                data = data.concat(group.tiles);
                            });
                            Overview.EventsHub.refreshModulesPublish({ data: data });
                        }
                    });
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-overview">
                        <div role="head"></div>
                        <div role="body"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.module_init();
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    if (this.m_allowRefresh) {
                        this.refresh();
                    }
                    this.m_allowRefresh = true;
                }
                grid_init(groups) {
                    if (this.m_grid != null) {
                        return;
                    }
                    this.m_grid = new Overview.OverviewListGrid({
                        insertAt: "div[role=body]",
                        groupsData: groups
                    });
                    this.controls.add(this.m_grid);
                }
                head_init() {
                    if (this.m_head != null) {
                        return;
                    }
                    this.m_head = new Overview.OverviewHeader({
                        insertAt: "div[role=head]",
                        filter: (term) => {
                            this.m_tiles.filter(term);
                            this.m_grid.filter(term);
                        },
                        toggle: (type) => {
                            this.setViewType(type);
                        }
                    });
                    this.controls.add(this.m_head);
                }
                tiles_init(groups) {
                    if (this.m_tiles != null) {
                        this.m_tiles.destroy();
                    }
                    this.m_tiles = new Overview.OverviewTileGrid({
                        insertAt: "div[role=body]",
                        groupsData: groups
                    });
                    this.controls.add(this.m_tiles);
                }
                module_init() {
                    this.m_allowRefresh = false;
                    let service = new PDJS.Services.Overview.OverviewService();
                    service.index({
                        success: (e) => {
                            this.head_init();
                            this.grid_init(e.data);
                            this.tiles_init(e.data);
                            this.setViewType("tiles");
                        }
                    });
                }
                setViewType(type) {
                    if (type == "tiles") {
                        this.m_tiles.show();
                        this.m_grid.hide();
                    }
                    if (type == "list") {
                        this.m_tiles.hide();
                        this.m_grid.show();
                    }
                }
            }
            Overview.OverviewModule = OverviewModule;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewTile extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_isVisible = true;
                }
                get selectCallback() {
                    return this.state.get("select", () => { });
                }
                get notification() {
                    var _a;
                    return (_a = this.data.attributes) === null || _a === void 0 ? void 0 : _a.notify;
                }
                get notificationNode() {
                    return this.node.find(".-pdjs-manage-overview-module-tile-notifiction");
                }
                get tileId() {
                    return _.first(this.data.moduleScripts).id;
                }
                get data() {
                    return this.state.get("tile");
                }
                set data(value) {
                    this.state.set("tile", value);
                }
                get icon() {
                    return this.data.icon;
                }
                get label() {
                    return this.data.label;
                }
                get description() {
                    return this.data.description;
                }
                get selected() {
                    return this.node.hasClass("-pdjs-selected");
                }
                set selected(value) {
                    value ? this.node.addClass("-pdjs-selected") :
                        this.node.removeClass("-pdjs-selected");
                }
                get isVisible() {
                    return this.m_isVisible;
                }
                set isVisible(value) {
                    this.m_isVisible = value;
                }
                hide() {
                    this.node.hide();
                    this.m_isVisible = false;
                }
                show() {
                    this.node.show();
                    this.m_isVisible = true;
                }
                select() {
                    this.selectCallback(this);
                    this.selected = true;
                }
                filter(term) {
                }
                template() {
                    let iconPath = Jade.IconSet.get("pdv2")
                        .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x48);
                    let notifyPath = Jade.IconSet.get("pdv2")
                        .resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x24);
                    return `<a href="#/module/${this.tileId}" class="-pdjs-manage-overview-tile-grid-tile">
                        <div role="box">
                            <div role="icon">
                                <img src="${iconPath}"/>
                            </div>
                            <div role="label">
                                ${this.label}
                            </div>
                        </div>
                        <div class="-pdjs-manage-overview-module-tile-notifiction" style="display:none;">
                            <img src="${notifyPath}" />
                        </div>
                    </a>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    if (this.notification != null) {
                        this.notificationNode.show();
                    }
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.select();
                        e.preventDefault();
                    });
                    this.node.on(Jade.BrowserEvent.DOUBLECLICK, (e) => {
                        window.location.href = `#/module/${this.tileId}`;
                        return false;
                    });
                    this.notificationNode.on(Jade.BrowserEvent.CLICK, () => {
                        this.notification_onClick();
                    });
                    this.subscriptions.add(Overview.EventsHub.refreshModulesSubscribe((e) => {
                        let module = _.first(this.data.moduleScripts);
                        let match = e.data.find(tile => {
                            return _.first(tile.moduleScripts).id === module.id;
                        });
                        if (match != null) {
                            this.data = match;
                        }
                        this.onStateChanged();
                    }));
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.notification != null ?
                        this.notificationNode.show() :
                        this.notificationNode.hide();
                    this.data.visible ?
                        this.node.show() :
                        this.node.hide();
                }
                notification_onClick() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        allowClose: true,
                        title: `Notification | ${this.label}`,
                        message: this.notification
                    });
                }
            }
            Overview.OverviewTile = OverviewTile;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewTileGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get groupsData() {
                    return this.state.get("groupsData", []);
                }
                get groups() {
                    return this.controls.getByType(Overview.OverviewTileGroup).toArray();
                }
                get footerNode() {
                    return this.node.children("div[role=foot]");
                }
                hide() {
                    this.node.css({
                        display: "none"
                    });
                }
                show() {
                    this.node.css({
                        display: "grid"
                    });
                }
                filter(term) {
                    this.removeMessage();
                    this.removeTileFilter();
                    if (Jade.String.isNullOrWhiteSpace(term)) {
                        return;
                    }
                    this.addTileFilter(term);
                }
                template() {
                    return `<div class="-pdjs-manage-overview-module-tile-grid">
                        <div role="body" data-controls></div>
                        <div role="foot"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.groupsData.forEach(group => {
                        this.controls.add(new Overview.OverviewTileGroup({
                            group: group,
                            selectTile: (tile) => {
                                this.tile_onSelect(tile);
                            }
                        }));
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.selectFirstTileByDefault();
                }
                tile_onSelect(tile) {
                    this.groups.forEach(group => {
                        group.tiles.forEach(tile => {
                            tile.selected = false;
                        });
                    });
                    this.footerNode.empty();
                    this.footerNode.html(`<b>${tile.label}</b><br/>${tile.description}`);
                }
                selectFirstTileByDefault() {
                    let group = _.first(this.groups);
                    let tile = _.first(group.tiles);
                    tile.select();
                }
                removeTileFilter() {
                    this.groups.forEach(group => {
                        group.tiles.forEach(tile => {
                            tile.show();
                        });
                        group.show();
                    });
                }
                addTileFilter(term) {
                    term = term.toLowerCase();
                    this.groups.forEach(group => {
                        group.tiles.forEach(tile => {
                            tile.label.toLowerCase().indexOf(term) > -1 ?
                                tile.show() : tile.hide();
                        });
                        group.hasVisibleTiles() ?
                            group.show() : group.hide();
                    });
                    let hasResults = false;
                    this.groups.forEach(group => {
                        !hasResults ?
                            hasResults = group.hasVisibleTiles() : null;
                    });
                    if (!hasResults) {
                        this.addNoResultsMessage(term);
                    }
                }
                addNoResultsMessage(term) {
                    this.controls.add(new PDJS.Shared.UI.Controls.Message({
                        backgroundColor: "var(--visiv-theme-base-1-back-color",
                        message: `No modules match the search term.`
                    }));
                }
                removeMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                    }
                }
            }
            Overview.OverviewTileGrid = OverviewTileGrid;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Overview;
        (function (Overview) {
            class OverviewTileGroup extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get group() {
                    return this.state.get("group");
                }
                get tiles() {
                    return this.controls.getByType(Overview.OverviewTile).toArray();
                }
                get selectTileCallback() {
                    return this.state.get("selectTile", () => { });
                }
                filter(term) {
                }
                hasVisibleTiles() {
                    return this.tiles.filter(tile => tile.isVisible).length > 0;
                }
                hide() {
                    this.node.hide();
                }
                show() {
                    this.node.show();
                }
                template() {
                    return `<div class="-pdjs-manage-overview-module-tile-grid-group">
                        <div role="label">${this.group.name}</div>
                        <div role="tiles" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.group.tiles.forEach(tile => {
                        this.controls.add(new Overview.OverviewTile({
                            tile: tile,
                            select: (tile) => {
                                this.selectTileCallback(tile);
                            }
                        }));
                    });
                }
            }
            Overview.OverviewTileGroup = OverviewTileGroup;
        })(Overview = Manage.Overview || (Manage.Overview = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get pluginId() {
                    return this.state.get("pluginId");
                }
                set pluginId(value) {
                    this.state.set("pluginId", value);
                }
                load(pluginId) {
                    this.pluginId = pluginId;
                }
                template() {
                    return `<div class="-pdjs-manage-plugins-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Links"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Placeholder Link",
                        click: (e) => {
                            Jade.UI.Dialogs.MessageDialog.open({
                                message: "Not Implemented"
                            });
                        }
                    }));
                }
            }
            Plugins.PluginsActions = PluginsActions;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/plugins": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Plugins.PluginsCommand = PluginsCommand;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class OpenPluginCommand extends Plugins.PluginsCommand {
                get plugin() {
                    return _.first(this.selections);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "plugin/open",
                        label: "Open",
                        icon: "folder_into.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Open the configuration page for the selected plugin.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    if (!this.plugin.installed) {
                        this.showPluginNotInstalledDialog();
                        return;
                    }
                    let route = `#/plugin/${this.plugin.customId}`;
                    let type = PDJS.Manage.Modules.instance.types.findByRoute(route);
                    if (type != null) {
                        window.location.hash = `#/plugin/${this.plugin.customId}`;
                    }
                    else {
                        this.showPluginHasNoModuleDialog();
                    }
                }
                showPluginNotInstalledDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: "Plugin Not Installed",
                        message: `The "${this.plugin.name}" plugin is no longer installed.`
                    });
                }
                showPluginHasNoModuleDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: "Plugin Has No Module",
                        message: `The "${this.plugin.name}" plugin has no module.`
                    });
                }
            }
            Plugins.OpenPluginCommand = OpenPluginCommand;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/plugins");
                }
                registerCommands(e) {
                    e.commands.add(new Plugins.OpenPluginCommand({}));
                }
            }
            Plugins.PluginsCommands = PluginsCommands;
            Jade.CommandGroups.add(PluginsCommands);
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-plugins-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Plugins</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Plugins.PluginsToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No plugins."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name,
                                    customId: e.CustomID,
                                    installed: e.Installed
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/plugins:plugin/open");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Plugins.PluginsGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Plugins.PluginsGrid = PluginsGrid;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/plugins";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:plugin/open`
                    }));
                }
            }
            Plugins.PluginsGridContextMenu = PluginsGridContextMenu;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-plugins">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Plugins.PluginsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Plugins.PluginsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Plugins.PluginsService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/plugins": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Plugins.PluginsModule = PluginsModule;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Plugins;
        (function (Plugins) {
            class PluginsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/plugins";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:plugin/open`
                    }));
                }
            }
            Plugins.PluginsToolbar = PluginsToolbar;
        })(Plugins = Manage.Plugins || (Manage.Plugins = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            let CssClass;
            (function (CssClass) {
                CssClass["ProcessModule"] = "-pdjs-manage-module-process";
                CssClass["ProcessesModule"] = "-pdjs-manage-module-processes";
                CssClass["ProcessExplorer"] = "-pdjs-manage-module-process-explorer";
                CssClass["ProcessActions"] = "-pdjs-manage-module-process-actions";
                CssClass["ProcessEditor"] = "-pdjs-manage-module-process-editor";
                CssClass["ProcessNode"] = "-pdjs-manage-process-node";
                CssClass["ProcessTree"] = "-pdjs-manage-process-tree";
                CssClass["ProcessesModuleGrid"] = "-pdjs-manage-module-processes-grid";
            })(CssClass = Process.CssClass || (Process.CssClass = {}));
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            let Events;
            (function (Events) {
                Events["ProcessRenamed"] = "process/renamed";
            })(Events = Process.Events || (Process.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static processRenamedPublish(args) {
                    this.global.publish(Events.ProcessRenamed, args);
                }
                static processRenamedSubscribe(handler) {
                    return this.global.subscribe(Events.ProcessRenamed, handler);
                }
            }
            Process.EventsHub = EventsHub;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessActions extends PDJS.Shared.UI.Controls.PanelMenu {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return this.state.get("processId", null);
                }
                template() {
                    return `<div class="${Process.CssClass.ProcessActions} ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Process Status"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Manage Status List...",
                        click: (e) => {
                            PDJS.Manage.Process.ProcessStatusDialog.open({
                                processId: this.processId
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Tag...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewTagDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tags",
                        label: "Manage Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Expression...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewExpressionDialog.open({
                                callbacks: {
                                    ok: () => { }
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tag-expressions",
                        label: "Manage Expressions"
                    }));
                }
            }
            Process.ProcessActions = ProcessActions;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessCommandBase extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$editor", null);
                    this.state.set("$explorer", null);
                    this.state.set("$module", null);
                    this.state.set("$targetNodeId", null);
                }
                get nodes() {
                    return this.explorer.processNodeTree;
                }
                get explorer() {
                    return this.state.get("$explorer");
                }
                get editor() {
                    return this.state.get("$editor");
                }
                get module() {
                    return this.state.get("$module");
                }
                get selectedNode() {
                    var _a;
                    return this.contextMenuNode || ((_a = this.explorer) === null || _a === void 0 ? void 0 : _a.selectedProcessNode);
                }
                get contextMenuNode() {
                    this.ensureContextMenuNode();
                    return this.m_contextMenuNode;
                }
                get contextMenuNodeId() {
                    return this.state.get("$targetNodeId");
                }
                get discriminatorId() {
                    return this.contextMenuNodeId == null ? undefined : "context-menu";
                }
                commit() {
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/process": {
                            $editor: this.editor,
                            $explorer: this.explorer,
                            $module: this.module,
                            $targetNodeId: this.contextMenuNodeId
                        }
                    }, { force: true, discriminatorId: this.discriminatorId });
                }
                ensureContextMenuNode() {
                    this.m_contextMenuNode = null;
                    if (this.contextMenuNodeId != null) {
                        this.m_contextMenuNode =
                            this.nodes.getNode(this.contextMenuNodeId);
                    }
                }
            }
            Process.ProcessCommandBase = ProcessCommandBase;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class AddNodeCommand extends Process.ProcessCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selectedNode != null;
                    if (this.selectedNode != null) {
                        this.updateIconAndText();
                    }
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.module.monitor.go({
                        directive: () => {
                            switch (this.selectedNode.type) {
                                case "process":
                                    this.addKey();
                                    break;
                                case "key":
                                    this.addStage();
                                    break;
                                case "stage":
                                    this.addDecision();
                                    break;
                                case "decision":
                                    this.addDecision();
                                    break;
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/add",
                        tooltip: "Add",
                        label: "Add",
                        icon: "add.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                updateIconAndText() {
                    switch (this.selectedNode.type) {
                        case "process":
                            this.label = "Add Key";
                            this.tooltip = "Add a new key to the process.";
                            this.icon = "box_white_surprise.png";
                            break;
                        case "key":
                            this.label = "Add Stage";
                            this.tooltip = "Add a new stage to the selected key.";
                            this.icon = "gear.png";
                            break;
                        case "stage":
                            this.label = "Add Decision";
                            this.tooltip = "Add a new decision to the selected stage.";
                            this.icon = "breakpoint.png";
                            break;
                        case "decision":
                            this.label = "Add Decision";
                            this.tooltip = "Add a new decision to the parent stage of the selected decision.";
                            this.icon = "breakpoint.png";
                    }
                }
                addKey() {
                    this.addNode({
                        node: {
                            type: "key",
                            name: "New Key",
                            icon: "box_white_surprise.png",
                            parentId: this.selectedNode.objectId
                        }
                    });
                }
                addStage() {
                    this.addNode({
                        node: {
                            type: "stage",
                            name: "New Stage",
                            icon: "gear.png",
                            parentId: this.selectedNode.objectId
                        }
                    });
                }
                addDecision() {
                    let parent = this.selectedNode.type == "decision" ?
                        this.selectedNode.parent :
                        this.selectedNode;
                    this.addNode({
                        node: {
                            type: "decision",
                            name: "New Decision",
                            icon: "breakpoint.png",
                            parentId: parent.objectId
                        },
                        parent: parent
                    });
                }
                addNode(args) {
                    this.enabled = false;
                    let service = new PDJS.Services.Manage.Process.ProcessNodeService();
                    service.addNode({
                        node: args.node,
                        success: (e) => {
                            this.addNodeSuccess(_.extend(args, { node: e.data }));
                        },
                        complete: (e) => {
                            this.enabled = true;
                            this.setCommandState();
                        }
                    });
                }
                addNodeSuccess(args) {
                    let node = new PDJS.Core.Process.ProcessNode(args.node);
                    let parent = args.parent || this.selectedNode;
                    parent.nodes.add(node);
                    this.explorer.tree.addNode({
                        node: node.toJSON(),
                        parent: parent
                    });
                    this.setCommandState();
                }
            }
            Process.AddNodeCommand = AddNodeCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DeleteNodeCommand extends Process.ProcessCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled =
                        this.selectedNode != null &&
                            this.selectedNode.type != "process";
                }
                onExecute(e) {
                    super.onExecute(e);
                    let message = this.selectedNode.nodes.count == 0 ?
                        `Delete the "${this.selectedNode.name}" ${this.selectedNode.type}?` :
                        `Delete the "${this.selectedNode.name}" ${this.selectedNode.type} and all its children?`;
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: `Delete | Node`,
                        message: message,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.deleteNode();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/delete",
                        tooltip: "Delete the selected key, stage, or decision.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                deleteNode() {
                    this.enabled = false;
                    let service = new PDJS.Services.Manage.Process.ProcessNodeService();
                    service.deleteNode({
                        node: this.selectedNode.toJSON(),
                        success: (e) => {
                            this.deleteNodeSuccess();
                        },
                        complete: (e) => {
                            this.enabled = true;
                            this.setCommandState();
                        }
                    });
                }
                deleteNodeSuccess() {
                    let node = this.selectedNode;
                    this.selectedNode.remove();
                    this.explorer.tree.removeNode(node);
                    this.setCommandState();
                }
            }
            Process.DeleteNodeCommand = DeleteNodeCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            const PROCESS_NODE = "ProspectDirector.Services.Processes.ProcessDTO";
            class SaveNodeCommand extends Process.ProcessCommandBase {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    let module = PDJS.Manage.Modules.instance.current;
                    this.editor.commit({
                        success: (e) => {
                            this.updateNode(e.target);
                            if (e.target.type === PROCESS_NODE) {
                                Process.EventsHub.processRenamedPublish({
                                    processId: e.target.id,
                                    processName: e.target.name
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/save",
                        tooltip: "Save changes made to the selected key, stage, or decision.",
                        label: "Save",
                        icon: "floppy_disk.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                updateNode(target) {
                    this.selectedNode.name = target.name;
                    if (this.selectedNode.type != "process") {
                        this.selectedNode.icon = target.icon;
                    }
                    this.explorer.tree.applyTemplate(this.selectedNode.id);
                }
            }
            Process.SaveNodeCommand = SaveNodeCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            let DropType;
            (function (DropType) {
                DropType["over"] = "over";
                DropType["before"] = "before";
                DropType["after"] = "after";
            })(DropType || (DropType = {}));
            class MoveNodeCommand extends Process.ProcessCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selectedNode != null;
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.moveNode(e);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/move",
                        tooltip: "Move",
                        label: "Move",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                moveNode(args) {
                    let service = new PDJS.Services.Manage.Process.ProcessNodeService();
                    service.moveNode({
                        srcId: args.srcNodeId,
                        dstId: args.dstNodeId,
                        dropType: this.getDropTypeInteger(args.dropType),
                        success: (e) => {
                            this.moveNodeSuccess(args);
                        },
                        complete: (e) => {
                            this.setCommandState();
                        }
                    });
                }
                moveNodeSuccess(e) {
                }
                getDropTypeInteger(dropType) {
                    switch (dropType) {
                        case "over":
                            return 0;
                        case "before":
                            return 1;
                        case "after":
                            return 2;
                    }
                }
            }
            Process.MoveNodeCommand = MoveNodeCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/process");
                }
                registerCommands(e) {
                    e.commands.add(new Process.AddNodeCommand());
                    e.commands.add(new Process.DeleteNodeCommand());
                    e.commands.add(new Process.SaveNodeCommand());
                    e.commands.add(new Process.MoveNodeCommand());
                }
            }
            Process.ProcessCommands = ProcessCommands;
            Jade.CommandGroups.add(ProcessCommands);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get processNode() {
                    return this.m_processNode;
                }
                set processNode(value) {
                    this.m_processNode = value;
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get onCommitCallback() {
                    return this.state.get("onCommit", () => { });
                }
                template() {
                    return `<div class="${Process.CssClass.ProcessEditor}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Settings</div>
                        <div role="menu"></div>
                        <div data-controls></div>
                    </div>`;
                }
                load(node) {
                    this.processNode = node;
                    switch (node.type) {
                        case "process":
                            this.process_load();
                            break;
                        case "key":
                            this.key_load();
                            break;
                        case "stage":
                            this.stage_load();
                            break;
                        case "decision":
                            this.decision_load();
                            break;
                    }
                }
                commit(args = {}) {
                    let successFunction = (args.success || (() => { }));
                    let wrappedFunction = (e) => {
                        successFunction(e);
                        this.onCommitCallback();
                    };
                    args.success = wrappedFunction;
                    this.m_editor.commit(args);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                    this.menu_init();
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Features.FeatureEditor({
                        onFeatureValueChanged: (e) => {
                            this.onChangeCallback();
                        },
                        onCommitSuccess: (e) => {
                            PDJS.Shared
                                .MessageStack
                                .instance
                                .success("Changes Saved");
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Process.ProcessEditorToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                process_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.processNode.objectId,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessUIO",
                            type: "ProspectDirector.Web.Manage.Modules.Process.ProcessArbiter"
                        },
                        initialized: false
                    });
                }
                key_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.processNode.objectId,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessKeyUIO",
                            type: "ProspectDirector.Web.Manage.Modules.Process.ProcessKeyArbiter"
                        },
                        initialized: false
                    });
                }
                stage_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.processNode.objectId,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessStageUIO",
                            type: "ProspectDirector.Web.Manage.Modules.Process.ProcessStageArbiter"
                        },
                        initialized: false
                    });
                }
                decision_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.processNode.objectId,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessDecisionUIO",
                            type: "ProspectDirector.Web.Manage.Modules.Process.ProcessDecisionArbiter"
                        },
                        initialized: false
                    });
                }
            }
            Process.ProcessEditor = ProcessEditor;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/process:node/save"
                    }));
                }
            }
            Process.ProcessEditorToolbar = ProcessEditorToolbar;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessExplorer extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get processId() {
                    return this.state.get("processId");
                }
                get selectedProcessNode() {
                    var _a;
                    return (_a = this.m_tree) === null || _a === void 0 ? void 0 : _a.selectedProcessNode;
                }
                get processNodeTree() {
                    return this.m_processNodeTree;
                }
                set processNodeTree(value) {
                    this.m_processNodeTree = value;
                }
                get tree() {
                    return this.m_tree;
                }
                template() {
                    return `<div class="${Process.CssClass.ProcessExplorer} ${Manage.CssClass.NavigationPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Process Model</div>
                        <div role="menu"></div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.tree_init();
                    this.data_init();
                }
                data_init() {
                    let service = new PDJS.Services.Process.ProcessService();
                    service.getTree({
                        processId: this.processId,
                        success: (e) => {
                            this.processNodeTree =
                                new PDJS.Core.Process.ProcessNodeTree({
                                    node: e.data
                                });
                            this.m_tree.load(this.processNodeTree);
                        }
                    });
                }
                tree_init() {
                    this.m_tree = new Process.ProcessTree({
                        processId: this.processId,
                        onChange: (e) => {
                            this.onChangeCallback(e);
                        }
                    });
                    this.controls.add(this.m_tree);
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Process.ProcessExplorerToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
            }
            Process.ProcessExplorer = ProcessExplorer;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessExplorerContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = Jade.CommandPath
                        .buildGroup("pdjs/manage/process", "context-menu");
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:node/add`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:node/delete`
                    }));
                }
                onOpen(e) {
                    super.onOpen(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/process": {
                            $targetNodeId: Process.ProcessNodeHelper.getData(e.target, "id")
                        }
                    }, { force: true, discriminatorId: "context-menu" });
                }
            }
            Process.ProcessExplorerContextMenu = ProcessExplorerContextMenu;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessExplorerToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/process";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:node/add`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:node/delete`
                    }));
                }
            }
            Process.ProcessExplorerToolbar = ProcessExplorerToolbar;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return parseInt(this.settings.targetId);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} ${Process.CssClass.ProcessModule}">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                            <div data-id="pane-3"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.addSubscribers();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                onModuleLoad(e) {
                    super.onModuleLoad(e);
                    e.addStep(() => this.module_init());
                }
                actions_init() {
                    this.m_actions = new Process.ProcessActions({
                        insertAt: "div[data-id=pane-3]",
                        processId: this.processId
                    });
                    this.controls.add(this.m_actions);
                }
                addSubscribers() {
                    this.subscriptions.add(Process.EventsHub.processRenamedSubscribe(e => {
                        if (this.settings.targetId == e.processId.toString()) {
                            this.settings.label = e.processName;
                        }
                    }));
                }
                explorer_init() {
                    this.m_explorer = new Process.ProcessExplorer({
                        insertAt: "div[data-id=pane-1]",
                        processId: this.processId,
                        onChange: (e) => {
                            this.setCommandState();
                            this.m_editor.load(this.m_explorer.selectedProcessNode);
                        }
                    });
                    this.controls.add(this.m_explorer);
                }
                editor_init() {
                    this.m_editor = new Process.ProcessEditor({
                        insertAt: "div[data-id=pane-2]",
                        processId: this.processId,
                        onCommit: () => {
                            this.settings.hasChanges = false;
                        },
                        onChange: () => {
                            this.settings.hasChanges = true;
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                module_init() {
                    return this.modulePromise((resolve, reject) => {
                        let service = new PDJS.Services.Process.ProcessService();
                        service.index({
                            processId: parseInt(this.settings.targetId),
                            success: (e) => {
                                this.editor_init();
                                this.explorer_init();
                                this.setCommandState();
                                this.settings.label = e.data.processName;
                                resolve();
                            },
                            error: (e) => { reject(e); }
                        });
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "300px" },
                            { resizable: true },
                            { resizable: true, size: "300px" }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    [undefined, "context-menu"].forEach(id => {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/process": {
                                $editor: this.m_editor,
                                $explorer: this.m_explorer,
                                $module: this
                            }
                        }, { force: true, discriminatorId: id });
                    });
                }
            }
            Process.ProcessModule = ProcessModule;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessNodeHelper {
                static getData(node, id, defaultValue = null) {
                    return $(node).find(`.${PDJS.Core.Process.CssClass.ProcessNode}`).data(id) || defaultValue;
                }
            }
            Process.ProcessNodeHelper = ProcessNodeHelper;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessStatusCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                    this.state.set("processId", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get processId() {
                    return this.state.get("processId");
                }
                commit() {
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/process/status": {
                            $grid: this.grid,
                            processId: this.processId
                        }
                    }, { force: true });
                }
            }
            Process.ProcessStatusCommand = ProcessStatusCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class AddStatusCommand extends Process.ProcessStatusCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Process Status",
                        height: 460,
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessStatusUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessStatusArbiter",
                            properties: {
                                processId: this.processId
                            }
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.grid.items.add(new PDJS.Core.Process.ProcessStatus(e.target));
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                                this.setCommandState();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "status/add",
                        tooltip: "Add",
                        label: "Add",
                        icon: "add.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Process.AddStatusCommand = AddStatusCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DeleteStatusCommand extends Process.ProcessStatusCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.grid.selections.count > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.confirmDeletion();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "status/delete",
                        tooltip: "Delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                deleteStatus() {
                    let id = this.grid.selections.first().id;
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.DELETE,
                        url: Jade.Path.resolve("~/manage/processstatus/delete"),
                        data: {
                            id: id
                        },
                        success: (e) => {
                            let status = this.grid.items.getById(id);
                            if (status) {
                                this.grid.items.remove(status);
                                this.grid.refresh({ clear: true });
                                this.setCommandState();
                            }
                        }
                    });
                }
                confirmDeletion() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Process Status",
                        message: "Delete the selected process status?",
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.deleteStatus();
                            }
                        }
                    });
                }
            }
            Process.DeleteStatusCommand = DeleteStatusCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class EditStatusCommand extends Process.ProcessStatusCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.grid.selections.count == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "Edit | Process Status",
                        height: 460,
                        args: {
                            targetId: this.grid.selections.first().id,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessStatusUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessStatusArbiter",
                            properties: {
                                processId: this.processId
                            }
                        },
                        select: {
                            "ok": (sender, e) => {
                                let status = this.grid.items.getById(e.target.id);
                                if (status) {
                                    status.update(e.target);
                                    this.grid.refresh();
                                }
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "status/edit",
                        tooltip: "Edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Process.EditStatusCommand = EditStatusCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessStatusCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/process/status");
                }
                registerCommands(e) {
                    e.commands.add(new Process.AddStatusCommand());
                    e.commands.add(new Process.DeleteStatusCommand());
                    e.commands.add(new Process.EditStatusCommand());
                }
            }
            Process.ProcessStatusCommands = ProcessStatusCommands;
            Jade.CommandGroups.add(ProcessStatusCommands);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessStatusDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get closeButtonNode() {
                    return this.node.find("button[data-command=close]");
                }
                get processId() {
                    return this.state.get("processId", null);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.toolbar_init();
                    this.grid_init();
                    this.closeButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-process-status-dialog">
                    <div role="text">
                        Create and manage here all of the possible status which may be assigned during execution of the process. 
                        Assign a status in the list to an entity, by selecting the status in "Assign Status" property of a decision.
                    </div>
                    <div role="toolbar"></div>
                    <div role="grid"></div>
                    <div role="deck">
                        <button data-command="close" class="-jadeui-dialog-button">Close</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Manage | Status List",
                        height: 400,
                        width: 600
                    };
                }
                grid_init() {
                    this.m_grid = new Process.ProcessStatusGrid({
                        insertAt: "div[role=grid]",
                        processId: this.processId,
                        change: (selections) => {
                            this.setCommandState();
                        },
                        dblClick: (selections) => {
                            this.setCommandState();
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/process/status:status/edit");
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Process.ProcessStatusToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/process/status": {
                            $grid: this.m_grid,
                            processId: this.processId
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new ProcessStatusDialog(options);
                }
            }
            Process.ProcessStatusDialog = ProcessStatusDialog;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessStatusGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return this.state.get("processId");
                }
                get dataSource() {
                    return this.grid.get_dataSource();
                }
                get grid() {
                    return this.m_grid;
                }
                get gridNode() {
                    return this.node.children("div[role=grid]");
                }
                get items() {
                    return this.m_items;
                }
                set items(value) {
                    this.m_items = value;
                }
                get selections() {
                    return this.getSelections();
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get dblClickCallback() {
                    return this.state.get("dblClick", () => { });
                }
                refresh(options) {
                    let data = this.items.toJSON();
                    data.sort((item1, item2) => {
                        if (item1.name < item2.name) {
                            return -1;
                        }
                        ;
                        if (item1.name > item2.name) {
                            return 1;
                        }
                        ;
                        return 0;
                    });
                    this.dataSource.data([]);
                    this.dataSource.data(data);
                    this.grid.refresh(options);
                }
                template() {
                    return `<div class="-pdjs-manage-process-status-grid">
                        <div role="grid"></div>
                    <div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.data_init();
                }
                data_init() {
                    let service = new PDJS.Services.Process.ProcessService();
                    service.getStatusList({
                        processId: this.processId,
                        success: (e) => {
                            this.items = new PDJS.Core.Process.ProcessStatusCollection(e.data);
                            this.refresh();
                        }
                    });
                }
                grid_init() {
                    this.items = new PDJS.Core.Process.ProcessStatusCollection([]);
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.gridNode,
                        pk: "id",
                        dataSource: {
                            data: this.items.toArray(),
                            storeAsLocalVariable: true
                        },
                        selectionMode: "single",
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                title: "ID",
                                field: "id",
                                width: 250,
                                hidden: true
                            }),
                            new PD.Web.UI.Controls.GridIconColumn({
                                title: "&nbsp",
                                field: "icon",
                                width: 25
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Name",
                                field: "name",
                                width: 250
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Custom ID",
                                field: "customId",
                                width: 250
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ],
                        messaging: {
                            noRecordsMessage: "No status items exist."
                        },
                        dblclick: (e) => {
                            if (this.m_grid) {
                                this.dblClickCallback(this.selections);
                            }
                        },
                        change: (e) => {
                            if (this.m_grid) {
                                this.changeCallback(this.selections);
                            }
                        }
                    });
                }
                getSelections() {
                    let result = new PDJS.Core.Process.ProcessStatusCollection([]);
                    let selectedIds = this.grid
                        .getSelections()
                        .toArray()
                        .map(item => {
                        return item.id;
                    });
                    this.items.each(item => {
                        if (selectedIds.indexOf(item.id) > -1) {
                            result.add(item);
                        }
                    });
                    return result;
                }
            }
            Process.ProcessStatusGrid = ProcessStatusGrid;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessStatusToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/process/status:status/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/process/status:status/edit"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/process/status:status/delete"
                    }));
                }
            }
            Process.ProcessStatusToolbar = ProcessStatusToolbar;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionStageComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                constructor(options) {
                    super(options);
                    this.tabIndex = 0;
                }
                get selection() {
                    return super.selection;
                }
                set selection(value) {
                    super.selection = value;
                }
                setSelection(item) {
                    this.selection = item;
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                onSelectionChange(selection) {
                    super.onSelectionChange(selection);
                    if (selection != null) {
                        this.iconValue = selection.icon;
                        this.maskValue = selection.name;
                        this.icon.title = selection.name;
                    }
                    else {
                        this.iconValue = "sign_forbidden.png";
                        this.maskValue = "Don't Move";
                    }
                }
                createListItem(data) {
                    return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                        data: data,
                        labelMap: "name"
                    });
                }
            }
            Process.DecisionStageComboBox = DecisionStageComboBox;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionStageEditor extends FeatureBlendJS.Views.MicroEditorBase {
                get processId() {
                    return this.source.getFeatureValue("processId");
                }
                get moveToList() {
                    return this.source.getFeatureValue("moveToList");
                }
                get moveToIcon() {
                    return this.source.getFeatureValue("moveToIcon");
                }
                get moveToName() {
                    return this.source.getFeatureValue("moveToName");
                }
                get moveToId() {
                    return this.source.getFeatureValue("moveToId");
                }
                set moveToId(value) {
                    this.source.setFeatureValue("moveToId", value);
                }
                get selectNode() {
                    return this.node.find("select");
                }
                template() {
                    return `<div class="-pdjs-manage-process-decision-stage-editor"></div>`;
                }
                focus() {
                    super.focus();
                    this.node.find("select").focus();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                    if (this.moveToId) {
                        this.m_list.setSelection({
                            id: this.moveToId,
                            icon: this.moveToIcon,
                            name: this.moveToName
                        });
                    }
                }
                list_init() {
                    this.m_list = new Process.DecisionStageComboBox({
                        data: this.moveToList,
                        processId: this.processId,
                        mode: PDJS.Shared.UI.Controls.ComboBoxMode.List,
                        onSelectionChanged: (e) => {
                            var _a;
                            let value = (_a = this.m_list.selection) === null || _a === void 0 ? void 0 : _a.id;
                            this.moveToId = value;
                        }
                    });
                    this.controls.add(this.m_list);
                }
            }
            Process.DecisionStageEditor = DecisionStageEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Process.DecisionStageEditor", DecisionStageEditor);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionStatusComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                constructor(options) {
                    super(options);
                    this.tabIndex = 0;
                }
                get selection() {
                    return super.selection;
                }
                set selection(value) {
                    super.selection = value;
                }
                get processId() {
                    return this.state.get("processId");
                }
                setSelection(item) {
                    this.selection = item;
                }
                onSelectionChange(selection) {
                    super.onSelectionChange(selection);
                    if (selection != null) {
                        this.iconValue = selection.icon;
                        this.maskValue = selection.name;
                        this.icon.title = selection.name;
                    }
                    else {
                        this.iconValue = "flag_white.png";
                        this.maskValue = "Don't Change Status";
                    }
                }
                createListItem(data) {
                    return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                        data: data,
                        labelMap: "name"
                    });
                }
                onFilter(e) {
                    let service = new PDJS.Services.Process.ProcessStatusService();
                    service.list({
                        request: {
                            keyword: this.textValue,
                            processId: this.processId,
                        },
                        success: (e2) => {
                            e.result.addRange(e2.data);
                            e.complete();
                            let maxHeight = 240;
                            let fullHeight = e2.data.length * 24;
                            this.list.resize(maxHeight <= fullHeight ? maxHeight : fullHeight);
                        }
                    });
                }
                onShowDialog() {
                    Process.DecisionStatusEditorDialog.open({
                        processId: this.processId,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.selection = e.status;
                            }
                        }
                    });
                }
            }
            Process.DecisionStatusComboBox = DecisionStatusComboBox;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionStatusEditor extends FeatureBlendJS.Views.MicroEditorBase {
                get processId() {
                    return this.source.getFeatureValue("processId");
                }
                get statusIcon() {
                    return this.source.getFeatureValue("statusIcon");
                }
                get statusId() {
                    return this.source.getFeatureValue("statusId");
                }
                set statusId(value) {
                    this.source.setFeatureValue("statusId", value);
                }
                get statusName() {
                    return this.source.getFeatureValue("statusName");
                }
                get selectNode() {
                    return this.node.find("select");
                }
                template() {
                    return `<div class="-pdjs-manage-process-decision-status-editor"></div>`;
                }
                focus() {
                    super.focus();
                    this.node.find("select").focus();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                    if (this.statusId) {
                        this.m_list.setSelection({
                            id: this.statusId,
                            icon: this.statusIcon,
                            name: this.statusName
                        });
                    }
                }
                list_init() {
                    this.m_list = new Process.DecisionStatusComboBox({
                        data: [],
                        processId: this.processId,
                        mode: PDJS.Shared.UI.Controls.ComboBoxMode.PopUp,
                        onSelectionChanged: (e) => {
                            var _a;
                            this.statusId = (_a = this.m_list.selection) === null || _a === void 0 ? void 0 : _a.id;
                        }
                    });
                    this.controls.add(this.m_list);
                }
            }
            Process.DecisionStatusEditor = DecisionStatusEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Process.DecisionStatusEditor", DecisionStatusEditor);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionStatusEditorDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get processId() {
                    return this.state.get("processId", null);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.okAndClose();
                    });
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-process-decision-status-editor-dialog">
                    <div role="grid"></div>
                    <div role="deck">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Process Status",
                        height: 300,
                        width: 600
                    };
                }
                grid_init() {
                    this.m_grid = new Process.ProcessStatusGrid({
                        insertAt: "div[role=grid]",
                        processId: this.processId,
                        change: (selections) => {
                        },
                        dblClick: (selections) => {
                            this.okAndClose();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                okAndClose() {
                    let status = this.m_grid.selections.first();
                    if (status) {
                        this.close({
                            name: "ok",
                            data: {
                                status: status.toJSON()
                            }
                        });
                    }
                }
                static open(options) {
                    return new DecisionStatusEditorDialog(options);
                }
            }
            Process.DecisionStatusEditorDialog = DecisionStatusEditorDialog;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionEditorExtender extends FeatureBlendJS.Views.MicroEditorBase {
                    get expressionId() {
                        return this.source.getFeatureValue(this.idProperty);
                    }
                    set expressionId(value) {
                        this.source.setFeatureValue(this.idProperty, value);
                    }
                    get expressionName() {
                        return this.source.getFeatureValue(this.nameProperty);
                    }
                    set expressionName(value) {
                        this.source.setFeatureValue(this.nameProperty, value);
                    }
                    get idProperty() {
                        return _.camelCase(this.source.state.get("expressionIdProperty"));
                    }
                    get nameProperty() {
                        return _.camelCase(this.source.state.get("expressionNameProperty"));
                    }
                    get checkboxNode() {
                        return this.node.children("div[role=check]").children("input");
                    }
                    template() {
                        return `<div class="-pdjs-shared-feature-editors-expression-editor-extender">
                        <div role="input" data-controls></div>
                        <div role="label">
                            Use Expression
                        </div>
                        <div role="check">
                            <input type="checkbox"/>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.m_expression) {
                            this.m_expression.focus();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.expression_init();
                        this.input_init();
                        this.checkboxNode.on(Jade.BrowserEvent.CLICK, _.bind(this.checkbox_check, this));
                        this.toggleExpressionEditor(this.expressionId != null);
                        this.checkboxNode.prop("checked", this.expressionId != null);
                    }
                    createInput() {
                        return null;
                    }
                    expression_init() {
                        this.m_expression = new Editors.ExpressionEditorInput({
                            insertAt: "div[role=input]",
                            expressionId: this.expressionId,
                            expressionName: this.expressionName,
                            enabled: this.source.enabled,
                            readOnly: this.source.readOnly,
                            change: (e) => {
                                this.expressionId = e.expressionId;
                                this.expressionName = e.expressionName;
                            }
                        });
                        this.controls.add(this.m_expression);
                    }
                    input_init() {
                        this.m_input = this.createInput();
                        if (this.m_input) {
                            this.controls.add(this.m_input);
                        }
                    }
                    checkbox_check(e) {
                        this.toggleExpressionEditor(this.checkboxNode.is(":checked"));
                        this.m_expression.clear();
                    }
                    toggleExpressionEditor(showExpressionEditor) {
                        if (showExpressionEditor) {
                            this.m_expression.node.show();
                            this.m_expression.clearText();
                            this.m_input.node.hide();
                        }
                        else {
                            this.m_expression.node.hide();
                            this.m_expression.clear();
                            this.m_input.node.show();
                        }
                    }
                }
                Editors.ExpressionEditorExtender = ExpressionEditorExtender;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionOrListEditor extends Editors.ExpressionEditorExtender {
                    get listId() {
                        return _.camelCase(this.source.state.get("listIdProperty"));
                    }
                    get list() {
                        return this.source.getFeatureValue(this.listId, []);
                    }
                    get listItemIdProperty() {
                        return _.camelCase(this.source.state.get("listItemIdProperty"));
                    }
                    get listItemId() {
                        return this.source.getFeatureValue(this.listItemIdProperty);
                    }
                    set listItemId(value) {
                        this.source.setFeatureValue(this.listItemIdProperty, value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                    createInput() {
                        return new Editors.ExpressionOrListEditorSelect({
                            list: this.list,
                            value: this.listItemId,
                            change: (e) => {
                                this.listItemId = e;
                            }
                        });
                    }
                }
                Editors.ExpressionOrListEditor = ExpressionOrListEditor;
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ExpressionOrListEditor", ExpressionOrListEditor);
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionVisibilityEditor extends PDJS.Shared.Features.Editors.ExpressionOrListEditor {
                onActivate(e) {
                    super.onActivate(e);
                }
                createInput() {
                    return new Process.DecisionVisibilityInput({
                        value: false,
                        change: (e) => {
                        }
                    });
                }
            }
            Process.DecisionVisibilityEditor = DecisionVisibilityEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Process.DecisionVisibilityEditor", DecisionVisibilityEditor);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DecisionVisibilityInput extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get selectNode() {
                    return this.node.children("select");
                }
                get value() {
                    return this.state.get("value", false);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                template() {
                    return `<div class="-pdjs-manage-process-decision-vibility-input">
                        <select>
                            <option value="false">Everyone</option>
                            <option value="true">Administrators</option>
                        </select>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                        this.changeCallback(this.selectNode.val() == "true");
                    });
                    this.selectNode.val(this.value.toString());
                }
            }
            Process.DecisionVisibilityInput = DecisionVisibilityInput;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class HiddenFoldersEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get explorerModel() {
                    return this.m_explorerModel || new Process.ExplorerModel();
                }
                set explorerModel(value) {
                    this.m_explorerModel = value;
                }
                get hiddenNodeIds() {
                    return this.source.getFeatureValue("hiddenNodeIds", []);
                }
                set hiddenNodeIds(value) {
                    this.source.setFeatureValue("hiddenNodeIds", value);
                }
                template() {
                    return `<div class="-pdjs-manage-process-hidden-folders-editor">
                        <div role="text">Check the folders below that you wish to be hidden from end users when an entity is at any child stage within this key.</div>
                        <div role="tree"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                }
                onCommit() {
                    this.hiddenNodeIds = this.explorerModel.getCheckedNodes().map(node => {
                        return node.id;
                    });
                }
                tree_init() {
                    this.explorerModel = new Process.ExplorerModel({
                        nodes: this.source.getFeatureValue("nodes", [])
                    });
                    this.explorerModel.getAllNodes().forEach(node => {
                        node.checked = this.hiddenNodeIds.indexOf(node.id) > -1;
                    });
                    this.m_tree = new Process.HiddenFoldersTree({
                        insertAt: "div[role=tree]",
                        explorerModel: this.explorerModel
                    });
                    this.controls.add(this.m_tree);
                }
            }
            Process.HiddenFoldersEditor = HiddenFoldersEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Process.HiddenFoldersEditor", HiddenFoldersEditor);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class HiddenFoldersTree extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get explorerModel() {
                    return this.state.get("explorerModel");
                }
                get tree() {
                    return this.m_tree;
                }
                set tree(value) {
                    this.m_tree = value;
                }
                get treeNode() {
                    return this.node.children("div[role=tree]");
                }
                template() {
                    return `<div class="-pdjs-manage-process-hidden-folders-tree">
                        <div role="tree"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.data_init();
                }
                applyTemplate(folderId) {
                    var _a;
                    let folder = this.explorerModel.getNode(folderId);
                    if (folder == null) {
                        return;
                    }
                    let uid = (_a = this.tree.dataSource.get(folder.id)) === null || _a === void 0 ? void 0 : _a.uid;
                    let span = $(folder.toMarkup());
                    let node = this.tree.findByUid(uid);
                    let kin = node.find(".k-in").first();
                    kin.empty();
                    kin.html(span[0].outerHTML);
                    span.hide();
                }
                data_init() {
                    this.tree.dataSource.data(this.explorerModel.nodes.toJSON());
                }
                tree_init() {
                    this.tree = this.treeNode.kendoTreeView({
                        dataTextField: "name",
                        loadOnDemand: false,
                        dataSource: new kendo.data.HierarchicalDataSource({
                            data: this.explorerModel.toKendoJSON().nodes,
                            schema: {
                                model: {
                                    children: "nodes"
                                }
                            }
                        }),
                        checkboxes: true,
                        template: _.bind(this.tree_template, this),
                        select: _.bind(this.tree_select, this),
                        check: _.bind(this.tree_check, this)
                    }).data("kendoTreeView");
                }
                tree_template(e) {
                    if (this.explorerModel.nodes.count == 0) {
                        return;
                    }
                    let folder = this.explorerModel.getNode(e.item.id);
                    let result = folder != null ?
                        folder.toMarkup() : "render error";
                    return result;
                }
                tree_select(e) {
                    e.preventDefault();
                }
                tree_check(e) {
                    let data = this.tree.dataItem(e.node);
                    let folder = this.explorerModel.getNode(data.get("id"));
                    if (!folder) {
                        return;
                    }
                    folder.checked = data.get("checked");
                    this.applyTemplate(folder.id);
                }
            }
            Process.HiddenFoldersTree = HiddenFoldersTree;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ExplorerModel extends PDJS.Core.EntityTypes.ExplorerModel.ExplorerModel {
                constructor(options = {}) {
                    super(options);
                }
                toKendoJSON() {
                    return {
                        nodes: this.nodes.toKendoJSON()
                    };
                }
                getCheckedNodes() {
                    let result = [];
                    this.forEachNode((node) => {
                        if (node.checked) {
                            result.push(node);
                        }
                    });
                    return result;
                }
                createNodeCollection(nodes) {
                    return new Process.NodeCollection({
                        explorerModel: this,
                        parent: null,
                        nodes: nodes
                    });
                }
            }
            Process.ExplorerModel = ExplorerModel;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class Node extends PDJS.Core.EntityTypes.ExplorerModel.Node {
                constructor(options) {
                    super(options);
                }
                get checked() {
                    return this.state.get("checked");
                }
                set checked(value) {
                    this.state.set("checked", value);
                }
                toJSON() {
                    return _.extend({
                        nodes: this.nodes.toJSON()
                    }, this.state.toJSON());
                }
                toKendoJSON() {
                    return _.extend({
                        nodes: this.nodes.toJSON(),
                        hasChildren: this.nodes.count > 0
                    }, this.state.toJSON());
                }
                toMarkup() {
                    return `<div class="-pdjs-manage-process-node">
                        <div role="icon"><img src="${this.getIcon()}"/></div>
                        <div role="text">${this.name}</div>
                    </div>`;
                }
                createNodeCollection(nodes) {
                    return new Process.NodeCollection({
                        explorerModel: this.explorerModel,
                        nodes: nodes,
                        parent: this
                    });
                }
                getIcon() {
                    let icon = this.checked ?
                        "sign_forbidden.png" : this.icon;
                    let result = Jade.IconSet.get("pd")
                        .resolve(icon, Jade.IconSetSizeSpecificDirectory.x16);
                    return result;
                }
            }
            Process.Node = Node;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class NodeCollection extends PDJS.Core.EntityTypes.ExplorerModel.NodeCollection {
                constructor(options) {
                    super(options);
                }
                toKendoJSON() {
                    return this.transform((item) => {
                        return item.toKendoJSON();
                    });
                }
                createNode(data) {
                    return new Process.Node(data);
                }
            }
            Process.NodeCollection = NodeCollection;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            let CssSelectors;
            (function (CssSelectors) {
                CssSelectors["node"] = "li[data-uid]";
                CssSelectors["innerNode"] = "li[data-uid] span.k-in";
                CssSelectors["topMidBot"] = ".k-top, .k-mid, .k-bot";
            })(CssSelectors || (CssSelectors = {}));
            class ProcessTree extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return this.state.get("processId");
                }
                get tree() {
                    return this.m_tree;
                }
                get treeNode() {
                    return this.node.children("div[role=tree]");
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get processNodeTree() {
                    return this.m_processNodeTree;
                }
                set processNodeTree(value) {
                    this.m_processNodeTree = value;
                }
                get selectedProcessNode() {
                    return this.getSelectedProcessNode();
                }
                get selectedNode() {
                    return this.tree.select();
                }
                load(tree) {
                    this.processNodeTree = tree;
                    this.tree_init();
                    this.select(tree.node, true);
                    this.contextMenu_init();
                }
                select(processNode, expand = false) {
                    let node = this.getNodeById(processNode.id);
                    if (node.length > 0) {
                        this.tree.select(node);
                        if (expand) {
                            this.tree.expand(node);
                        }
                    }
                }
                template() {
                    return `<div class="${Process.CssClass.ProcessTree}">
                        <div role="tree"></div>
                    </div>`;
                }
                addNode(e) {
                    var _a;
                    let parentNode = this.getNodeById((_a = e.parent) === null || _a === void 0 ? void 0 : _a.id) ||
                        this.selectedNode;
                    let addedNode = this.tree.append(e.node, parentNode);
                    this.tree.expand(parentNode);
                    if (addedNode.length > 0) {
                        this.tree.select(addedNode);
                        addedNode.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                    }
                }
                removeNode(node) {
                    let removeNode = this.getNodeById(node.id);
                    let fallbackNode = null;
                    fallbackNode = removeNode.next(CssSelectors.node);
                    if (fallbackNode.length == 0) {
                        fallbackNode = removeNode.prev(CssSelectors.node);
                    }
                    if (fallbackNode.length == 0) {
                        fallbackNode = removeNode.parent().closest(CssSelectors.node);
                    }
                    this.tree.remove(removeNode);
                    if (fallbackNode.length > 0) {
                        this.tree.select(fallbackNode);
                        fallbackNode.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                    }
                }
                applyTemplate(processNodeId) {
                    var _a;
                    let processNode = this.processNodeTree.getNode(processNodeId);
                    if (processNode == null) {
                        return;
                    }
                    let uid = (_a = this.tree.dataSource.get(processNode.id)) === null || _a === void 0 ? void 0 : _a.uid;
                    let span = $(processNode.toMarkup());
                    let node = this.tree.findByUid(uid);
                    let kin = node.find(".k-in").first();
                    kin.empty();
                    kin.html(span[0].outerHTML);
                    span.hide();
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                contextMenu_init() {
                    if (this.m_treeContextMenu) {
                        return;
                    }
                    this.m_treeContextMenu =
                        new PDJS.Shared.UI.Controls.TreeViewContextMenu({
                            tree: this.tree,
                            segments: [
                                {
                                    type: "PDJS.Manage.Process.ProcessExplorerContextMenu"
                                }
                            ]
                        });
                    this.controls.add(this.m_treeContextMenu);
                }
                getSelectedProcessNode() {
                    var _a, _b;
                    let result = null;
                    let item = (_a = this.tree) === null || _a === void 0 ? void 0 : _a.dataItem((_b = this.tree) === null || _b === void 0 ? void 0 : _b.select());
                    if (item) {
                        result = this.processNodeTree.getNode(item.id);
                    }
                    return result;
                }
                tree_init() {
                    let data;
                    this.m_tree = this.treeNode.kendoTreeView({
                        dataTextField: "name",
                        change: _.bind(this.tree_change, this),
                        dragAndDrop: true,
                        dataSource: new kendo.data.HierarchicalDataSource({
                            schema: {
                                model: {
                                    children: "nodes",
                                }
                            }
                        }),
                        dataBound: _.bind(this.tree_dataBound, this),
                        drag: _.bind(this.tree_drag, this),
                        drop: _.bind(this.tree_drop, this),
                        template: _.bind(this.tree_template, this)
                    }).data("kendoTreeView");
                    this.tree.templates.dragClue = (data) => {
                        return `<div class="k-header k-drag-clue -pdjs-manage-process-tree-drag-hint">
                            <span class="k-drag-icon">
                                <span class="k-icon k-drag-status" />
                            </span>
                            <span class="k-drag-text">
                                ${data.item.name}
                            </span>
                        </div>`;
                    };
                    data = [this.processNodeTree.toJSON()];
                    this.tree.dataSource.data(data);
                    new PDJS.Shared.Navigate.TreeViewProxy({
                        tree: this.m_tree
                    });
                }
                tree_change(e) {
                    this.onChangeCallback({
                        processNode: this.selectedProcessNode,
                        node: this.selectedNode
                    });
                }
                tree_dataBound(e) {
                    if (!this.tree) {
                        return;
                    }
                    let item = e.node ?
                        this.tree.dataItem(e.node) :
                        this.tree.dataSource.get(this.processNodeTree.node.id);
                    if (item) {
                        this.initializeNodes(item.id);
                    }
                }
                tree_drag(e) {
                    let srcNode = $(e.sourceNode).closest(".k-item");
                    let dstNode = $(e.dropTarget).closest(".k-item");
                    let srcType = Process.ProcessNodeHelper.getData(srcNode, "type", "unknown");
                    let dstType = Process.ProcessNodeHelper.getData(dstNode, "type", "unknown");
                    let dropType = e.statusClass;
                    let isValid = this.isValidAdd(srcType, dstType, dropType) ||
                        this.isValidInsert(srcType, dstType, dropType);
                    if (!isValid) {
                        e.setStatusClass("k-denied");
                    }
                }
                tree_drop(e) {
                    let srcNode = $(e.sourceNode).closest(".k-item");
                    let dstNode = $(e.dropTarget).closest(".k-item");
                    let srcType = Process.ProcessNodeHelper.getData(srcNode, "type", "unknown");
                    let dstType = Process.ProcessNodeHelper.getData(dstNode, "type", "unknown");
                    let dropType = e.dropPosition;
                    e.valid =
                        !this.m_treeMoveSuspended &&
                            (this.isValidAdd(srcType, dstType, dropType) ||
                                this.isValidInsert(srcType, dstType, dropType));
                    if (e.valid) {
                        this.m_treeMoveSuspended = true;
                        let srcId = this.tree.dataItem(srcNode).objectId;
                        let dstId = this.tree.dataItem(dstNode).objectId;
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("pdjs/manage/process:node/move", {
                            srcNodeId: srcId,
                            dstNodeId: dstId,
                            dropType: dropType
                        });
                        setTimeout(() => { this.m_treeMoveSuspended = false; }, 1500);
                    }
                }
                tree_template(e) {
                    let processNode = this.processNodeTree.getNode(e.item.id);
                    let result = processNode != null ?
                        processNode.toMarkup() : "render error";
                    return result;
                }
                initializeNodes(id) {
                    let node = this.processNodeTree.getNode(id);
                    let data = node.nodes.toJSON() || [];
                    if (node) {
                        this.applyTemplate(node.id);
                    }
                    data.forEach(item => {
                        this.initializeNodes(item.id);
                    });
                }
                getNodeById(id) {
                    let result = null;
                    let data = this.tree.dataSource.get(id);
                    if (data) {
                        result = this.tree.findByUid(data.uid);
                    }
                    return result;
                }
                isValidAdd(srcType, dstType, dropType) {
                    return (dropType == "add" || dropType == "over") && (dstType == "process" && srcType == "key" ||
                        dstType == "key" && srcType == "stage" ||
                        dstType == "stage" && srcType == "decision");
                }
                isValidInsert(srcType, dstType, dropType) {
                    let isInsert = (dropType == "insert-top" ||
                        dropType == "insert-middle" ||
                        dropType == "insert-bottom" ||
                        dropType == "before" ||
                        dropType == "after");
                    return isInsert && (dstType == "key" && srcType == "key" ||
                        dstType == "stage" && srcType == "stage" ||
                        dstType == "decision" && srcType == "decision");
                }
            }
            Process.ProcessTree = ProcessTree;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get process() {
                    return this.state.get("process");
                }
                set process(value) {
                    this.state.set("process", value);
                }
                load(process) {
                    this.process = process;
                }
                template() {
                    return `<div class="-pdjs-manage-recycle-bin-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Types",
                        url: "#/module/entity-types"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Insights"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Process Nodes",
                        url: "#/module/insights-viewer/processnodes"
                    }));
                }
            }
            Process.ProcessesActions = ProcessesActions;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selection() {
                    return _.first(this.selections);
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/processes": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Process.ProcessesCommand = ProcessesCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class CreateProcessCommand extends Process.ProcessesCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Process",
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/create",
                        tooltip: "Create a new process.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Process.CreateProcessCommand = CreateProcessCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class EditProcessCommand extends Process.ProcessesCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${this.selection.name}`,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.grid.refresh();
                                Process.EventsHub.processRenamedPublish({
                                    processId: e.target.id,
                                    processName: e.target.name
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/edit",
                        tooltip: "Edit the properties of the selected process",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Process.EditProcessCommand = EditProcessCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class DeleteProcessCommand extends Process.ProcessesCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Process",
                        message: `Delete the selected process?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/delete",
                        tooltip: "Delete the the selected process.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeDelete() {
                    let service = new PDJS.Services.Process.ProcessesService();
                    service.deleteProcess({
                        id: this.selection.id,
                        success: (e) => {
                            this.grid.refresh({
                                clear: true
                            });
                        }
                    });
                }
            }
            Process.DeleteProcessCommand = DeleteProcessCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class OpenProcessCommand extends Process.ProcessesCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    window.location.hash = `/module/process/${this.selection.id}`;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/open",
                        tooltip: "Open the selected process.",
                        label: "Open",
                        icon: "folder_open.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Process.OpenProcessCommand = OpenProcessCommand;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/processes");
                }
                registerCommands(e) {
                    e.commands.add(new Process.CreateProcessCommand());
                    e.commands.add(new Process.EditProcessCommand());
                    e.commands.add(new Process.DeleteProcessCommand());
                    e.commands.add(new Process.OpenProcessCommand());
                }
            }
            Process.ProcessesCommands = ProcessesCommands;
            Jade.CommandGroups.add(ProcessesCommands);
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/processes:process/edit"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/processes:process/delete"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/processes:process/open"
                    }));
                }
            }
            Process.ProcessesContextMenu = ProcessesContextMenu;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return ((_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray()) || [];
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-module-processes-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Processes</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Process.ProcessesToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No processes."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/processes:process/open");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: () => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{ type: "PDJS.Manage.Process.ProcessesContextMenu" }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Process.ProcessesGrid = ProcessesGrid;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} ${Process.CssClass.ProcessesModule}">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Process.ProcessesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Process.ProcessesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Process.ProcessesService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/processes": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Process.ProcessesModule = ProcessesModule;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Process;
        (function (Process) {
            class ProcessesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/processes:process/create"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/processes:process/edit"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/processes:process/delete"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/processes:process/open"
                    }));
                }
            }
            Process.ProcessesToolbar = ProcessesToolbar;
        })(Process = Manage.Process || (Manage.Process = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get itemId() {
                    return this.state.get("itemId");
                }
                set itemId(value) {
                    this.state.set("itemId", value);
                }
                load(itemId) {
                    this.itemId = itemId;
                }
                template() {
                    return `<div class="-pdjs-manage-recycle-bin-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Entity Management",
                        url: "#/module/entity-management"
                    }));
                }
            }
            RecycleBin.RecycleBinActions = RecycleBinActions;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selectedIds() {
                    return _.map(this.selections, "id");
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/recycle-bin": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            RecycleBin.RecycleBinCommand = RecycleBinCommand;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class DeleteItemsCommand extends RecycleBin.RecycleBinCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "item/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Permanently delete the selected items.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    PDJS.Manage.RecycleBin.RecycleBinConfirmationDialog.open({
                        select: (sender, e) => {
                            this.executeServiceCall(e.selection.value === "delete");
                        }
                    });
                }
                executeServiceCall(removeReferences = false) {
                    let service = new PDJS.Services.RecycleBin.RecycleBinService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete from Recycle Bin",
                        taskStart: (args) => {
                            service.delete({
                                ids: this.selectedIds,
                                removeReferences: removeReferences,
                                success: (e) => {
                                    args.startPolling(e.data);
                                },
                                error: (e) => {
                                    args.abort(e);
                                }
                            });
                        },
                        taskSuccess: (args) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            RecycleBin.DeleteItemsCommand = DeleteItemsCommand;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class EmptyRecycleBinCommand extends RecycleBin.RecycleBinCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "empty",
                        label: "Empty Recycle Bin",
                        icon: "refresh.16px.font",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Permanently delete all items in the Recycle Bin.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                }
                execute(e) {
                    PDJS.Manage.RecycleBin.RecycleBinConfirmationDialog.open({
                        select: (sender, e) => {
                            this.executeServiceCall(e.selection.value === "delete");
                        }
                    });
                }
                executeServiceCall(removeReferences = false) {
                    let service = new PDJS.Services.RecycleBin.RecycleBinService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Empty Recycle Bin",
                        taskStart: (e) => {
                            service.empty({
                                removeReferences: removeReferences,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            RecycleBin.EmptyRecycleBinCommand = EmptyRecycleBinCommand;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RestoreItemsCommand extends RecycleBin.RecycleBinCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "item/restore",
                        label: "Restore",
                        icon: "undo.16px.font",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Restore the selected items from the recycle bin.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Restore | Items",
                        message: "Restore the selected items from the Recycle Bin?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startRestoreTask();
                            }
                        }
                    });
                }
                startRestoreTask() {
                    let service = new PDJS.Services.RecycleBin.RecycleBinService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Restore from Recycle Bin",
                        taskStart: (e) => {
                            service.restore({
                                ids: this.selectedIds,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            RecycleBin.RestoreItemsCommand = RestoreItemsCommand;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/recycle-bin");
                }
                registerCommands(e) {
                    e.commands.add(new RecycleBin.DeleteItemsCommand());
                    e.commands.add(new RecycleBin.EmptyRecycleBinCommand());
                    e.commands.add(new RecycleBin.RestoreItemsCommand());
                }
            }
            RecycleBin.RecycleBinCommands = RecycleBinCommands;
            Jade.CommandGroups.add(RecycleBinCommands);
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/recycle-bin";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:item/restore`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:item/delete`
                    }));
                }
            }
            RecycleBin.RecycleBinContextMenu = RecycleBinContextMenu;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-recycle-bin-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Recycle Bin Items</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new RecycleBin.RecycleBinToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No items in recycle bin."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/recycle-bin:item/open");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.RecycleBin.RecycleBinContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            RecycleBin.RecycleBinGrid = RecycleBinGrid;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-recycle-bin">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    if (this.m_grid != null) {
                        this.m_grid.refresh();
                    }
                }
                grid_init() {
                    this.m_grid = new RecycleBin.RecycleBinGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new RecycleBin.RecycleBinActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.RecycleBin.RecycleBinService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/recycle-bin": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            RecycleBin.RecycleBinModule = RecycleBinModule;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/recycle-bin";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:item/restore`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:item/delete`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:empty`
                    }));
                }
            }
            RecycleBin.RecycleBinToolbar = RecycleBinToolbar;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinConfirmationDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(options) {
                    return new RecycleBinConfirmationDialog({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        height: 270,
                        title: "Delete | Reference Handling",
                        header: `<span style="color:var(--visiv-required-text-color)">WARNING: This recycle bin operation cannot be undone.</span><br/>
                         How would you like the system to proceed when an item you are deleting is found to be referenced by other items in the system:`,
                        items: [
                            {
                                title: "Skip and Proceed",
                                message: `Skip deletion of the item leaving its active references intact and proceed onto to the next item to delete.`,
                                value: "skip",
                                selected: true
                            },
                            {
                                title: "Remove References, Delete and Proceed",
                                message: `Remove all the active references to the item, delete the item and proceed onto the next item to delete.`,
                                value: "delete"
                            }
                        ],
                        select: (sender, e) => {
                            sender.close();
                            if (sender.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                if (e.selection != null && options.select instanceof Function) {
                                    options.select(sender, e);
                                }
                            }
                        }
                    });
                }
            }
            RecycleBin.RecycleBinConfirmationDialog = RecycleBinConfirmationDialog;
        })(RecycleBin = Manage.RecycleBin || (Manage.RecycleBin = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get report() {
                    return this.state.get("tag");
                }
                set report(value) {
                    this.state.set("tag", value);
                }
                load(report) {
                    this.report = report;
                }
                template() {
                    return `<div class="-pdjs-manage-tags-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Manage"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Resources",
                        url: "#/module/resources"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Insights"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Text Resources",
                        url: "#/module/insights-viewer/textresources"
                    }));
                }
            }
            Reports.ReportsActions = ReportsActions;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                get selections() {
                    return this.grid.selections;
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/reports": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Reports.ReportsCommand = ReportsCommand;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class DeleteReportCommand extends Reports.ReportsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "report/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected reports.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Reports?",
                        message: `Delete the selected reports?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.executeDelete();
                            }
                        }
                    });
                }
                executeDelete() {
                    let service = new PDJS.Services.Reports.ReportsService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete Reports",
                        taskStart: (args) => {
                            service.delete({
                                ids: this.selectedIds,
                                success: (e2) => {
                                    args.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    args.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (args) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Reports.DeleteReportCommand = DeleteReportCommand;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class DownloadTemplateCommand extends Reports.ReportsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "report/download-template",
                        label: "Download Template",
                        icon: "inbox_into.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Download the template associated with the selected report.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    PDJS.Shared.Downloader.download({
                        url: `~/Manage/Report/Download/${this.selection.id}`
                    });
                }
            }
            Reports.DownloadTemplateCommand = DownloadTemplateCommand;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class EditReportCommand extends Reports.ReportsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "report/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the selected report.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let report = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${report.name}`,
                        height: 550,
                        width: 500,
                        args: {
                            targetId: report.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Reports.ReportUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Reports.ReportArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            Reports.EditReportCommand = EditReportCommand;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class NewReportCommand extends Reports.ReportsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "report/new",
                        label: "New Report",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new report.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Report",
                        height: 550,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Reports.ReportUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Reports.ReportArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            Reports.NewReportCommand = NewReportCommand;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/reports");
                }
                registerCommands(e) {
                    e.commands.add(new Reports.DeleteReportCommand());
                    e.commands.add(new Reports.DownloadTemplateCommand());
                    e.commands.add(new Reports.EditReportCommand());
                    e.commands.add(new Reports.NewReportCommand());
                }
            }
            Reports.ReportsCommands = ReportsCommands;
            Jade.CommandGroups.add(ReportsCommands);
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-tags-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Reports</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Reports.ReportsGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No reports."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/reports:report/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Reports.ReportsGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Reports.ReportsGrid = ReportsGrid;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/reports";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:report/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:report/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:report/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:report/download-template`
                    }));
                }
            }
            Reports.ReportsGridContextMenu = ReportsGridContextMenu;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/reports";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:report/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:report/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:report/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:report/download-template`
                    }));
                }
            }
            Reports.ReportsGridToolbar = ReportsGridToolbar;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportsModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-reports">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Reports.ReportsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Reports.ReportsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Reports.ReportsService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/reports": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Reports.ReportsModule = ReportsModule;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class ReportSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get filter() {
                    return this.state.get("filter");
                }
                get grid() {
                    return this.m_grid;
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-report-selection-dialog">
                    <div data-role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Report",
                        height: "400px",
                        width: "600px",
                        maximized: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.Name
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.m_selection = e.selection;
                        },
                        dblclick: (e) => {
                            this.m_selection = e.selection;
                            this.closeAndReturn();
                        },
                        needContext: (e) => {
                            if (this.filter != null) {
                                e.filters[e.filters.length] = {
                                    id: this.filter
                                };
                            }
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.m_selection != null) {
                        this.close({
                            name: "ok",
                            data: {
                                report: this.m_selection
                            }
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No report has been selected. Select a report and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                static open(options) {
                    return new ReportSelectionDialog(options);
                }
            }
            Reports.ReportSelectionDialog = ReportSelectionDialog;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class IEditableType {
            }
            Resources.IEditableType = IEditableType;
            class EditableTypes {
                static get extensions() {
                    this.ensureExtensions();
                    return this.m_extensions.slice(0);
                }
                static get list() {
                    this.ensureTypes();
                    return this.m_list.slice(0);
                }
                static getType(extension) {
                    return _.first(this.list.filter(item => {
                        return item.type.find(type => type.toLowerCase() == extension.toLowerCase()) != null;
                    }));
                }
                static isEditableType(extension) {
                    return this.extensions.find(item => item.toLowerCase() == extension.toLowerCase()) != null;
                }
                static ensureExtensions() {
                    if (this.m_extensions) {
                        return;
                    }
                    let set = new Set();
                    this.list.forEach(item => {
                        item.type.forEach(type => {
                            set.add(type);
                        });
                    });
                    this.m_extensions = Array.from(set);
                }
                static ensureTypes() {
                    if (this.m_list) {
                        return;
                    }
                    this.m_list = [{
                            file: "New Stylesheet.css",
                            icon: "file-type-css.png",
                            mime: "text/css",
                            name: "Style Sheet",
                            type: [".css"]
                        },
                        {
                            file: "New HTML Page.html",
                            icon: "file-type-html.png",
                            mime: "text/html",
                            name: "HTML Page",
                            type: [".html", ".htm"]
                        },
                        {
                            file: "New JavaScript File.js",
                            icon: "file-type-js.png",
                            mime: "text/javascript",
                            name: "JavaScript File",
                            type: [".js"]
                        },
                        {
                            file: "New JSON File.json",
                            icon: "file-type-json.png",
                            mime: "text/json",
                            name: "JSON File",
                            type: [".json"]
                        },
                        {
                            file: "New Text File.txt",
                            icon: "file-type-txt.png",
                            mime: "text/txt",
                            name: "Text File",
                            type: [".txt"]
                        },
                        {
                            file: "New XML File.xml",
                            icon: "file-type-xml.png",
                            mime: "text/xml",
                            name: "XML File",
                            type: [".xml"]
                        }
                    ];
                }
            }
            Resources.EditableTypes = EditableTypes;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourcesCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.state.set("$browser", null);
                    this.state.set("$explorer", null);
                    this.state.set("$location", null);
                    this.state.set("isDialog", null);
                    this.state.set("contextFolder", null);
                }
                get browser() {
                    return this.state.get("$browser");
                }
                get explorer() {
                    return this.state.get("$explorer");
                }
                get location() {
                    return this.state.get("$location");
                }
                get currentFolder() {
                    return this.getCurrentFolder();
                }
                get selections() {
                    return this.getSelections();
                }
                get isDialog() {
                    return this.state.get("isDialog");
                }
                get contextFolder() {
                    return this.state.get("contextFolder");
                }
                updateCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/resources": {
                            $browser: this.browser,
                            $explorer: this.explorer,
                            $location: this.location,
                            isDialog: this.isDialog,
                            contextFolder: this.contextFolder
                        }
                    }, { force: true });
                }
                folderContentChanged(folderId = null) {
                    if (!this.isDialog) {
                        return;
                    }
                    PDJS.Manage.Resources.
                        EventsHub.folderContentChangedPublish({
                        folderId: folderId || this.currentFolder.id
                    });
                }
                getCurrentFolder() {
                    return this.contextFolder != null ?
                        this.contextFolder :
                        _.last(this.location.path);
                }
                getSelections() {
                    var _a;
                    return this.contextFolder != null ?
                        [this.contextFolder] : ((_a = this.browser) === null || _a === void 0 ? void 0 : _a.selections) || [];
                }
            }
            Resources.ResourcesCommand = ResourcesCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceDownloadCommand extends Resources.ResourcesCommand {
                get isMultiSelect() {
                    return this.selections.length > 1;
                }
                get selectionContainsFolder() {
                    return this.selections
                        .filter(item => item.role == "folder").length > 0;
                }
                get isPackageDownload() {
                    return this.isMultiSelect || this.selectionContainsFolder;
                }
                get selection() {
                    return _.first(this.selections);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "file/download",
                        label: "Download",
                        tooltip: "Download the selected files and/or folders.",
                        icon: "nav_down.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    if (this.isPackageDownload) {
                        this.downloadPackage();
                    }
                    else {
                        PDJS.Shared.Downloader.downloadWithProgress({
                            url: `~/Manage/Resources/DownloadFile/${this.selection.id}`,
                            name: this.selection.name
                        });
                    }
                }
                downloadPackage() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    let resourceIds = _.map(this.selections, "id");
                    let firstResourceId = _.first(resourceIds);
                    let zipFolderContents = resourceIds.length == 1 &&
                        firstResourceId == this.currentFolder.id;
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Download Files",
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.getPackage({
                                folderId: this.currentFolder.id,
                                resourceIds: zipFolderContents ? [] : resourceIds,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            PDJS.Shared.Downloader.downloadWithProgress({
                                url: "~/Manage/Resources/DownloadPackage",
                                params: {
                                    path: e.output.path,
                                    name: e.output.name
                                }
                            });
                        }
                    });
                }
            }
            Resources.ResourceDownloadCommand = ResourceDownloadCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class FileNewCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "file/new",
                        label: "New File",
                        tooltip: "Add a new file to the selected folder.",
                        icon: "document_empty.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = !this.isDialog;
                }
                execute(e) {
                    PDJS.Manage.Resources.NewFileDialog.open({
                        select: {
                            ok: (sender, e) => {
                                window.location.hash = `/module/resources-editor/${e.type},${this.currentFolder.id},${Jade.Guid.new()}`;
                            }
                        }
                    });
                }
            }
            Resources.FileNewCommand = FileNewCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class FileUploadCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "file/upload",
                        label: "Upload",
                        tooltip: "Upload one or more files to the selected folder.",
                        icon: "nav_up.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.setState(state);
                    this.init_uploader();
                }
                execute(e) {
                    this.folderContentChanged();
                }
                init_uploader() {
                    let buttonNode = $(`[command-id=${this.UID}]`);
                    if (buttonNode.length == 0 || this.browser == null) {
                        return;
                    }
                    PDJS.Shared.Upload.Uploader.create({
                        folderId: () => {
                            return this.currentFolder.id;
                        },
                        containerNode: this.browser.node,
                        selectButtonNode: buttonNode,
                        dropNode: this.browser.node,
                        onCommitSuccess: (sender, e) => {
                            this.browser.refresh({
                                clear: true,
                                selections: e.ids
                            });
                            PDJS.Shared.MessageStack.instance.success("Files uploaded successfully.");
                        }
                    });
                }
            }
            Resources.FileUploadCommand = FileUploadCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class FolderNewCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "folder/new",
                        label: "New Folder",
                        icon: "folder_plus.png",
                        tooltip: "Add a new folder to the selected folder.",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Folder",
                        height: 400,
                        width: 450,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FolderUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FolderArbiter",
                            properties: {
                                parentId: this.currentFolder.id
                            }
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.updateUI(e.target);
                                this.folderContentChanged();
                            }
                        }
                    });
                }
                updateUI(target) {
                    this.browser.refresh({
                        clear: true,
                        selections: [target.id]
                    });
                    this.explorer.refresh({
                        folderId: target.parentId,
                    });
                    Resources.EventsHub.explorerRefreshPublish();
                }
            }
            Resources.FolderNewCommand = FolderNewCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceDeleteCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "resource/delete",
                        label: "Delete",
                        tooltip: "Delete the selected files and/or folders.",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.isEnabled();
                }
                execute(e) {
                    if (!this.enabled) {
                        return;
                    }
                    let ids = this.selections.map(item => item.id);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Selections",
                        message: `Delete the selected ${ids.length} items?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDeletionTask(ids);
                            }
                        }
                    });
                }
                executeDeletionTask(ids) {
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete | Resources",
                        taskStart: (e) => {
                            let service = new PDJS.Services.Resources.ResourcesService();
                            service.deleteResources({
                                ids: ids,
                                success: (args) => {
                                    e.startPolling(args.data);
                                }
                            });
                        },
                        close: (e) => {
                            this.browser.refresh({
                                clear: true
                            });
                            ids.forEach(id => {
                                this.explorer.deleteNode(id);
                                Resources.EventsHub.explorerRefreshPublish();
                            });
                            this.fallback(ids);
                            this.folderContentChanged();
                        }
                    });
                }
                fallback(ids) {
                    let shouldFallback = false;
                    let fallbackId = null;
                    this.location.path.reverse().forEach(item => {
                        ids.indexOf(item.id) > -1 ?
                            shouldFallback = true : null;
                        if (ids.indexOf(item.id) < 0 && fallbackId == null) {
                            let data = this.explorer.getDataItem(item.id);
                            if (data) {
                                fallbackId = data.id;
                            }
                        }
                    });
                    if (shouldFallback) {
                        this.explorer.select(fallbackId);
                        Resources.EventsHub.locationChangePublish({
                            folderId: fallbackId
                        });
                    }
                }
                isEnabled() {
                    let result = false;
                    let resource = _.first(this.selections);
                    if (resource) {
                        result = !Jade.Guid.isNullOrEmpty(resource.id);
                    }
                    return result && this.selections.length > -1;
                }
            }
            Resources.ResourceDeleteCommand = ResourceDeleteCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceMoveCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "resource/move",
                        label: "Move",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    let args = {
                        destination: e.destination,
                        sourceIds: this.selections.map(item => item.id),
                        folderIds: this.selections
                            .filter(item => item.role == "folder")
                            .map(item => item.id)
                    };
                    if (this.isValidMove(args)) {
                        this.showTaskDialog(args);
                    }
                }
                showTaskDialog(args) {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Move | Resources",
                        taskStart: (e) => {
                            service.moveResources({
                                destinationId: args.destination.id,
                                sourceIds: args.sourceIds,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2.xhr.responseJSON);
                                    e2.errorHandled = true;
                                }
                            });
                        },
                        close: (e) => {
                            this.browser.refresh({
                                clear: true
                            });
                            this.explorer.move(args.destination.id, e.output.moved);
                            this.folderContentChanged();
                        }
                    });
                }
                isValidMove(args) {
                    if (args.destination.role !== "folder") {
                        return false;
                    }
                    if (_.includes(args.sourceIds, args.destination.id)) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "Error | Cannot Move folder",
                            message: `The folder "${args.destination.name}" cannot be moved into itself. 
                                Please try moving the selections to a different folder location.`
                        });
                        return false;
                    }
                    return true;
                }
            }
            Resources.ResourceMoveCommand = ResourceMoveCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceOpenCommand extends Resources.ResourcesCommand {
                get selection() {
                    return _.first(this.selections);
                }
                get allSelectionsAreEditableFiles() {
                    return this.canOpenAllSelectionsForEdit();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "resource/open",
                        label: "Open",
                        tooltip: "Open the selected file.",
                        icon: "nav_redo.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled =
                        (this.selections.length === 1 && this.selection.role == "folder") ||
                            (this.selections.length > 0 && this.allSelectionsAreEditableFiles);
                }
                execute(e) {
                    if (this.allSelectionsAreEditableFiles) {
                        this.openEditableFiles();
                        return;
                    }
                    switch (this.selection.role) {
                        case "folder":
                            this.openFolder(this.selection);
                            break;
                        case "file":
                            this.openFile(this.selection);
                            break;
                    }
                }
                openFile(file) {
                    if (this.canOpenFileForEdit(file)) {
                        window.location.hash = `#/module/resources-editor/${file.id}`;
                        return;
                    }
                    PDJS.Shared.Downloader.downloadWithProgress({
                        url: `~/Manage/Resources/DownloadFile/${file.id}`,
                        name: file.name
                    });
                }
                openFolder(folder) {
                    Resources.EventsHub.locationChangePublish({
                        folderId: folder.id,
                        source: "browser"
                    });
                }
                openEditableFiles() {
                    let routes = this.selections.map(file => {
                        return `#/module/resources-editor/${file.id}`;
                    });
                    Manage.ModuleLoader.load(routes, {
                        message: "Loading files, please wait...",
                        returnUrl: routes.length > 1 ? location.href : null
                    });
                }
                canOpenFileForEdit(file) {
                    let extension = Jade.Path.getFileExtension(file.name);
                    return Resources.EditableTypes.isEditableType(extension);
                }
                canOpenAllSelectionsForEdit() {
                    let hasFolders = this.selections.find(item => {
                        return item.role === "folder";
                    }) != null;
                    if (hasFolders) {
                        return false;
                    }
                    let result = false;
                    result = this.selections.find(item => !this.canOpenFileForEdit(item)) == null;
                    return result;
                }
            }
            Resources.ResourceOpenCommand = ResourceOpenCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourcePropertiesCommand extends Resources.ResourcesCommand {
                get selection() {
                    return _.first(this.selections);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "resource/properties",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2",
                        tooltip: "Edit the properties of the selected file or folder."
                    };
                }
                onStateChanged(e) {
                    var _a;
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1 &&
                        !Jade.Guid.isNullOrEmpty((_a = this.selection) === null || _a === void 0 ? void 0 : _a.id);
                }
                execute(e) {
                    switch (this.selection.role) {
                        case "folder":
                            this.editFolder();
                            break;
                        case "file":
                            this.editFile();
                            break;
                    }
                }
                editFolder() {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Folder | ${this.selection.name}`,
                        height: 500,
                        width: 450,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FolderUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FolderArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.browser.refresh();
                                if (this.selection.name == e.target.name) {
                                    return;
                                }
                                this.explorer.refresh({
                                    folderId: e.target.parentId
                                });
                                Resources.EventsHub.explorerRefreshPublish();
                            }
                        }
                    });
                }
                editFile() {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `File | ${this.selection.name}`,
                        height: 500,
                        width: 450,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FileMetadataUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FileArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                Resources.Editor.EventsHub.resourceRenamedPublish({
                                    id: e.target.id,
                                    name: e.target.name
                                });
                                this.browser.refresh();
                                this.folderContentChanged();
                            }
                        }
                    });
                }
            }
            Resources.ResourcePropertiesCommand = ResourcePropertiesCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ZipUploadCommand extends Resources.ResourcesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "zip/upload",
                        label: "Upload Zip",
                        tooltip: "Upload a zip file that contains files and/or folders to be added or updated.",
                        icon: "folder_zip_up.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    super.execute(e);
                    this.executeServiceCall();
                }
                executeServiceCall() {
                    Resources.UploadZipDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.showTaskDialog(e.uploadId, e.uploadName, this.currentFolder.id);
                            }
                        }
                    });
                }
                showTaskDialog(uploadId, uploadName, folderId) {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Zip | Extract",
                        taskStart: (e) => {
                            service.addPackage({
                                fileName: uploadName,
                                folderId: folderId,
                                uploadId: uploadId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2.xhr.responseJSON);
                                    e2.errorHandled = true;
                                }
                            });
                        },
                        close: (e) => {
                            Resources.EventsHub.locationChangePublish({
                                folderId: this.currentFolder.id,
                                record: false,
                                source: "dialog"
                            });
                            this.explorer.refresh({
                                folderId: this.currentFolder.id
                            });
                        }
                    });
                }
            }
            Resources.ZipUploadCommand = ZipUploadCommand;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourcesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/resources");
                }
                registerCommands(e) {
                    e.commands.add(new Resources.FileNewCommand());
                    e.commands.add(new Resources.FileUploadCommand());
                    e.commands.add(new Resources.FolderNewCommand());
                    e.commands.add(new Resources.ResourceDeleteCommand());
                    e.commands.add(new Resources.ResourceDownloadCommand());
                    e.commands.add(new Resources.ResourceMoveCommand());
                    e.commands.add(new Resources.ResourceOpenCommand());
                    e.commands.add(new Resources.ResourcePropertiesCommand());
                    e.commands.add(new Resources.ZipUploadCommand());
                }
            }
            Resources.ResourcesCommands = ResourcesCommands;
            Jade.CommandGroups.add(ResourcesCommands);
            class ResourcesContextMenuCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/resources/context-menu");
                }
                registerCommands(e) {
                    e.commands.add(new Resources.FileUploadCommand());
                    e.commands.add(new Resources.FolderNewCommand());
                    e.commands.add(new Resources.ResourceDeleteCommand());
                    e.commands.add(new Resources.ResourceDownloadCommand());
                    e.commands.add(new Resources.ResourceOpenCommand());
                    e.commands.add(new Resources.ResourcePropertiesCommand());
                    e.commands.add(new Resources.ZipUploadCommand());
                }
            }
            Resources.ResourcesContextMenuCommands = ResourcesContextMenuCommands;
            Jade.CommandGroups.add(ResourcesContextMenuCommands);
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourcesModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get browser() {
                    return this.m_browser;
                }
                set browser(value) {
                    this.m_browser = value;
                }
                get errorCallback() {
                    return this.state.get("error", () => { });
                }
                get explorer() {
                    return this.m_explorer;
                }
                set explorer(value) {
                    this.m_explorer = value;
                }
                get location() {
                    return this.m_location;
                }
                set location(value) {
                    this.m_location = value;
                }
                get nodes() {
                    return this.state.get("nodes");
                }
                set nodes(value) {
                    this.state.set("nodes", value);
                }
                get recorder() {
                    return this.m_recorder;
                }
                set recorder(value) {
                    this.m_recorder = value;
                }
                get splitter() {
                    return this.m_splitter;
                }
                set splitter(value) {
                    this.m_splitter = value;
                }
                get splitterNode() {
                    return this.node.find("div[data-role=splitter]");
                }
                get successCallback() {
                    return this.state.get("success", () => { });
                }
                get toolbar() {
                    return this.m_toolbar;
                }
                set toolbar(value) {
                    this.m_toolbar = value;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                template() {
                    return `<div class="-pdjs-manage-resources">
                        <div data-role="toolbar"></div>
                        <div data-role="location"></div>
                        <div>
                            <div data-role="splitter">
                                <div data-role="explorer"></div>
                                <div data-role="browser"></div>
                            </div>
                        </div>
                    </div>`;
                }
                resize() {
                    if (this.m_splitter) {
                        this.m_splitter.resize();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.module_init();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter) {
                        this.splitter.destroy();
                    }
                    if (this.recorder) {
                        this.recorder.destroy();
                    }
                }
                onModuleFocus(e) {
                    super.onModuleFocus(e);
                    if (this.splitter) {
                        this.splitter.resize(true);
                    }
                    if (this.recorder) {
                        this.recorder.refresh();
                    }
                    if (this.m_browser != null) {
                        this.m_browser.refresh();
                    }
                }
                module_init() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    service.getIndex({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.nodes = e.data.nodes;
                            this.successCallback();
                            this.explorer_init();
                            this.browser_init();
                            this.draggable_init();
                            this.recorder_init();
                            this.updateCommandState();
                        },
                        error: (e) => {
                            this.errorCallback();
                            e.errorHandled = true;
                        }
                    });
                    this.location_init();
                    this.splitter_init();
                    this.toolbar_init();
                    this.subscriptions.add(Resources.EventsHub.locationChangedSubscribe((e) => {
                        this.updateCommandState();
                    }));
                    this.subscriptions.add(Resources.EventsHub.resourceHighlightSubscribe((e) => {
                        this.updateCommandState();
                    }));
                    this.subscriptions.add(Resources.EventsHub.resourceSelectSubscribe((e) => {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("pdjs/manage/resources:resource/open");
                    }));
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .hotkeys
                        .simple_combo("delete", (e) => {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("pdjs/manage/resources:resource/delete");
                    });
                }
                browser_init() {
                    this.browser = new Resources.Browser({
                        insertAt: "div[data-role=browser]",
                        viewStateId: this.viewStateId,
                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                        change: () => {
                            this.updateCommandState();
                        }
                    });
                    this.controls.add(this.browser);
                }
                explorer_init() {
                    this.explorer = new Resources.Explorer({
                        insertAt: "div[data-role=explorer]",
                        nodes: this.nodes,
                        change: () => {
                            this.updateCommandState();
                        },
                        dblclick: () => {
                            this.updateCommandState();
                        }
                    });
                    this.controls.add(this.explorer);
                }
                location_init() {
                    this.location = new Resources.Location({
                        insertAt: "div[data-role=location]"
                    });
                    this.controls.add(this.location);
                }
                splitter_init() {
                    this.splitter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "300px" },
                            { resizable: true },
                            { resizable: true, size: "300px" }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                recorder_init() {
                    this.recorder = new Resources.EventsHubRecorder({
                        browser: this.browser,
                        explorer: this.explorer
                    });
                }
                toolbar_init() {
                    this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[data-role=toolbar]",
                        segments: [new Resources.ResourcesToolbar()]
                    });
                    this.controls.add(this.toolbar);
                }
                draggable_init() {
                    new Resources.DragAndDrop({
                        browser: this.browser,
                        explorer: this.explorer
                    });
                }
                updateCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/resources": {
                            $browser: this.browser,
                            $explorer: this.explorer,
                            $location: this.location,
                            isDialog: false
                        },
                        "pdjs/manage/resources/context-menu": {
                            $browser: this.browser,
                            $explorer: this.explorer,
                            $location: this.location,
                            isDialog: false
                        }
                    }, { force: true });
                }
            }
            Resources.ResourcesModule = ResourcesModule;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourcesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:folder/new"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:file/new"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:file/upload"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:file/download"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:resource/open"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:resource/properties"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:resource/delete"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:zip/upload"
                    }));
                }
            }
            Resources.ResourcesToolbar = ResourcesToolbar;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            let CssClass;
            (function (CssClass) {
                CssClass["Location"] = "-pdjs-manage-resources-location";
                CssClass["LocationRootItem"] = "-location-root-item";
                CssClass["LocationPathItem"] = "-location-path-item";
                CssClass["LocationButton"] = "-location-btn";
                CssClass["LocationButtonBack"] = "-location-btn-back";
                CssClass["LocationButtonNext"] = "-location-btn-next";
                CssClass["LocationBox"] = "-location-box";
                CssClass["LocationRoot"] = "-location-box-root";
                CssClass["LocationPath"] = "-location-box-path";
            })(CssClass = Resources.CssClass || (Resources.CssClass = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class DragAndDrop {
                constructor(options) {
                    this.m_grid_selector = "TR[data-uid][role=row]";
                    this.m_tree_selector = ".k-top, .k-mid, .k-bot";
                    this.m_browser = options.browser;
                    this.m_explorer = options.explorer;
                    this.m_subscriptions = [];
                    this.m_subscriptions.push(Resources.EventsHub.browserRefreshSubscribe(() => {
                        if (this.grid) {
                            this.draggable_init();
                            this.grid_droppable_init();
                        }
                    }));
                    this.m_subscriptions.push(Resources.EventsHub.explorerChangedSubscribe(() => {
                        if (this.explorer.loaded) {
                            this.tree_droppable_init();
                        }
                    }));
                    this.draggable_init();
                    this.grid_droppable_init();
                    this.tree_droppable_init();
                }
                get browser() {
                    return this.m_browser;
                }
                get explorer() {
                    return this.m_explorer;
                }
                get grid() {
                    return this.browser.grid.get_kendo();
                }
                get dropTarget() {
                    return this.m_dropTarget || $();
                }
                set dropTarget(value) {
                    this.m_dropTarget = value;
                }
                draggable_init() {
                    this.destroyDraggable();
                    this.browser.node.find(this.m_grid_selector)
                        .draggable({
                        appendTo: "body",
                        cursorAt: {
                            top: 0, left: -20
                        },
                        distance: 10,
                        helper: (e) => {
                            return this.getDragHelper(e);
                        },
                        create: _.bind(this.draggable_create, this),
                        drag: _.bind(this.draggable_drag, this),
                        start: _.bind(this.draggable_start, this),
                        stop: _.bind(this.draggable_stop, this),
                    });
                }
                draggable_create(e, ui) {
                }
                draggable_drag(e, ui) {
                }
                draggable_start(e, ui) {
                    this.setDragHelperTargetHTML(ui.helper, `Move ${this.browser.selections.length} items.`);
                }
                draggable_stop(e, ui) {
                }
                grid_droppable_init() {
                    this.destroyGridDroppable();
                    this.browser.node.find(this.m_grid_selector)
                        .droppable({
                        tolerance: "pointer",
                        drop: _.bind(this.grid_droppable_drop, this),
                        over: _.bind(this.grid_droppable_over, this),
                        out: _.bind(this.grid_droppable_out, this)
                    });
                }
                grid_droppable_drop(e, ui) {
                    let data = this.grid.dataItem($(e.target));
                    let isFolder = data.ObjectType == "folder";
                    if (isFolder) {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .execute("pdjs/manage/resources:resource/move", {
                            destination: {
                                icon: null,
                                id: data.ObjectId,
                                name: data.ObjectName,
                                role: data.ObjectType
                            }
                        });
                    }
                }
                grid_droppable_over(e, ui) {
                    this.dropTarget = $(e.target);
                    setTimeout(() => {
                        let data = this.grid.dataItem($(e.target));
                        let isFolder = data.ObjectType == "folder";
                        this.setDragHelperActionHTML(ui.helper, `Move into <b>${data.Name}.</b>`);
                        this.setDragHelperActionVisible(ui.helper, isFolder);
                    });
                }
                grid_droppable_out(e, ui) {
                    let node = $(e.target);
                    let isDropTargetBeingExited = this.dropTarget.get(0) == node.get(0);
                    if (!isDropTargetBeingExited) {
                        let data = this.grid.dataItem($(e.target));
                        if (data.ObjectType == "folder") {
                            return;
                        }
                        ;
                    }
                    this.setDragHelperActionHTML(ui.helper, "");
                    this.setDragHelperActionVisible(ui.helper, false);
                }
                tree_droppable_init() {
                    this.destroyTreeDroppable();
                    this.explorer.node.find(this.m_tree_selector)
                        .droppable({
                        tolerance: "pointer",
                        drop: _.bind(this.tree_droppable_drop, this),
                        over: _.bind(this.tree_droppable_over, this),
                        out: _.bind(this.tree_droppable_out, this)
                    });
                }
                tree_droppable_drop(e, ui) {
                    let node = $(e.target).closest("li[role=treeitem]");
                    let data = this.explorer.getDataItem(node);
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .execute("pdjs/manage/resources:resource/move", {
                        destination: {
                            icon: null,
                            id: data.id,
                            name: data.name,
                            role: "folder"
                        }
                    });
                }
                tree_droppable_over(e, ui) {
                    this.dropTarget = $(e.target);
                    setTimeout(() => {
                        let data = this.explorer.getDataItem($(e.target));
                        this.setDragHelperActionHTML(ui.helper, `Move into <b>${data.name}.</b>`);
                        this.setDragHelperActionVisible(ui.helper, true);
                    });
                }
                tree_droppable_out(e, ui) {
                    let node = $(e.target);
                    let isDropTargetBeingExited = this.dropTarget.get(0) == node.get(0);
                    if (!isDropTargetBeingExited) {
                        let data = this.explorer.getDataItem($(e.target));
                        if (data.ObjectType == "folder") {
                            return;
                        }
                        ;
                    }
                    this.setDragHelperActionHTML(ui.helper, "");
                    this.setDragHelperActionVisible(ui.helper, false);
                }
                destroy() {
                    this.destroyDraggable();
                    this.destroyGridDroppable();
                    this.destroyTreeDroppable();
                    this.m_subscriptions.forEach(subscription => subscription.unsubscribe);
                }
                destroyDraggable() {
                    let draggableExists = this.browser.node
                        .find(this.m_grid_selector)
                        .hasClass("ui-draggable");
                    if (draggableExists) {
                        this.browser.node.find(this.m_grid_selector)
                            .draggable("destroy");
                    }
                }
                destroyGridDroppable() {
                    let droppableExists = this.browser.node
                        .find(this.m_grid_selector)
                        .hasClass("ui-droppable");
                    if (droppableExists) {
                        this.browser.node.find(".ui-droppable")
                            .droppable("destroy");
                    }
                }
                destroyTreeDroppable() {
                    let droppableExists = this.explorer.node
                        .find(this.m_tree_selector)
                        .hasClass("ui-droppable");
                    if (droppableExists) {
                        this.explorer.node.find(".ui-droppable")
                            .droppable("destroy");
                    }
                }
                getDragHelper(e) {
                    return `<div class="-pdjs-manage-resources-drag-helper">
                        <div role="target"></div>
                        <div role="action" style="display:none"></div>
                    </div>`;
                }
                setDragHelperTargetHTML(helper, value) {
                    helper.children("div[role=target]").html(value);
                }
                setDragHelperActionHTML(helper, value) {
                    helper.children("div[role=action]").html(value);
                }
                setDragHelperActionVisible(helper, visible) {
                    let action = helper.children("div[role=action]");
                    visible ? action.show() : action.hide();
                }
            }
            Resources.DragAndDrop = DragAndDrop;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            let Events;
            (function (Events) {
                Events["FolderContentChanged"] = "folder/content/changed";
                Events["LocationChange"] = "location/change";
                Events["LocationChanged"] = "location/changed";
                Events["ResourceHighlight"] = "resource/highlight";
                Events["ResourceSelect"] = "resource/select";
                Events["BrowserRefresh"] = "browser/refresh";
                Events["ExplorerChanged"] = "explorer/changed";
                Events["ExplorerRefresh"] = "explorer/refresh";
            })(Events = Resources.Events || (Resources.Events = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static browserRefreshPublish() {
                    this.current.publish(Resources.Events.BrowserRefresh);
                }
                static explorerChangedPublish(args) {
                    this.global.publish(Resources.Events.ExplorerChanged, args);
                }
                static resourceHighlightPublish(args) {
                    this.current.publish(Resources.Events.ResourceHighlight, args);
                }
                static resourceSelectPublish(args) {
                    this.current.publish(Resources.Events.ResourceSelect, args);
                }
                static locationChangePublish(args) {
                    this.current.publish(Resources.Events.LocationChange, args);
                }
                static locationChangedPublish(args) {
                    this.current.publish(Resources.Events.LocationChanged, args);
                }
                static folderContentChangedPublish(args) {
                    this.global.publish(Resources.Events.FolderContentChanged, args);
                }
                static explorerRefreshPublish() {
                    this.global.publish(Resources.Events.ExplorerRefresh);
                }
                static browserRefreshSubscribe(handler) {
                    return this.current.subscribe(Resources.Events.BrowserRefresh, handler);
                }
                static explorerChangedSubscribe(handler) {
                    return this.global.subscribe(Resources.Events.ExplorerChanged, handler);
                }
                static resourceHighlightSubscribe(handler) {
                    return this.current.subscribe(Resources.Events.ResourceHighlight, handler);
                }
                static resourceSelectSubscribe(handler) {
                    return this.current.subscribe(Resources.Events.ResourceSelect, handler);
                }
                static locationChangeSubscribe(handler) {
                    return this.current.subscribe(Resources.Events.LocationChange, handler);
                }
                static locationChangedSubscribe(handler) {
                    return this.current.subscribe(Resources.Events.LocationChanged, handler);
                }
                static folderContentChangedSubscribe(handler) {
                    return this.global.subscribe(Resources.Events.FolderContentChanged, handler);
                }
                static explorerRefreshSubscribe(handler) {
                    return this.global.subscribe(Resources.Events.ExplorerRefresh, handler);
                }
            }
            Resources.EventsHub = EventsHub;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class EventsHubRecorder extends PDJS.Core.Model {
            constructor(options = {}) {
                super(options);
                this.m_history = new Jade.Collection();
                this.onInitialize();
            }
            get history() {
                return this.m_history;
            }
            get contextId() {
                return this.state.get("contextId");
            }
            set contextId(value) {
                this.state.set("contextId", value);
            }
            get globalContext() {
                return PDJS.Application
                    .instance
                    .contexts
                    .global;
            }
            get currentContext() {
                return PDJS.Application
                    .instance
                    .contexts
                    .current;
            }
            get shouldRefresh() {
                return this.history.count > 0;
            }
            refresh() {
                if (this.history.count > 0) {
                    this.onRefresh();
                }
            }
            onInitialize() {
                this.contextId = this.currentContext.ID;
            }
            onRefresh() {
            }
            record(args) {
                if (this.contextId == this.currentContext.ID) {
                    return;
                }
                this.history.add(args);
            }
        }
        Shared.EventsHubRecorder = EventsHubRecorder;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class EventsHubRecorder extends PDJS.Shared.EventsHubRecorder {
                constructor(options) {
                    super();
                    this.m_browser = options.browser;
                    this.m_explorer = options.explorer;
                }
                get browser() {
                    return this.m_browser;
                }
                get explorer() {
                    return this.m_explorer;
                }
                destroy() {
                    this.m_subscriptions.forEach(subscription => subscription.unsubscribe());
                }
                onInitialize() {
                    super.onInitialize();
                    this.m_subscriptions = [];
                    this.m_subscriptions.push(Resources.EventsHub.explorerRefreshSubscribe(() => {
                        this.record({
                            eventName: Resources.Events.ExplorerRefresh
                        });
                    }));
                }
                onRefresh() {
                    super.onRefresh();
                    if (this.shouldRefresh) {
                        this.explorer.refresh();
                        this.browser.refresh();
                        this.history.clear();
                    }
                }
            }
            Resources.EventsHubRecorder = EventsHubRecorder;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class Browser extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get extensions() {
                    return this.state.get("extensions", []);
                }
                get grid() {
                    return this.m_grid;
                }
                set grid(value) {
                    this.m_grid = value;
                }
                get gridNode() {
                    return this.node.children("div[role=grid]");
                }
                get selectedFolderId() {
                    return this.state.get("selectedFolderId");
                }
                set selectedFolderId(value) {
                    this.state.set("selectedFolderId", value);
                }
                get selections() {
                    return this.grid.getSelections().toArray();
                }
                get selectionMode() {
                    return this.state.get("selectionMode", PD.Web.UI.Controls.GridSelectionMode.single);
                }
                set selectionMode(value) {
                    this.state.set("selectionMode", value);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(args = {}) {
                    this.grid.refresh(args);
                }
                template() {
                    return `<div class="-pdjs-manage-resources-browser">
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.subscriptions.add(Resources.EventsHub.locationChangedSubscribe((e) => {
                        this.selectedFolderId = e.folderId;
                        this.grid.refresh({
                            clear: true
                        });
                    }));
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.grid) {
                        this.grid.destroy();
                    }
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.gridNode,
                        viewStateId: this.viewStateId,
                        height: "100%",
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName,
                                    role: e.ObjectType,
                                    mimeType: e.ObjectMimeType
                                };
                            }
                        },
                        defaultSelectionEnabled: false,
                        selectOnRightClick: true,
                        selectionMode: this.selectionMode,
                        needContext: (e) => {
                            this.grid_addFilterByParent(e);
                            this.grid_addFilterByExtension(e);
                        },
                        dataBound: () => {
                            Resources.EventsHub.browserRefreshPublish();
                        },
                        change: _.bind(this.grid_change, this),
                        dblclick: _.bind(this.grid_dblclick, this),
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                grid_change(e) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pd/resources": {
                            targetFolderId: this.selectedFolderId,
                            resources: e.selections.toArray()
                        }
                    });
                    Resources.EventsHub.resourceHighlightPublish({
                        items: e.selections.toArray()
                    });
                }
                grid_dblclick(e) {
                    if (e.selection.role === "folder") {
                        Resources.EventsHub.locationChangePublish({
                            folderId: e.selection.id,
                            source: "browser"
                        });
                    }
                    else {
                        Resources.EventsHub.resourceSelectPublish({
                            items: e.selections.toArray()
                        });
                    }
                }
                grid_addFilterByParent(context) {
                    let selectedFolderId = null;
                    if (this.selectedFolderId != null && this.selectedFolderId != Jade.Guid.empty()) {
                        selectedFolderId = this.selectedFolderId;
                    }
                    context.filters.push({
                        id: "Parent",
                        params: {
                            id: selectedFolderId
                        }
                    });
                }
                grid_addFilterByExtension(context) {
                    if (this.extensions.length > 0) {
                        context.filters.push({
                            id: "Extension",
                            params: {
                                ext: this.extensions.join("|")
                            }
                        });
                    }
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Resources.BrowserContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Resources.Browser = Browser;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class BrowserContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:folder/new"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:file/new"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:resource/open"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:resource/properties"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:resource/delete"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:file/download"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources:zip/upload"
                    }));
                }
            }
            Resources.BrowserContextMenu = BrowserContextMenu;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class Explorer extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_dataSource = new PDJS.Core.Resources.ResourceTree({
                        items: this.nodes
                    });
                }
                get loaded() {
                    return this.tree != null;
                }
                get selectedNode() {
                    return this.tree.select();
                }
                get dataSource() {
                    return this.m_dataSource;
                }
                get nodes() {
                    return this.state.get("nodes", []);
                }
                get tree() {
                    return this.m_tree;
                }
                set tree(value) {
                    this.m_tree = value;
                }
                get treeNode() {
                    return this.node.children("div[role=tree]");
                }
                template() {
                    return `<div class="-pdjs-manage-resources-explorer">
                        <div role="tree"></div>
                    </div>`;
                }
                getSelectedFolder() {
                    let result = null;
                    let data = this.tree.dataItem(this.tree.select());
                    if (data != null) {
                        result = data.toJSON();
                    }
                    return result;
                }
                getSelectedFolderId() {
                    let folder = this.getSelectedFolder();
                    let result = null;
                    if (folder) {
                        result = Jade.Guid.isNullOrEmpty(folder.id)
                            ? null : folder.id;
                    }
                    return result;
                }
                getDataItem(arg1) {
                    if (arg1 instanceof jQuery) {
                        return this.tree.dataItem(arg1);
                    }
                    if (_.isString(arg1)) {
                        return this.tree.dataSource.get(arg1);
                    }
                    return null;
                }
                deleteNode(folderId) {
                    let src = this.getNodeInfo(folderId);
                    if (!src.hasNode) {
                        return;
                    }
                    this.tree.remove(src.node);
                    if (!src.data.parentId) {
                        return;
                    }
                }
                move(dstId, srcIds) {
                    let expanded = [];
                    this.getExpandedNodes(dstId).forEach(id => {
                        expanded.push(id);
                    });
                    srcIds.forEach(id => {
                        this.getExpandedNodes(id).forEach(id => {
                            expanded.push(id);
                        });
                        this.deleteNode(id);
                    });
                    this.refresh({
                        folderId: dstId,
                        expanded: expanded
                    });
                }
                refresh(args = {}) {
                    let id = args.folderId == null ?
                        Jade.Guid.empty() : args.folderId;
                    let service = new PDJS.Services.Resources.ResourcesService();
                    let item = this.tree.dataSource.get(id);
                    if (!item) {
                        return;
                    }
                    service.getTreeNodes({
                        folderId: item.id,
                        expanded: args.expanded || this.getExpandedNodes(id),
                        success: (result) => {
                            item.nodes = result.data;
                            this.rebuildNode(item.toJSON(), args.expand);
                            Resources.EventsHub.explorerChangedPublish({
                                action: "expand"
                            });
                            _.isFunction(args.success) ?
                                args.success() : null;
                        },
                        error: (result) => {
                        }
                    });
                }
                select(id) {
                    this.findAndSelectNode(id);
                }
                onInit(e) {
                    super.onInit(e);
                    this.subscriptions.add(Resources.EventsHub.locationChangedSubscribe((e) => {
                        if (e.source != "explorer") {
                            this.findAndSelectNode(e.folderId);
                        }
                    }));
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.contextMenu_init();
                }
                tree_init() {
                    this.tree = this.treeNode.kendoTreeView({
                        dragAndDrop: false,
                        loadOnDemand: true,
                        dataSource: new kendo.data.HierarchicalDataSource({
                            schema: {
                                model: {
                                    children: "nodes",
                                    hasChildren: "hasNodes"
                                }
                            }
                        }),
                        select: _.bind(this.tree_select, this),
                        expand: _.bind(this.tree_expand, this),
                        template: (e) => {
                            return `<div class="-pdjs-manage-resources-explorer-node">
                                <div><img src="${this.get16x16Icon(e.item.icon)}" /></div>
                                <div>${e.item.name}</div>
                            </div>`;
                        }
                    }).data("kendoTreeView");
                    this.loadNodes(this.nodes);
                }
                tree_select(e) {
                    let item = this.tree.dataItem(e.node);
                    Resources.EventsHub.locationChangePublish({
                        folderId: item.id,
                        source: "explorer"
                    });
                }
                tree_expand(e) {
                    let item = e.sender.dataItem(e.node);
                    this.expandNode({
                        folderId: item.id
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.TreeContextMenu({
                        open: (e) => {
                            let data = this.tree.dataItem(e.target).toJSON();
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .setState({
                                "pdjs/manage/resources/context-menu": {
                                    contextFolder: _.extend(data, { type: "folder" })
                                }
                            }, { force: true });
                        },
                        target: `div[id=${this.ID}]`,
                        tree: this.tree,
                        segments: [{
                                type: "PDJS.Manage.Resources.ExplorerContextMenu",
                                context: (e) => {
                                    return "camera camera";
                                }
                            }]
                    });
                    this.controls.add(contextMenu);
                }
                expandNode(args = {}) {
                    let item = this.tree.dataSource.get(args.folderId);
                    if (item == null || item.loaded()) {
                        _.isFunction(args.success) ?
                            args.success() : null;
                        return;
                    }
                    this.refresh(args);
                }
                findAndSelectNode(id, expand = true) {
                    if (id == null) {
                        let rootNode = this.treeNode.find("li.k-item:first-child");
                        this.tree.select(rootNode);
                    }
                    this.expandNode({
                        folderId: id,
                        expand: expand,
                        success: () => {
                            let data = this.tree.dataSource.get(id);
                            if (!data) {
                                return;
                            }
                            let node = this.tree.element
                                .find(`.k-item[data-uid=${data.uid}]`);
                            if (node.length > 0) {
                                this.tree.select(node);
                                setTimeout(() => {
                                    node.get(0).scrollIntoView({
                                        behavior: "auto",
                                        block: "center",
                                        inline: "center"
                                    });
                                }, 100);
                            }
                        }
                    });
                }
                get16x16Icon(name) {
                    return Jade.IconSet.get("pd")
                        .resolve(name, Jade.IconSetSizeSpecificDirectory.x16);
                }
                getExpandedNodes(nodeId = null, list = []) {
                    let item = this.getNodeInfo(nodeId);
                    if (item.data && item.data.expanded) {
                        list.push(item.data.id);
                        let children = item.data.nodes;
                        children.forEach(item => {
                            list = this.getExpandedNodes(item.id, list);
                        });
                    }
                    return list;
                }
                getNodeInfo(id) {
                    let data = this.tree.dataSource.get(id);
                    let node = data != null ?
                        this.tree.findByUid(data.uid) : null;
                    return {
                        data: data,
                        node: node,
                        hasNode: node != null && node.length > -1,
                        nodeLoaded: data != null && data.loaded()
                    };
                }
                loadNodes(nodes) {
                    if (nodes == null) {
                        return;
                    }
                    this.tree.dataSource.data(this.dataSource.toJSON());
                    this.tree.expandPath([Jade.Guid.empty()], (e) => {
                        this.findAndSelectNode(Jade.Guid.empty());
                    });
                    Resources.EventsHub.explorerChangedPublish({
                        action: "expand"
                    });
                }
                rebuildNode(nodeData, expanded = null) {
                    let dst = this.getNodeInfo(nodeData.id);
                    if (dst.hasNode) {
                        let data = _.extend(nodeData, {
                            expanded: expanded == null ? nodeData.expanded : expanded,
                            hasNodes: nodeData.nodes.length > 0
                        });
                        this.tree.insertAfter(data, dst.node);
                        this.tree.remove(dst.node);
                    }
                }
            }
            Resources.Explorer = Explorer;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ExplorerContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources/context-menu:folder/new"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources/context-menu:resource/open"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources/context-menu:resource/properties"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources/context-menu:resource/delete"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "pdjs/manage/resources/context-menu:file/download"
                    }));
                }
            }
            Resources.ExplorerContextMenu = ExplorerContextMenu;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class Input extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get input() {
                    return this.m_input;
                }
                set input(value) {
                    this.m_input = value;
                }
                get label() {
                    return this.state.get("label", "");
                }
                set label(value) {
                    this.state.set("label", value);
                }
                get extension() {
                    return this.state.get("extension", "");
                }
                set extension(value) {
                    this.state.set("extension", value);
                }
                get labelNode() {
                    return this.node.children("div[role=label]");
                }
                get readonly() {
                    return this.state.get("readonly", false);
                }
                set readonly(value) {
                    this.state.set("readonly", value);
                }
                get value() {
                    return this.input.maskValue;
                }
                set value(value) {
                    this.setInputValue(value);
                    this.changedCallback();
                }
                get changedCallback() {
                    return this.state.get("changed", () => { });
                }
                get enterCallback() {
                    return this.state.get("enter", () => { });
                }
                focus() {
                    this.input.showText();
                    this.input.focusText();
                }
                template() {
                    return `<div class="-pdjs-manage-resources-input">
                        <div role="label"></div>
                        <div role="input"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input_init();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.labelNode.text(`${this.label}:`);
                    this.input.enabled = !this.readonly;
                }
                input_init() {
                    this.input = new PDJS.Shared.UI.Controls.MaskedTextBox({
                        insertAt: "div[role=input]",
                        defaultMaskText: "",
                        onMaskFocus: (e) => {
                            this.input.showText();
                            this.input.focusText();
                        },
                        onTextBlur: (e) => {
                            this.input.maskValue = `${this.input.textValue}${this.extension}`;
                            this.input.showMask();
                        },
                        onTextKeyUp: (e) => {
                            if (e.keyCode == Jade.KeyCode.Enter) {
                                this.input.textNode.blur();
                                this.enterCallback();
                            }
                            else {
                                this.changedCallback();
                            }
                        }
                    });
                    this.controls.add(this.input);
                }
                setInputValue(value) {
                    if (Jade.String.isNullOrWhiteSpace(value)) {
                        this.input.textValue = "";
                        this.input.maskValue = "";
                    }
                    else {
                        this.extension = Jade.Path.getFileExtension(value);
                        this.input.textValue = Jade.Path.getFileNameWithoutExtension(value);
                        this.input.maskValue = value;
                    }
                }
            }
            Resources.Input = Input;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class Location extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get nextButtonNode() {
                    return this.node.find("button[role=next]");
                }
                get prevButtonNode() {
                    return this.node.find("button[role=prev]");
                }
                get rootButtonNode() {
                    return this.node.find(`div.${Resources.CssClass.LocationRootItem}`);
                }
                get path() {
                    return (this.m_path || []).slice(0);
                }
                set path(value) {
                    this.m_path = value;
                }
                get pathNode() {
                    return this.node.find("div[role=path]");
                }
                get history() {
                    return this.m_history;
                }
                set history(value) {
                    this.m_history = value;
                }
                get events() {
                    return PDJS.Application.instance.contexts.current.events;
                }
                get overflowMenu() {
                    return this.m_overflowMenu;
                }
                set overflowMenu(value) {
                    this.m_overflowMenu = value;
                }
                getPath(includeRoot = false) {
                    var result = null;
                    if (_.isArray(this.path)) {
                        result = "";
                        this.path.forEach((item, index) => {
                            if (index > 0 || (index == 0 && includeRoot)) {
                                result += "/" + item.name;
                            }
                        });
                    }
                    return result;
                }
                resize() {
                    let pathNodeWidth = this.pathNode.outerWidth(true) - this.rootButtonNode.outerWidth(true);
                    let pathNodesReversed = $(this.pathNode.children().get().reverse());
                    let hiddenItems = [];
                    let totalWidth = 0;
                    this.pathNode.children().show();
                    pathNodesReversed.hide();
                    pathNodesReversed.each((index, element) => {
                        let node = $(element);
                        let item = node.data("item");
                        totalWidth += node.outerWidth(true);
                        if (totalWidth <= pathNodeWidth) {
                            node.show();
                        }
                        else {
                            if (item != null) {
                                hiddenItems.push(item);
                            }
                        }
                    });
                    this.rootButtonNode.removeClass("-pd-state-toggled");
                    this.overflowMenu.clear();
                    if (hiddenItems.length > 0) {
                        this.rootButtonNode.addClass("-pd-state-toggled");
                        this.overflowMenu.addMenuItems(hiddenItems);
                    }
                }
                template() {
                    return `<div class="${Resources.CssClass.Location}">
                        <div>
                            <button role="prev" class="${Resources.CssClass.LocationButton} ${Resources.CssClass.LocationButtonBack}" disabled>
                                <i class="icofont-simple-left"></i>
                            </button>
                        </div>
                        <div>
                            <button role="next" class="${Resources.CssClass.LocationButton} ${Resources.CssClass.LocationButtonNext}" disabled>
                                <i class="icofont-simple-right"></i>
                            </button>
                        </div>
                        <div role="box" class="${Resources.CssClass.LocationBox}">
                            <div role="root" class="${Resources.CssClass.LocationRoot}">
                                <div class="${Resources.CssClass.LocationRootItem}">
                                    <div>
                                        <img src="${this.getIcon16x16("hard_drive.png", "pd")}"/>
                                    </div>
                                    <div>
                                        <i class="icofont-caret-right"/>
                                    </div>
                                </div>
                            </div>
                            <div role="path" class="${Resources.CssClass.LocationPath}">
                            </div>
                        </div>
                    </div>`;
                }
                onInit(e) {
                    super.onInit(e);
                    this.setupSerivceCallSubscriber();
                    this.history = new PDJS.Core.Resources.History({
                        add: (e) => {
                            this.enableButton(this.prevButtonNode, e.canMovePrev);
                            this.enableButton(this.nextButtonNode, e.canMoveNext);
                        },
                        move: (e) => {
                            this.enableButton(this.prevButtonNode, e.canMovePrev);
                            this.enableButton(this.nextButtonNode, e.canMoveNext);
                            this.publishChangeEvent(e.item.folderId, false);
                        }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.pathNode.on("click", `.${Resources.CssClass.LocationPathItem}:not(:last-child)`, _.bind(this.item_onClick, this));
                    this.prevButtonNode.on("click", (e) => {
                        this.history.prev();
                    });
                    this.nextButtonNode.on("click", (e) => {
                        this.history.next();
                    });
                    this.m_overflowMenu = new Resources.LocationMenu({
                        anchor: this.rootButtonNode
                    });
                    this.subscriptions.add(Resources.EventsHub.locationChangeSubscribe(_.bind(this.onChange, this)));
                    this.subscriptions.add(Resources.EventsHub.locationChangedSubscribe(_.bind(this.onChanged, this)));
                    this.onChanged({
                        folderId: null,
                        folderPath: [{
                                icon: "folders.png",
                                id: Jade.Guid.empty(),
                                name: "Resources",
                                parentId: null,
                                path: "/Resources",
                                role: "folder"
                            }],
                        record: true,
                        source: "location"
                    });
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.overflowMenu) {
                        this.overflowMenu.destroy();
                    }
                }
                onChange(e) {
                    this.pathNode.empty();
                    this.pathNode.addClass("-pd-state-loading");
                }
                onChanged(e) {
                    this.path = e.folderPath;
                    this.renderPath(e.folderPath);
                    if (e.record !== false) {
                        this.history.add(new PDJS.Core.Resources.HistoryItem({
                            folderId: e.folderId,
                            folderPath: e.folderPath
                        }));
                    }
                }
                item_onClick(e) {
                    let data = $(e.currentTarget).data("item");
                    this.publishChangeEvent(data.id);
                }
                publishChangeEvent(folderId, shouldRecord = true) {
                    Resources.EventsHub.locationChangePublish({
                        folderId: folderId,
                        source: "location",
                        record: shouldRecord
                    });
                }
                enableButton(button, enable) {
                    enable ?
                        button.removeAttr("disabled") :
                        button.attr("disabled", "");
                }
                renderPath(path) {
                    let item = null;
                    this.pathNode.empty();
                    this.pathNode.removeClass("-pd-state-loading");
                    path.map(part => {
                        item = $(this.renderPathItem(part));
                        item.data("item", part);
                        this.pathNode.append(item);
                    });
                    this.resize();
                }
                renderPathItem(item) {
                    return `<div class="${Resources.CssClass.LocationPathItem}" data-id="${item.id}">
                    <div>${item.name}</div>
                    <div>
                        <i class="icofont-caret-right"/>
                    </div>
                </div>`;
                }
                getIcon16x16(icon, set = "pdv2") {
                    return Jade.IconSet.get(set)
                        .resolve(icon, Jade.IconSetSizeSpecificDirectory.x16);
                }
                getIconMisc(icon, set = "pdv2") {
                    return Jade.IconSet.get(set)
                        .resolve(icon, Jade.IconSetSizeSpecificDirectory.misc);
                }
                setupSerivceCallSubscriber() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    this.subscriptions.add(Resources.EventsHub.locationChangeSubscribe((e) => {
                        service.getFolderPath({
                            folderId: e.folderId,
                            success: (args) => {
                                Resources.EventsHub.locationChangedPublish({
                                    folderId: e.folderId,
                                    folderPath: args.data,
                                    source: e.source,
                                    record: e.record
                                });
                            }
                        });
                    }));
                }
            }
            Resources.Location = Location;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class LocationMenu {
                constructor(options) {
                    this.m_anchor = options.anchor;
                    this.init();
                }
                get menu() {
                    return this.m_menu;
                }
                set menu(value) {
                    this.m_menu = value;
                }
                get anchor() {
                    return this.m_anchor;
                }
                set anchor(value) {
                    this.m_anchor = value;
                }
                get events() {
                    return PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events;
                }
                get menuItemNodes() {
                    return this.menu.element.children("UL > LI");
                }
                addMenuItems(items) {
                    items.forEach(item => {
                        let menuItem = this.createMenuItem(item);
                        this.menu.append(menuItem);
                    });
                }
                clear() {
                    this.menuItemNodes.each((index, element) => {
                        this.menu.remove(element);
                    });
                }
                destroy() {
                    if (this.menu) {
                        this.menu.destroy();
                    }
                }
                init() {
                    this.menu = $("<ul></ul>").kendoContextMenu({
                        alignToAnchor: true,
                        target: this.anchor,
                        showOn: "click",
                        select: _.bind(this.onMenuItemSelect, this),
                    }).data("kendoContextMenu");
                    this.clear();
                }
                onMenuItemSelect(e) {
                    let id = $(e.item)
                        .find(".-pd-menu-item")
                        .data("id");
                    this.publishChangeEvent(id);
                }
                createMenuItem(item) {
                    var imageUrl = Jade.IconSet.get("pd")
                        .resolve("folder.png", Jade.IconSetSizeSpecificDirectory.x16);
                    return {
                        id: item.id,
                        encoded: false,
                        text: `<span data-id='${item.id}' class="-pd-menu-item">
                            <span class='-pd-menu-icon'>
                                <img src="${imageUrl}">
                            </span>
                            <span class='-pd-menu-text'>
                                ${item.name}
                            </span>
                        </span>`
                    };
                }
                publishChangeEvent(folderId) {
                    Resources.EventsHub.locationChangePublish({
                        folderId: folderId,
                        source: "location",
                        record: true
                    });
                }
            }
            Resources.LocationMenu = LocationMenu;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskAlertDialogOf extends Jade.UI.Dialogs.DialogOf {
            constructor(options) {
                super(options);
            }
            get alert() {
                return this.state.get("alert", { code: -1 });
            }
        }
        Shared.TaskAlertDialogOf = TaskAlertDialogOf;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskAlertDialog extends Shared.TaskAlertDialogOf {
            constructor(options) {
                super(options);
            }
            static open(options) {
                return new TaskAlertDialog(options);
            }
        }
        Shared.TaskAlertDialog = TaskAlertDialog;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ConflictDialog extends PDJS.Shared.TaskAlertDialogOf {
                constructor(options) {
                    super(options);
                }
                get alert() {
                    return super.alert;
                }
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get srcNode() {
                    return this.node.find("span[role=src]");
                }
                get dstNode() {
                    return this.node.find("span[role=src]");
                }
                get repeatNode() {
                    return this.node.find("div[role=repeat] input[type=checkbox]");
                }
                get isFileConflict() {
                    return this.alert.code == 1;
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-resources-conflict-dialog">
                        <div role="header">${this.getHeaderText()}</div>
                        <div role="conflict">${this.getConflictText()}</div>
                        <div role="list"></div>
                        <div role="repeat">
                            <label>
                                <div>
                                    <input type="checkbox">
                                </div>
                                <div>
                                    Do this for all conflicts like this.
                                </div>
                            </label>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Replace or Skip Files",
                        actions: [],
                        width: "500px",
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.init_list();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.center();
                }
                init_list() {
                    this.list = new PDJS.Shared.UI.Controls.ListView({
                        insertAt: "div[role=list]",
                        data: [
                            {
                                value: 2,
                                label: this.getResolveText(),
                                icon: this.getIcon("check.png")
                            },
                            {
                                value: 1,
                                label: this.getSkipText(),
                                icon: this.getIcon("undo.png")
                            },
                            {
                                value: 0,
                                label: "Cancel the move operation",
                                icon: this.getIcon("delete.png")
                            }
                        ],
                        createItem: (e) => {
                            return new PDJS.Shared.UI.Controls.ListViewItem(e);
                        },
                        change: (e) => {
                            var _a, _b;
                            if (e.count > 0) {
                                this.close({
                                    name: "ok",
                                    data: {
                                        action: (_b = (_a = e.first()) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.value,
                                        repeat: this.repeatNode.is(":checked")
                                    }
                                });
                            }
                        }
                    });
                    this.controls.add(this.list);
                }
                getHeaderText() {
                    let srcPath = _.trim(this.alert.tags.sourcepath, "/");
                    let dstPath = _.trim(this.alert.tags.targetpath, "/");
                    let srcName = _.first(srcPath.split(`/`));
                    let dstName = _.first(dstPath.split(`/`));
                    return `Moving item from 
                    <span title="${srcPath}" role="src">${srcName}</span> 
                    to
                    <span title="${dstPath}" role="dst">${dstName}</span>`;
                }
                getConflictText() {
                    return this.isFileConflict ?
                        `The destination already has a file named "${this.alert.tags.name}"` :
                        `The destination already has a folder named "${this.alert.tags.name}"`;
                }
                getIcon(icon) {
                    return Jade.IconSet.get("pdjs")
                        .resolve(icon, Jade.IconSetSizeSpecificDirectory.x24);
                }
                getResolveText() {
                    return this.isFileConflict ?
                        "Replace the file in the destination" :
                        "Merge the contents of the folders";
                }
                getSkipText() {
                    return this.isFileConflict ?
                        "Skip this file" :
                        "Skip this folder";
                }
                static open(options) {
                    return new ConflictDialog(options);
                }
            }
            Resources.ConflictDialog = ConflictDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class NewFileDialog extends Jade.UI.Dialogs.DialogOf {
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get selection() {
                    return this.state.get("selection");
                }
                set selection(value) {
                    this.state.set("selection", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-resources-new-file-dialog">
                    <div role="label">Select the type of new file to create:</div>
                    <div data-controls></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "New | File",
                        width: "500px",
                        maximized: false,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.selection == null ?
                        this.okButtonNode.attr("disabled", "disabled") :
                        this.okButtonNode.removeAttr("disabled");
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        height: "270px",
                        data: Resources.EditableTypes.list,
                        binding: {
                            icon: "icon",
                            label: "name",
                            value: "type"
                        },
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                        showCheckboxes: false,
                        change: (e) => {
                            var _a, _b;
                            if (e.first()) {
                                this.selection = (_b = (_a = e.first()) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.toJSON();
                            }
                        },
                        dblClick: (e) => {
                            var _a, _b;
                            this.selection = (_b = (_a = e.first()) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.toJSON();
                            this.closeAndReturn();
                        },
                        createItem: (e) => {
                            return new Resources.NewFileDialogItem(e);
                        }
                    });
                    this.controls.add(this.m_list);
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.selection != null) {
                        this.close({
                            name: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No file type has been selected. Select a file type and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                static open(options) {
                    return new NewFileDialog(options);
                }
            }
            Resources.NewFileDialog = NewFileDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListViewItemBase extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_data = new Controls.ListViewItemData(_.extend(options.data, {
                            $binding: options.binding,
                            $iconSet: this.iconSet,
                            $stateChanged: () => {
                                this.onStateChanged();
                            }
                        }));
                        this.data.onStateChangeCallback = () => {
                            this.onStateChanged();
                        };
                    }
                    get checked() {
                        return this.state.get("checked", true);
                    }
                    set checked(value) {
                        this.state.set("checked", value);
                    }
                    get data() {
                        return this.m_data;
                    }
                    get selected() {
                        return this.state.get("selected", false);
                    }
                    set selected(value) {
                        this.state.set("selected", value);
                    }
                    get value() {
                        return this.data.value;
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    get checkNode() {
                        return this.node
                            .children("div[role=check]")
                            .children("input");
                    }
                    get checkOnSelect() {
                        return this.state.set("checkOnSelect", false);
                    }
                    get checkVisible() {
                        return this.state.get("checkVisible", false);
                    }
                    get checkCallback() {
                        return this.state.get("check", () => { });
                    }
                    get removeCallback() {
                        return this.state.get("remove", () => { });
                    }
                    get removeNode() {
                        return this.node.find("div[role=remove] > i");
                    }
                    get removeVisible() {
                        return this.state.get("removeVisible", false);
                    }
                    get selectCallback() {
                        return this.state.get("select", () => { });
                    }
                    get selectMode() {
                        return this.state.get("selectMode", Controls.ListViewSelectMode.single);
                    }
                    get selectOnCheck() {
                        return this.state.set("selectOnCheck", false);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get templateNode() {
                        return this.node.children("div[role=template]");
                    }
                    get iconSet() {
                        return this.state.get("iconSet", "pdjs");
                    }
                    template() {
                        return `<div role="item" class="-pdjs-list-view-item-base">
                        <div role="check">
                            <input type="checkbox" tabIndex="${this.tabIndex}" />
                        </div>
                        <div role="template">${this.templateContent()}</div>
                        <div role="remove">
                            <i class="icofont-close"></i>
                        </div>
                    </div>`;
                    }
                    toJSON() {
                        return this.data.toJSON();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.attr("data-value", this.data.value);
                        this.checkVisible ?
                            this.checkNode.show() :
                            this.checkNode.hide();
                        this.visible ?
                            this.node.show() :
                            this.node.hide();
                        !this.removeVisible ?
                            this.removeNode.remove() : null;
                        this.removeNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onRemove, this));
                        this.checkNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onCheck, this));
                        this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.onSelect, this));
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.visible ?
                            this.node.show() :
                            this.node.hide();
                        this.node.attr("data-selected", this.selected ? "true" : "false");
                        this.checkNode.prop("checked", this.checked);
                    }
                    templateContent() {
                        return `<div class="-pdjs-list-view-item">
                        <div role="label">${this.data.label}</div>
                    </div>`;
                    }
                    onRemove(e) {
                        this.removeCallback(this);
                    }
                    onCheck(e) {
                        e.stopPropagation();
                        this.checked = this.checkNode.prop("checked");
                        this.checkCallback(this);
                        if (this.selectOnCheck) {
                            this.onSelect(e);
                        }
                    }
                    onSelect(e) {
                        if (this.selectMode != Controls.ListViewSelectMode.none) {
                            this.selectCallback(this, e.ctrlKey);
                        }
                        if (this.checkOnSelect) {
                            this.onCheck(e);
                        }
                    }
                }
                Controls.ListViewItemBase = ListViewItemBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListViewItem extends Controls.ListViewItemBase {
                    constructor(options) {
                        super(options);
                    }
                    get iconNode() {
                        return this.templateNode.find("div[role=icon] > img");
                    }
                    get iconPath() {
                        return this.resolveIconPath();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let hasIcon = !Jade.String
                            .isNullOrWhiteSpace(this.data.icon);
                        hasIcon ?
                            this.iconNode.show() :
                            this.iconNode.hide();
                        if (hasIcon) {
                            this.iconNode.attr("src", this.iconPath);
                        }
                    }
                    templateContent() {
                        return `<div class="-pdjs-list-view-item">
                        <div role="icon">
                            <img />
                        </div>
                        <div role="label">${this.data.label}</div>
                    </div>`;
                    }
                    resolveIconPath() {
                        let isFixed = _.startsWith(this.data.icon, "/");
                        let isVirtual = _.startsWith(this.data.icon, "~");
                        switch (true) {
                            case isFixed:
                                return this.data.icon;
                            case isVirtual:
                                return Jade.Path.resolve(this.data.icon);
                            default:
                                return Jade.IconSet.get(this.iconSet)
                                    .resolve(this.data.icon, Jade.IconSetSizeSpecificDirectory.x16);
                        }
                    }
                }
                Controls.ListViewItem = ListViewItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class NewFileDialogItem extends PDJS.Shared.UI.Controls.ListViewItem {
                resolveIconPath() {
                    return Jade.IconSet.get("pdjs")
                        .resolve(this.data.icon, Jade.IconSetSizeSpecificDirectory.x32);
                }
            }
            Resources.NewFileDialogItem = NewFileDialogItem;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get browser() {
                    return this.m_browser;
                }
                set browser(value) {
                    this.m_browser = value;
                }
                get explorer() {
                    return this.m_explorer;
                }
                set explorer(value) {
                    this.m_explorer = value;
                }
                get extensions() {
                    return this.state.get("extensions", []);
                }
                get input() {
                    return this.m_input;
                }
                set input(value) {
                    this.m_input = value;
                }
                get location() {
                    return this.m_location;
                }
                set location(value) {
                    this.m_location = value;
                }
                get nodes() {
                    return this.state.get("nodes", []);
                }
                set nodes(value) {
                    this.state.set("nodes", value);
                }
                get selectionMode() {
                    return this.state.get("selectionMode", PD.Web.UI.Controls.GridSelectionMode.single);
                }
                set selectionMode(value) {
                    this.state.set("selectionMode", value);
                }
                get splitter() {
                    return this.m_splitter;
                }
                set splitter(value) {
                    this.m_splitter = value;
                }
                get splitterNode() {
                    return this.node.find("div.-pd-minimal-splitter");
                }
                get toolbar() {
                    return this.m_toolbar;
                }
                set toolbar(value) {
                    this.m_toolbar = value;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                get result() {
                    return this.m_result;
                }
                set result(value) {
                    this.m_result = value;
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-resources-selection-dialog">
                    <div role="actions">
                        <div role="location"></div>
                        <div role="toolbar"></div>
                    </div>
                    <div role="content">
                        <div class="-pd-minimal-splitter">
                            <div data-role="explorer"></div>
                            <div data-role="browser"></div>
                        </div>
                    </div>
                    <div role="input">
                    </div>
                    <div role="deck">
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok" disabled>OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                onResize() {
                    if (this.location) {
                        this.location.resize();
                    }
                }
                getDefaultOptions() {
                    return {
                        height: "500px",
                        width: "800px",
                        maximized: false,
                        resizable: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    this.subscriptions.add(Resources.EventsHub.resourceHighlightSubscribe(_.bind(this.onResourceHighlight, this)));
                    let service = new PDJS.Services.Resources.ResourcesService();
                    service.getIndex({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.nodes = e.data.nodes;
                            this.explorer_init();
                            this.browser_init();
                            this.onDialogPrepared();
                        }
                    });
                    this.location_init();
                    this.input_init();
                    this.splitter_init();
                    this.toolbar_init();
                    this.subscriptions.add(Resources.EventsHub.locationChangedSubscribe((e) => {
                        this.updateCommandState();
                    }));
                    this.subscriptions.add(Resources.EventsHub.resourceHighlightSubscribe((e) => {
                        this.updateCommandState();
                    }));
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter && this.splitter.element) {
                        this.splitter.destroy();
                    }
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.result == null ?
                        this.okButtonNode.attr("disabled", "disabled") :
                        this.okButtonNode.removeAttr("disabled");
                }
                closeAndReturn() {
                }
                onResourceHighlight(e) {
                }
                onInputChanged() {
                }
                onDialogPrepared() {
                }
                browser_init() {
                    this.browser = new Resources.Browser({
                        insertAt: "div[data-role=browser]",
                        extensions: this.extensions,
                        viewStateId: this.viewStateId,
                        selectionMode: this.selectionMode
                    });
                    this.controls.add(this.browser);
                }
                explorer_init() {
                    this.explorer = new Resources.Explorer({
                        insertAt: "div[data-role=explorer]",
                        nodes: this.nodes
                    });
                    this.controls.add(this.explorer);
                }
                location_init() {
                    this.location = new Resources.Location({
                        insertAt: "div[role=location]"
                    });
                    this.controls.add(this.location);
                }
                input_init() {
                    this.input = new Resources.Input({
                        insertAt: "div[role=input]",
                        changed: () => {
                            this.onInputChanged();
                        },
                        enter: () => {
                            this.closeAndReturn();
                        }
                    });
                    this.controls.add(this.input);
                }
                splitter_init() {
                    this.splitter = this.splitterNode.kendoSplitter({
                        orientation: "horizontal",
                        panes: [{ size: "250px" }, {}],
                        resize: _.debounce(() => {
                            this.splitter.resize();
                        }, 100)
                    }).data("kendoSplitter");
                }
                toolbar_init() {
                    this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Resources.ResourceDialogToolbar()]
                    });
                    this.controls.add(this.toolbar);
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                updateCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/resources": {
                            $browser: this.browser,
                            $explorer: this.explorer,
                            $location: this.location,
                            isDialog: true
                        }
                    }, { force: true });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/resources/context-menu": {
                            $browser: this.browser,
                            $explorer: this.explorer,
                            $location: this.location,
                            isDialog: true
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new ResourceDialog(options);
                }
            }
            Resources.ResourceDialog = ResourceDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class OpenFileDialog extends Resources.ResourceDialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "File | Open"
                    }));
                    this.m_selectedFiles = [];
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                closeAndReturn() {
                    this.openFile();
                }
                onInit() {
                    this.selectionMode = PD.Web.UI.Controls.GridSelectionMode.multiple;
                }
                onDialogPrepared() {
                    Resources.EventsHub.locationChangePublish({
                        folderId: this.folderId,
                        record: true
                    });
                    this.subscriptions.add(Resources.EventsHub.resourceSelectSubscribe((e) => {
                        this.onResourceSelect(e);
                    }));
                    this.input.focus();
                    this.input.readonly = true;
                    this.selectFolderInExplorer();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.input.label = "File Name(s)";
                }
                onInputChanged() {
                    super.onInputChanged();
                    this.setOkButtonState();
                }
                onResourceHighlight(e) {
                    super.onResourceHighlight(e);
                    this.setSelections(e.items);
                }
                onResourceSelect(e) {
                    this.setSelections(e.items);
                    this.openFile();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.setOkButtonState();
                }
                setOkButtonState() {
                    Jade.String.isNullOrWhiteSpace(this.input.value) ?
                        this.okButtonNode.attr("disabled", "disabled") :
                        this.okButtonNode.removeAttr("disabled");
                }
                openFile() {
                    let files = this.m_selectedFiles;
                    this.close();
                    let routes = this.m_selectedFiles.map(file => {
                        return `#/module/resources-editor/${file.id}`;
                    });
                    Manage.ModuleLoader.load(routes);
                }
                setSelections(items) {
                    this.m_selectedFiles = [];
                    items.filter(item => item.role == "file")
                        .forEach(item => {
                        this.m_selectedFiles.push(item);
                    });
                    let names = this.m_selectedFiles
                        .map(item => item.name);
                    this.input.value = names.length > 1 ?
                        `"${names.join(`" "`)}"` : names.join(``);
                }
                selectFolderInExplorer() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    service.getFolderPath({
                        folderId: this.folderId,
                        success: (e) => {
                            let ids = e.data.map(item => item.id);
                            this.explorer.refresh({
                                expanded: ids,
                                success: () => {
                                    this.explorer.select(this.folderId);
                                }
                            });
                        }
                    });
                }
                static open(options) {
                    return new OpenFileDialog(options);
                }
            }
            Resources.OpenFileDialog = OpenFileDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class ResourceDialogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/resources:folder/new"
                    }));
                }
            }
            Resources.ResourceDialogToolbar = ResourceDialogToolbar;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class SaveFileDialog extends Resources.ResourceDialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "File | Save"
                    }));
                }
                get fileName() {
                    return this.state.get("fileName", "");
                }
                get fileContent() {
                    return this.state.get("fileContent", "");
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                closeAndReturn() {
                    this.saveFile();
                }
                onInit() {
                    this.selectionMode = PD.Web.UI.Controls.GridSelectionMode.multiple;
                }
                onDialogPrepared() {
                    Resources.EventsHub.locationChangePublish({
                        folderId: this.folderId,
                        record: true
                    });
                    this.input.focus();
                    this.input.value = this.fileName;
                    this.browser.selectionMode =
                        PD.Web.UI.Controls.GridSelectionMode.multiple;
                    this.selectFolderInExplorer();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.input.label = "File Name";
                }
                onInputChanged() {
                    super.onInputChanged();
                    this.setOkButtonState();
                }
                onResourceHighlight(e) {
                    super.onResourceHighlight(e);
                    let item = _.first(e.items);
                    if ((item === null || item === void 0 ? void 0 : item.role) != "file") {
                        return;
                    }
                    if (!Jade.String.isNullOrWhiteSpace(item.name)) {
                        this.input.value = `${item.name}`;
                    }
                    this.input.focus();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.setOkButtonState();
                }
                setOkButtonState() {
                    Jade.String.isNullOrWhiteSpace(this.input.value) ?
                        this.okButtonNode.attr("disabled", "disabled") :
                        this.okButtonNode.removeAttr("disabled");
                }
                saveFile() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    let folderId = this.explorer.getSelectedFolderId();
                    service.addTextFile({
                        folderId: folderId,
                        content: this.fileContent || "",
                        name: this.input.value,
                        fileMode: PDJS.Services.Resources.DuplicateFileMode.Fail,
                        success: (e) => {
                            this.close({
                                name: "ok",
                                data: {
                                    fileId: e.data.id,
                                    fileName: this.input.value,
                                    folderId: folderId,
                                    folderPath: this.location.getPath()
                                }
                            });
                        },
                        error: (e) => {
                            let errors = e.xhr.responseJSON;
                            let error = _.first(errors);
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                message: error === null || error === void 0 ? void 0 : error.message,
                                select: (e) => {
                                    e.close();
                                    setTimeout(() => { this.input.focus(); }, 150);
                                }
                            });
                            e.errorHandled = error != null;
                        }
                    });
                }
                selectFolderInExplorer() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    service.getFolderPath({
                        folderId: this.folderId,
                        success: (e) => {
                            let ids = e.data.map(item => item.id);
                            this.explorer.refresh({
                                expanded: ids,
                                success: () => {
                                    this.explorer.select(this.folderId);
                                }
                            });
                        }
                    });
                }
                static open(options) {
                    return new SaveFileDialog(options);
                }
            }
            Resources.SaveFileDialog = SaveFileDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class SelectFileDialog extends Resources.ResourceDialog {
                constructor(options) {
                    super(_.extend({
                        title: "File | Select",
                        selectionMode: options.selectionMode != null ?
                            options.selectionMode :
                            PD.Web.UI.Controls.GridSelectionMode.single
                    }, options));
                    this.m_selectedFiles = [];
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                closeAndReturn() {
                    this.returnFiles();
                }
                onDialogPrepared() {
                    Resources.EventsHub.locationChangePublish({
                        folderId: this.folderId,
                        record: true
                    });
                    this.subscriptions.add(Resources.EventsHub.resourceSelectSubscribe((e) => {
                        this.onResourceSelect(e);
                    }));
                    this.input.focus();
                    this.input.readonly = true;
                    this.selectFolderInExplorer();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.input.label = "File Name(s)";
                }
                onInputChanged() {
                    super.onInputChanged();
                    this.setOkButtonState();
                }
                onResourceHighlight(e) {
                    super.onResourceHighlight(e);
                    this.setSelections(e.items);
                }
                onResourceSelect(e) {
                    this.setSelections(e.items);
                    this.returnFiles();
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.setOkButtonState();
                }
                setOkButtonState() {
                    Jade.String.isNullOrWhiteSpace(this.input.value) ?
                        this.okButtonNode.attr("disabled", "disabled") :
                        this.okButtonNode.removeAttr("disabled");
                }
                returnFiles() {
                    this.close({
                        name: "ok",
                        data: this.m_selectedFiles
                    });
                }
                setSelections(items) {
                    this.m_selectedFiles = [];
                    items.filter(item => item.role == "file")
                        .forEach(item => {
                        item.path = `${this.location.getPath()}/${item.name}`;
                        this.m_selectedFiles.push(item);
                    });
                    let names = this.m_selectedFiles
                        .map(item => item.name);
                    this.input.value = names.length > 1 ?
                        `"${names.join(`" "`)}"` : names.join(``);
                }
                selectFolderInExplorer() {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    service.getFolderPath({
                        folderId: this.folderId,
                        success: (e) => {
                            let ids = e.data.map(item => item.id);
                            this.explorer.refresh({
                                expanded: ids,
                                success: () => {
                                    this.explorer.select(this.folderId);
                                }
                            });
                        }
                    });
                }
                static open(options) {
                    return new SelectFileDialog(options);
                }
            }
            Resources.SelectFileDialog = SelectFileDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class UploadZipDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                get uploadName() {
                    return this.state.get("uploadName");
                }
                set uploadName(value) {
                    this.state.set("uploadName", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                getDefaultOptions() {
                    return {
                        title: "Upload | Zip File",
                        width: "400px",
                        maximized: false,
                        resizable: true
                    };
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-upload-zip-dialog">
                        <div role="text">Select a ".zip" file to upload and extract its contents to the target folder.</div>
                        <div role="progress"></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok" disabled>Extract</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                uploadId: this.uploadId,
                                uploadName: this.uploadName
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=progress]",
                        onFileSelected: (e) => {
                        },
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.uploadName = e.name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options) {
                    return new UploadZipDialog(options);
                }
            }
            Resources.UploadZipDialog = UploadZipDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class EditorCommand extends Jade.Command {
                    constructor() {
                        super({});
                        this.initialLoadComplete = false;
                        this.state.set("$editor", null);
                        this.state.set("$module", null);
                        this.state.set("fileId", null);
                        this.state.set("fileName", null);
                        this.state.set("folderId", null);
                        this.state.set("moduleId", null);
                    }
                    get editor() {
                        return this.state.get("$editor");
                    }
                    get module() {
                        return this.state.get("$module");
                    }
                    get fileId() {
                        return this.state.get("fileId");
                    }
                    set fileId(value) {
                        this.state.set("fileId", value);
                    }
                    get fileName() {
                        return this.state.get("fileName");
                    }
                    set fileName(value) {
                        this.state.set("fileName", value);
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    set folderId(value) {
                        this.state.set("folderId", value);
                    }
                    get moduleId() {
                        return this.state.get("moduleId");
                    }
                    set moduleId(value) {
                        this.state.set("moduleId", value);
                    }
                    get editorSettings() {
                        return PDJS.Shared.Coding.CodeEditorEnvironment.current;
                    }
                    setState(state) {
                        super.setState(state);
                        if (this.editor != null && !this.initialLoadComplete) {
                            this.onInitialLoad();
                        }
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/manage/resources/editor": {
                                editor: this.editor,
                                fileId: this.fileId,
                                fileName: this.fileName,
                                folderId: this.folderId,
                                moduleId: this.moduleId
                            }
                        }, { force: true });
                    }
                    onInitialLoad() {
                    }
                }
                Editor.EditorCommand = EditorCommand;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class OpenCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "file/open",
                            label: "Open",
                            tooltip: "Open another file.",
                            icon: "folder_open_document.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Manage.Resources.OpenFileDialog.open({
                            extensions: Resources.EditableTypes.extensions,
                            folderId: this.folderId
                        });
                    }
                }
                Editor.OpenCommand = OpenCommand;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class SaveCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "file/save",
                            label: "Save",
                            tooltip: "Save changes made to the file.",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.editor && this.editor.content.changed;
                    }
                    execute(e) {
                        this.fileId == null ?
                            this.saveDialog() :
                            this.save();
                    }
                    save() {
                        let service = new PDJS.Services.Resources.ResourcesService();
                        service.saveTextFile({
                            fileId: this.fileId,
                            content: this.editor.content.getValue() || "",
                            success: (e) => {
                                this.module.settings.hasChanges = false;
                                PDJS.Shared.MessageStack
                                    .instance
                                    .success(`<b>${this.fileName}<b/> saved successfully.`);
                            }
                        });
                    }
                    saveDialog() {
                        PDJS.Manage.Resources.SaveFileDialog.open({
                            extensions: [Jade.Path.getFileExtension(this.fileName)],
                            fileName: this.fileName,
                            fileContent: this.editor.content.getValue(),
                            folderId: this.folderId,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    Editor.EventsHub.saveAsPublish({
                                        fileId: e.fileId,
                                        fileName: e.fileName,
                                        folderId: e.folderId,
                                        folderPath: e.folderPath
                                    });
                                }
                            }
                        });
                    }
                }
                Editor.SaveCommand = SaveCommand;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class SaveAsCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "file/save-as",
                            label: "Save As",
                            tooltip: "Create a new file using the contents of this file.",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    setState(state) {
                        super.setState(state);
                        this.visible = !Jade.Guid.isNullOrEmpty(this.fileId);
                    }
                    execute(e) {
                        PDJS.Manage.Resources.SaveFileDialog.open({
                            title: "File | Save As",
                            extensions: [Jade.Path.getFileExtension(this.fileName)],
                            fileName: this.fileName,
                            fileContent: this.editor.content.getValue(),
                            folderId: this.folderId,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    Editor.EventsHub.saveAsPublish({
                                        fileId: e.fileId,
                                        fileName: e.fileName,
                                        folderId: e.folderId,
                                        folderPath: e.folderPath
                                    });
                                }
                            }
                        });
                    }
                }
                Editor.SaveAsCommand = SaveAsCommand;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class EditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/resources/editor");
                    }
                    registerCommands(e) {
                        e.commands.add(new Editor.OpenCommand());
                        e.commands.add(new Editor.SaveCommand());
                        e.commands.add(new Editor.SaveAsCommand());
                    }
                }
                Editor.EditorCommands = EditorCommands;
                Jade.CommandGroups.add(EditorCommands);
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class EditorModule extends Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get editor() {
                        return this.m_editor;
                    }
                    set editor(value) {
                        this.m_editor = value;
                    }
                    get errorCallback() {
                        return this.state.get("error", () => { });
                    }
                    get toolbar() {
                        return this.m_toolbar;
                    }
                    set toolbar(value) {
                        this.m_toolbar = value;
                    }
                    get fileId() {
                        return this.state.get("fileId", null);
                    }
                    set fileId(value) {
                        this.state.set("fileId", value);
                    }
                    get fileName() {
                        return this.state.get("fileName", null);
                    }
                    set fileName(value) {
                        this.state.set("fileName", value);
                    }
                    get fileType() {
                        return this.state.get("fileType", null);
                    }
                    set fileType(value) {
                        this.state.set("fileType", value);
                    }
                    get folderId() {
                        return this.state.get("folderId", null);
                    }
                    set folderId(value) {
                        this.state.set("folderId", value);
                    }
                    get folderPath() {
                        return this.state.get("folderPath", null);
                    }
                    set folderPath(value) {
                        this.state.set("folderPath", value);
                    }
                    template() {
                        return `<div class="-pdjs-manage-resources-editor">
                        <div data-role="toolbar"></div>
                        <div data-role="editor"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.toolbar_init();
                        this.editor_init();
                        Editor.EventsHub.saveAsSubscribe((e) => {
                            this.state.set({
                                fileId: e.fileId,
                                fileName: e.fileName,
                                folderId: e.folderId,
                                folderPath: e.folderPath
                            });
                            let newRoute = `#/module/resources-editor/${this.fileId}`;
                            window.history.replaceState({}, "", newRoute);
                            this.settings.targetId = this.fileId;
                            this.settings.route = newRoute;
                            this.settings.hasChanges = false;
                            this.settings.label = this.fileName;
                            PDJS.Manage.Resources.
                                EventsHub.folderContentChangedPublish({
                                folderId: e.folderId
                            });
                            this.updateCommandState();
                        });
                        this.addSubscribers();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.registerKeyboardShortcuts();
                        this.editor.autocomplete.enabled = false;
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.parseTargetId();
                    }
                    onModuleFocus(e) {
                        super.onModuleFocus(e);
                        if (this.editor) {
                            this.editor.focus();
                        }
                    }
                    onModuleLoad(e) {
                        super.onModuleLoad(e);
                        if (this.fileId != null) {
                            e.addStep(() => this.loadExistingResource());
                        }
                        if (this.fileId == null && this.fileType != null) {
                            e.addStep(() => this.loadNewResource());
                        }
                        if (this.fileId == null && this.fileType == null) {
                            e.addError("Invalid resource ID was provided.");
                        }
                    }
                    addSubscribers() {
                        this.subscriptions.add(Editor.EventsHub.resourceRenamedSubscribe(e => {
                            if (this.settings.targetId == e.id) {
                                this.settings.label = e.name;
                            }
                        }));
                    }
                    editor_init() {
                        this.editor = new PDJS.Shared.Coding.CodeEditor({
                            insertAt: "div[data-role=editor]",
                            change: () => {
                                this.settings.hasChanges = true;
                                this.updateCommandState();
                            }
                        });
                        this.controls.add(this.editor);
                    }
                    loadNewResource() {
                        return new Promise((resolve, reject) => {
                            let service = new PDJS.Services.Resources.ResourcesService();
                            service.getFolderPath({
                                folderId: this.folderId,
                                success: (e) => {
                                    let path = "";
                                    let type = Resources.EditableTypes.getType(this.fileType);
                                    e.data.forEach(item => {
                                        path += `/${item.name}`;
                                    });
                                    this.fileName = type.file;
                                    this.settings.label = type.file;
                                    this.editor.settings.setStyle(type.mime);
                                    this.editor.load("");
                                    this.updateCommandState();
                                    resolve();
                                },
                                error: (e) => { reject(e.xhr); }
                            });
                        });
                    }
                    loadExistingResource() {
                        return new Promise((resolve, reject) => {
                            let service = new PDJS.Services.Resources.ResourcesService();
                            service.loadTextFile({
                                fileId: this.fileId,
                                success: (e) => {
                                    this.editor.load(e.data.content);
                                    this.editor.settings.setStyle(e.data.mimeType);
                                    this.editor.content.resetChangedState();
                                    this.state.set({
                                        fileId: e.data.id,
                                        fileName: e.data.name,
                                        fileType: Jade.Path.getFileExtension(e.data.name).toLowerCase(),
                                        folderId: e.data.folderId,
                                        folderPath: e.data.folderPath
                                    });
                                    this.settings.label = this.fileName;
                                    this.updateCommandState();
                                    resolve();
                                },
                                error: (e) => {
                                    reject(e.xhr);
                                    e.errorHandled = true;
                                }
                            });
                        });
                    }
                    parseTargetId() {
                        let isTargetIdGuid = Jade.Guid.isGuid(this.settings.targetId);
                        if (isTargetIdGuid) {
                            this.fileId = this.settings.targetId;
                            return;
                        }
                        let parts = this.settings
                            .targetId.toLowerCase().split(",");
                        if (parts.length > 1) {
                            this.fileType = parts[0];
                            this.folderId = parts[1];
                        }
                    }
                    registerKeyboardShortcuts() {
                        let keys = PDJS.Application
                            .instance
                            .contexts
                            .current
                            .hotkeys;
                        keys.simple_combo("ctrl s", () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/resources/editor:file/save");
                        });
                        keys.simple_combo("ctrl o", () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/resources/editor:file/open");
                        });
                    }
                    toolbar_init() {
                        this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[data-role=toolbar]",
                            segments: [new Editor.EditorToolbar(), new PDJS.Shared.Coding.CodeEditorToolbar({ target: "code" })]
                        });
                        this.controls.add(this.toolbar);
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/manage/resources/editor": {
                                $module: this,
                                $editor: this.editor,
                                fileId: this.fileId,
                                fileName: this.fileName,
                                folderId: this.folderId,
                                moduleId: this.settings.moduleId
                            }
                        }, { force: true });
                        this.editor.setCommandState();
                    }
                }
                Editor.EditorModule = EditorModule;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                class EditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/resources/editor";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:file/open`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:file/save`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:file/save-as`
                        }));
                    }
                }
                Editor.EditorToolbar = EditorToolbar;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                let Events;
                (function (Events) {
                    Events["SaveAs"] = "file/save-as";
                })(Events = Editor.Events || (Editor.Events = {}));
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            var Editor;
            (function (Editor) {
                let Events;
                (function (Events) {
                    Events["ResourceRenamed"] = "resources/resource-renamed";
                })(Events = Editor.Events || (Editor.Events = {}));
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static resourceRenamedPublish(args) {
                        this.global.publish(Events.ResourceRenamed, args);
                    }
                    static saveAsPublish(args) {
                        this.current.publish(Events.SaveAs, args);
                    }
                    static resourceRenamedSubscribe(handler) {
                        return this.global.subscribe(Events.ResourceRenamed, handler);
                    }
                    static saveAsSubscribe(handler) {
                        return this.current.subscribe(Events.SaveAs, handler);
                    }
                }
                Editor.EventsHub = EventsHub;
            })(Editor = Resources.Editor || (Resources.Editor = {}));
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            let Events;
            (function (Events) {
                Events["SearchScripts"] = "rules/search-scripts";
            })(Events = Rules.Events || (Rules.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static searchScriptsPublish(args) {
                    this.current.publish(Events.SearchScripts, args);
                }
                static searchScriptsSubscribe(handler) {
                    return this.current.subscribe(Events.SearchScripts, handler);
                }
            }
            Rules.EventsHub = EventsHub;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get scripts() {
                    return this.state.get("scripts", []);
                }
                set scripts(value) {
                    this.state.set("scripts", value);
                }
                load(scripts) {
                    this.scripts = scripts;
                    this.m_references.refresh(scripts);
                }
                template() {
                    return `<div class="-pdjs-manage-rules-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addReferences();
                    this.addSearchItems();
                    this.addLinks();
                }
                addLinks() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/rule-script-tags",
                        label: "Manage Script Tags"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/rule-script-tags",
                        label: "New Script Tag...",
                        click: (e) => {
                            PDJS.Manage.Rules.Tags.NewTagDialog.open();
                        }
                    }));
                }
                addSearchItems() {
                    let search = new Rules.ScriptSearch({});
                    this.controls.add(search);
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                }
                addReferences() {
                    this.m_references = new PDJS.Manage.Rules.ScriptReferences({
                        scripts: []
                    });
                    this.controls.add(this.m_references);
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                }
            }
            Rules.RulesActions = RulesActions;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.state.set("$actions", null);
                    this.state.set("$grid", null);
                }
                get actions() {
                    return this.state.get("$actions");
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                updateCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/manage/rules": {
                            $actions: this.actions,
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Rules.RulesCommand = RulesCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class ChangeTagsCommand extends Rules.RulesCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.selections.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Rules.Tags.ChangeTagsDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeTask(e);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity/change-tags",
                        tooltip: "Add/Remove tags from the selected rule scripts.",
                        label: "Change Tags",
                        icon: "tags.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeTask(items) {
                    let service = new PDJS.Services.Rules.RulesTagsService();
                    let add = items.filter(item => {
                        return item.type == PDJS.Shared.UI.Controls.TagItemType.add;
                    }).map(item => item.text);
                    let remove = items.filter(item => {
                        return item.type == PDJS.Shared.UI.Controls.TagItemType.remove;
                    }).map(item => item.text);
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Rule Scripts | Change Tags",
                        enableClose: false,
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.changeTags({
                                scriptIds: this.selectedIds,
                                add: add,
                                remove: remove,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            Rules.ChangeTagsCommand = ChangeTagsCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class DeleteScriptCommand extends Rules.RulesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "script/delete",
                        label: "Delete",
                        tooltip: "Delete the selected rule scripts.",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        title: "Delete Rule Script?",
                        message: `Delete the selected rule scripts?`,
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.executeDelete();
                            }
                        }
                    });
                }
                executeDelete() {
                    let service = new PDJS.Services.Rules.RulesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete Rule Scripts",
                        taskStart: (args) => {
                            service.deleteRuleScript({
                                scriptIds: this.selections.map(item => item.id),
                                success: (e) => {
                                    args.startPolling(e.data);
                                },
                                error: (e) => {
                                    args.abort(e);
                                }
                            });
                        },
                        taskSuccess: (args) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            Rules.DeleteScriptCommand = DeleteScriptCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class DownloadZipCommand extends Rules.RulesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "package/download",
                        label: "Download Zip",
                        tooltip: "Download a zip file that contains all rule scripts.",
                        icon: "folder_zip_down.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    let service = new PDJS.Services.Rules.RulesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Download | Rules",
                        autoCloseOnSuccess: true,
                        taskStart: (e) => {
                            service.getPackage({
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            PDJS.Shared.Downloader.downloadWithProgress({
                                url: "~/Manage/Rules/DownloadPackage",
                                params: {
                                    path: e.output.path,
                                    name: e.output.name
                                }
                            });
                        }
                    });
                }
            }
            Rules.DownloadZipCommand = DownloadZipCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class EditScriptCommand extends Rules.RulesCommand {
                get selection() {
                    return _.first(this.selections);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "script/edit",
                        label: "Edit",
                        tooltip: "Edit the properties of the selected rule script.",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length === 1;
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${this.selection.name}`,
                        height: "400px",
                        width: "450px",
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.grid.refresh();
                                PDJS.Manage.Rules.Editor.EventsHub.ruleRenamedPublish({
                                    id: e.target.id,
                                    name: e.target.name
                                });
                            }
                        }
                    });
                }
            }
            Rules.EditScriptCommand = EditScriptCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class NewScriptCommand extends Rules.RulesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "script/new",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new rule script.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Rule Script",
                        height: "400px",
                        width: "450px",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptArbiter"
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.grid.refresh({
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            Rules.NewScriptCommand = NewScriptCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class OpenScriptCommand extends Rules.RulesCommand {
                get selection() {
                    return _.first(this.selections);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "script/open",
                        label: "Open",
                        tooltip: "Open the selected rule scripts.",
                        icon: "nav_redo.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    let ids = this.selections
                        .map(selection => selection.id);
                    let routes = ids.map(id => {
                        return `#/module/rule-script-editor/${id}`;
                    });
                    Manage.ModuleLoader.load(routes, {
                        message: "Loading files, please wait...",
                        returnUrl: routes.length > 1 ? location.href : null,
                        complete: () => {
                            if (!Jade.String.isNullOrWhiteSpace(this.grid.searchTerm)) {
                                PDJS.Manage.Rules.Editor.EditorDirectivesHub.highlightSearchTerm(ids, {
                                    text: this.grid.searchTerm
                                });
                            }
                        }
                    });
                }
            }
            Rules.OpenScriptCommand = OpenScriptCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class UploadZipCommand extends Rules.RulesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "package/upload",
                        label: "Upload Zip",
                        tooltip: "Upload a zip file that contains rule scripts to be added or updated.",
                        icon: "folder_zip_up.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    PDJS.Manage.Rules.UploadZipDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeServiceCall(e.uploadId);
                            }
                        }
                    });
                }
                executeServiceCall(uploadId) {
                    let service = new PDJS.Services.Rules.RulesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Zip | Extract",
                        taskStart: (e) => {
                            service.addPackage({
                                uploadId: uploadId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2.xhr.responseJSON);
                                    e2.errorHandled = true;
                                }
                            });
                        },
                        close: (e) => {
                            this.grid.refresh();
                            PDJS.Shared.MessageStack
                                .instance
                                .success(`Rule scripts extracted successfully.`);
                        }
                    });
                }
            }
            Rules.UploadZipCommand = UploadZipCommand;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/rules");
                }
                registerCommands(e) {
                    e.commands.add(new Rules.ChangeTagsCommand());
                    e.commands.add(new Rules.DeleteScriptCommand());
                    e.commands.add(new Rules.DownloadZipCommand());
                    e.commands.add(new Rules.EditScriptCommand());
                    e.commands.add(new Rules.NewScriptCommand());
                    e.commands.add(new Rules.OpenScriptCommand());
                    e.commands.add(new Rules.UploadZipCommand());
                }
            }
            Rules.RulesCommands = RulesCommands;
            Jade.CommandGroups.add(RulesCommands);
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesGrid extends Jade.UI.Control {
                ;
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get filters() {
                    return this.state.get("filters", []);
                }
                set filters(value) {
                    this.state.set("filters", value);
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get searchTerm() {
                    return this.m_searchTerm;
                }
                set searchTerm(value) {
                    this.m_searchTerm = value;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-rules-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Events and Scripts</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Rules.RulesToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No rule scripts."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName,
                                    isBuiltIn: e.IsBuiltIn
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/rules:script/open");
                        },
                        change: (e) => {
                            this.changeCallback(e.selections.toArray());
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        },
                        needContext: (e) => {
                            _.each(this.filters, (item) => {
                                e.filters[e.filters.length] = item.toJSON();
                            });
                        }
                    });
                    this.subscriptions.add(Rules.EventsHub.searchScriptsSubscribe(e => {
                        this.filters = [];
                        this.searchTerm = Jade.String.isNullOrWhiteSpace(e.searchTerm) ? null : e.searchTerm;
                        if (!Jade.String.isNullOrWhiteSpace(e.searchTerm)) {
                            this.filters.push(PDJS.Core.Views.RulesFilter.content(e.searchTerm));
                        }
                        if (!Jade.String.isNullOrWhiteSpace(e.expression)) {
                            this.filters.push(PDJS.Core.Views.RulesFilter.expression(e.expression));
                        }
                        this.m_grid.refresh();
                    }));
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Rules.RulesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Rules.RulesGrid = RulesGrid;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let group = "pdjs/manage/rules";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${group}:script/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${group}:script/open`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${group}:script/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${group}:entity/change-tags`
                    }));
                }
            }
            Rules.RulesGridContextMenu = RulesGridContextMenu;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                onModuleFocus() {
                    if (this.m_grid) {
                        this.m_grid.refresh();
                    }
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-rules">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Rules.RulesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Rules.RulesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Rules.RulesService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/rules": {
                            $grid: this.m_grid,
                            $actionsPane: this.m_actions
                        }
                    }, { force: true });
                }
            }
            Rules.RulesModule = RulesModule;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class ExportPanes extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get actionsPaneId() {
                    return "actions";
                }
                get contentPaneId() {
                    return "content";
                }
                get explorePaneId() {
                    return "explore";
                }
                get splitter() {
                    return this.m_splitter;
                }
                set splitter(value) {
                    this.m_splitter = value;
                }
                actionsPaneVisible(visible) {
                    visible ?
                        this.splitter.expand(this.explorePaneId) :
                        this.splitter.collapse(this.explorePaneId);
                }
                explorePaneVisible(visible) {
                    visible ?
                        this.splitter.expand(this.explorePaneId) :
                        this.splitter.collapse(this.explorePaneId);
                }
                template() {
                    return `
                <div>
                    <div role="explore"></div>
                    <div role="content"></div>
                    <div role="actions"></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                }
            }
            Rules.ExportPanes = ExportPanes;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RulesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let group = "pdjs/manage/rules";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:script/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:script/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:script/open`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:script/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:entity/change-tags`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:package/upload`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${group}:package/download`
                    }));
                }
            }
            Rules.RulesToolbar = RulesToolbar;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class ScriptReferences extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_view = null;
                }
                get buttons() {
                    return this.buttonsNode.find("button");
                }
                get buttonsNode() {
                    return this.node.find("div[role=buttons]");
                }
                get canvasButton() {
                    return this.node.find("button[role=canvas]");
                }
                get canvasReferences() {
                    return this.references.fromCanvas || [];
                }
                get fromButton() {
                    return this.node.find("button[role=from]");
                }
                get fromReferences() {
                    return this.references.fromScripts || [];
                }
                get header() {
                    return this.m_header;
                }
                get headerNode() {
                    return this.node.find("div[role=header]");
                }
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get references() {
                    return this.m_references || {};
                }
                set references(value) {
                    this.m_references = value;
                }
                get scripts() {
                    return this.state.get("scripts");
                }
                set scripts(value) {
                    this.state.set("scripts", value);
                }
                get toButton() {
                    return this.node.find("button[role=to]");
                }
                get toReferences() {
                    return this.references.toScripts || [];
                }
                get view() {
                    return this.m_view || "to";
                }
                set view(value) {
                    this.m_view = value;
                }
                refresh(scripts) {
                    this.scripts = scripts;
                    this.list_populate();
                }
                template() {
                    return `<div class="-pdjs-manage-rules-script-references">
                        <div role="header"></div>
                        <div role="list" data-controls></div>
                        <div role="buttons">
                            <div>
                                <button role="to">
                                </button>
                            </div>
                            <div>
                                <button role="from">
                                </button>
                            </div>
                            <div>
                                <button role="canvas">
                                </button>
                            </div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.header_init();
                    this.list_init();
                    this.buttons.on("click", (e) => {
                        this.view = $(e.currentTarget).attr("role");
                        this.setSelectedHeaderText();
                        this.setSelectedButton();
                        this.loadList();
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setButtonText();
                    this.setSelectedHeaderText();
                    this.setSelectedButton();
                    this.list_populate();
                    this.node.css({ marginBottom: "10px" });
                }
                header_init() {
                    this.m_header = new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        insertAt: "div[role=header]",
                        label: "References"
                    });
                    this.controls.add(this.m_header);
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        noItemsMessage: "No references.",
                        height: "160px",
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                        iconSet: "pd",
                        binding: {
                            icon: "icon",
                            label: "label",
                            value: "value"
                        },
                        dblClick: (items) => {
                            this.list_item_dblclick(items.first().toJSON());
                        }
                    });
                    this.controls.add(this.list);
                }
                list_populate() {
                    let service = new PDJS.Services.Rules.RuleService();
                    this.list.binding = {
                        label: "name",
                        value: "value"
                    };
                    if (this.scripts.length == 0) {
                        return;
                    }
                    this.references = null;
                    this.setButtonText();
                    this.setLoadingMessage();
                    service.getReferences({
                        scriptIds: this.scripts.map(script => script.id),
                        success: (e) => {
                            this.references = e.data;
                            this.loadList();
                            this.setButtonText();
                        }
                    });
                }
                list_item_dblclick(item) {
                    switch (this.view) {
                        case "canvas":
                            this.canvasItemDblClick(item);
                            break;
                        case "from":
                            this.fromScriptItemDblClick(item);
                            break;
                        case "to":
                            this.fromScriptItemDblClick(item);
                            break;
                    }
                }
                fromScriptItemDblClick(item) {
                    let reference = item;
                    PDJS.Manage.Rules.Editor.EditorDirectivesHub.highlightReferences([reference.id], {
                        terms: this.scripts.map(script => script.name)
                    });
                }
                toScriptItemDblClick(item) {
                    let reference = item;
                    PDJS.Manage.Rules.Editor.EditorDirectivesHub.highlightReferences(reference.scriptIds, {
                        terms: [reference.name]
                    });
                }
                canvasItemDblClick(item) {
                    let reference = item;
                    PDJS.Manage.Canvas.CanvasDirectivesHub.highlightElement(reference.documentId, {
                        elementId: reference.elementId
                    });
                }
                addListItem(item, data) {
                    this.list.addItem(_.extend(item, data));
                }
                loadList() {
                    this.list.removeAll();
                    if (this.view === "to") {
                        this.references.toScripts.map(item => {
                            this.addListItem(item, {
                                name: item.name,
                                value: item.id,
                                icon: "arrow_right_green.png"
                            });
                        });
                    }
                    if (this.view === "from") {
                        this.references.fromScripts.map(item => {
                            this.addListItem(item, {
                                name: item.name,
                                value: item.id,
                                icon: "arrow_left_red.png"
                            });
                        });
                    }
                    if (this.view === "canvas") {
                        this.references.fromCanvas.map(item => {
                            this.addListItem(item, {
                                name: `${item.formName} > ${item.type}`,
                                value: item.elementId == null ? item.documentId : item.elementId,
                                icon: "objects.png"
                            });
                        });
                    }
                }
                getButtonImage(icon) {
                    return Jade.IconSet.get("pd").resolve(icon, Jade.IconSetSizeSpecificDirectory.x16);
                }
                setButtonText() {
                    this.toButton.empty();
                    this.toButton.html(`<img src="${this.getButtonImage("arrow_right_green.png")}" /> <b>${this.toReferences.length || "-"}</b>`);
                    this.fromButton.empty();
                    this.fromButton.html(`<img src="${this.getButtonImage("arrow_left_red.png")}" /> <b>${this.fromReferences.length || "-"}</b>`);
                    this.canvasButton.empty();
                    this.canvasButton.html(`<img src="${this.getButtonImage("objects.png")}" /> <b>${this.canvasReferences.length || "-"}</b>`);
                }
                setSelectedButton() {
                    this.buttons.removeClass("-pdjs-selected");
                    this.buttons.each((index, element) => {
                        let node = $(element);
                        if (node.attr("role") === this.view) {
                            node.addClass("-pdjs-selected");
                        }
                    });
                }
                setSelectedHeaderText() {
                    switch (this.view) {
                        case "canvas":
                            this.header.label = "References from Canvas";
                            break;
                        case "from":
                            this.header.label = "References from External Scripts";
                            break;
                        case "to":
                            this.header.label = "References to External Scripts";
                            break;
                    }
                }
                setLoadingMessage() {
                    let messageControl = this.list.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (messageControl != null) {
                        messageControl.message = PDJS.Shared.Spinner.toHtml({
                            size: 12,
                            text: "Loading..."
                        });
                        ;
                    }
                }
            }
            Rules.ScriptReferences = ScriptReferences;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class ScriptSearch extends Jade.UI.Control {
                get clearButton() {
                    return this.node.find("button[role=clear]");
                }
                get searchButton() {
                    return this.node.find("button[role=search]");
                }
                template() {
                    return `<div class="-pdjs-manage-rules-script-search">
                        <div role="header"></div>
                        <div role="search-box"></div>
                        <div role="expression"></div>
                        <div role="buttons">
                            <button role="search" class="-pdjs-button">Find</button>
                            <button role="clear" class="-pdjs-button" style="display:none;">Clear</button>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.header_init();
                    this.tagExpression_init();
                    this.searchBox_init();
                    this.clearButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.m_searchBox.clear();
                        this.m_expression.value = "";
                        this.executeSearch();
                    });
                    this.searchButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.executeSearch();
                    });
                    this.node.css({ marginBottom: "10px" });
                }
                header_init() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        insertAt: "div[role=header]",
                        label: "Find in Scripts"
                    }));
                }
                searchBox_init() {
                    this.m_searchBox =
                        new PDJS.Shared.UI.Controls.SearchBox({
                            insertAt: "div[role=search-box]",
                            defaultMaskText: "Find...",
                            onSearch: (e) => {
                                this.executeSearch();
                            }
                        });
                    this.controls.add(this.m_searchBox);
                }
                tagExpression_init() {
                    this.m_expression = new PDJS.Shared.UI.Controls.Fields.ExpressionField({
                        insertAt: "div[role=expression]",
                        height: 100,
                        label: "Script Tags"
                    });
                    this.controls.add(this.m_expression);
                }
                executeSearch() {
                    this.m_expression.errors.clear();
                    let service = new PDJS.Services.Rules.RulesTagsService();
                    service.validateExpression({
                        expression: this.m_expression.value,
                        success: (e) => {
                            Rules.EventsHub.searchScriptsPublish({
                                searchTerm: this.m_searchBox.textValue,
                                expression: this.m_expression.value
                            });
                        },
                        error: (e) => {
                            this.m_expression.errors.clear();
                            let error = e.xhr.responseJSON != null ? e.xhr.responseJSON[0] : null;
                            this.m_expression.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                                message: error != null ? error.message : e.error.message
                            }));
                            if (error != null) {
                                e.errorHandled = true;
                                if (error.tags["Tags"]) {
                                    this.m_expression.highlight(error.tags["Tags"]);
                                }
                            }
                        }
                    });
                }
            }
            Rules.ScriptSearch = ScriptSearch;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RuleScriptSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get grid() {
                    return this.m_grid;
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-rules-script-select-dialog">
                    <div data-role="grid"></div>
                    <div data-role="buttons">
                        <button data-command="ok" class="-pdjs-dialog-button">OK</button>
                        <button data-command="cancel" class="-pdjs-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Rule Script",
                        height: "400px",
                        width: "600px",
                        maximized: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.dialog_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.Name
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.m_selection = e.selection;
                        },
                        dblclick: (e) => {
                            this.m_selection = e.selection;
                            this.closeAndReturn();
                        },
                        needContext: (e) => {
                            e.filters[e.filters.length] = {
                                id: "NoEvents"
                            };
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.m_selection != null) {
                        this.close({
                            name: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No rule script has been selected. Select a rule script and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                dialog_init() {
                    let service = new PDJS.Services.Views.ViewService();
                    service.getViewStateId({
                        viewCustomId: PDJS.Services.Views.BuiltInViews.RULE_SELECTION,
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                            this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        }
                    });
                }
                static open(options) {
                    return new RuleScriptSelectionDialog(options);
                }
            }
            Rules.RuleScriptSelectionDialog = RuleScriptSelectionDialog;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class UploadZipDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                get uploadName() {
                    return this.state.get("uploadName");
                }
                set uploadName(value) {
                    this.state.set("uploadName", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-upload-zip-dialog">
                    <div role="text">Select a ".zip" file to upload and extract the rule scripts.</div>
                    <div role="progress"></div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-id="ok" disabled>Extract</button>
                        <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Upload | Zip File",
                        width: "400px",
                        resizable: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                uploadId: this.uploadId,
                                uploadName: this.uploadName
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=progress]",
                        onFileSelected: (e) => {
                        },
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.uploadName = e.name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options) {
                    return new UploadZipDialog(options);
                }
            }
            Rules.UploadZipDialog = UploadZipDialog;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            class RuleEditing {
                static create() {
                    this.showFeatureDialog();
                }
                static edit(e) {
                    this.showFeatureDialog(e);
                }
                static editScript(scriptId) {
                    window.location.href = `#/module/rule-script-editor/${scriptId}`;
                }
                static showFeatureDialog(e = {}) {
                    let action = e.ruleId == null ?
                        `New` : `Edit`;
                    let name = e.ruleId == null ?
                        `Rule Script` : `${e.ruleName}`;
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `${action} | ${name}`,
                        height: "400px",
                        width: "450px",
                        args: {
                            targetId: e.ruleId,
                            targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptArbiter"
                        },
                        select: {
                            "ok": (sender, e2) => {
                                sender.close();
                                e.commit != null ? e.commit(e2) :
                                    this.showPromptToOpenDialog(e2.target.id);
                            }
                        }
                    });
                }
                static showPromptToOpenDialog(targetId) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Edit | Rule",
                        message: `Open the new rule for editing?`,
                        select: (e2) => {
                            e2.close();
                            if (e2.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                window.location.href = `#/module/rule-script-editor/${targetId}`;
                            }
                        }
                    });
                }
            }
            Rules.RuleEditing = RuleEditing;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                let Directives;
                (function (Directives) {
                    Directives["HighlightReferences"] = "HighlightReferences";
                    Directives["HighlightSearchTerm"] = "HighlightSearchTerm";
                })(Directives = Editor.Directives || (Editor.Directives = {}));
                class EditorDirectivesHub extends PDJS.Manage.ModuleDirectives {
                    static get moduleId() {
                        return "rule-script-editor";
                    }
                    static highlightReferences(ruleScriptIds, args, complete = () => { }) {
                        let routes = ruleScriptIds.map(targetId => {
                            return this.createUrl(this.moduleId, targetId, Directives.HighlightReferences, args);
                        });
                        Manage.ModuleLoader.load(routes, { complete: complete });
                    }
                    static highlightSearchTerm(ruleScriptIds, args, complete = () => { }) {
                        let routes = ruleScriptIds.map(targetId => {
                            return this.createUrl(this.moduleId, targetId, Directives.HighlightSearchTerm, args);
                        });
                        Manage.ModuleLoader.load(routes, { complete: complete });
                    }
                }
                Editor.EditorDirectivesHub = EditorDirectivesHub;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class EditorActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    constructor(options) {
                        super(options);
                    }
                    get scriptId() {
                        return this.state.get("scriptId");
                    }
                    set scriptId(value) {
                        this.state.set("scriptId", value);
                    }
                    get scriptName() {
                        return this.state.get("scriptName");
                    }
                    set scriptName(value) {
                        this.state.set("scriptName", value);
                    }
                    get workspace() {
                        return this.state.get("workspace");
                    }
                    load(scriptId, scriptName) {
                        this.scriptId = scriptId;
                        this.scriptName = scriptName;
                        this.addItems();
                    }
                    template() {
                        return `<div class="-pdjs-manage-rules-editor-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    addItems() {
                        this.addReferencesControl();
                        this.addRuleHistory();
                        this.addScriptTags();
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Rules"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Manage Rules",
                            url: "#/module/rules"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "New Rule Script",
                            click: () => {
                                PDJS.Manage.Rules.RuleEditing.create();
                            }
                        }));
                    }
                    addReferencesControl() {
                        let references = new PDJS.Manage.Rules.ScriptReferences({
                            scripts: [{ id: this.scriptId, name: this.scriptName }]
                        });
                        this.controls.add(references);
                        this.subscriptions.add(Editor.EventsHub.saveSubscribe(() => {
                            references.refresh([{
                                    id: this.scriptId,
                                    name: this.scriptName
                                }]);
                        }));
                    }
                    addRuleHistory() {
                        this.controls.add(new Editor.RuleHistory({
                            scriptId: this.scriptId,
                            workspace: this.workspace
                        }));
                    }
                    addScriptTags() {
                        this.controls.add(new Editor.ScriptTags({
                            scriptId: this.scriptId
                        }));
                    }
                }
                Editor.EditorActions = EditorActions;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.initialLoadComplete = false;
                    this.state.set("$editor", null);
                    this.state.set("$workspace", null);
                }
                get editor() {
                    var _a, _b;
                    return this.state.get("$editor") || ((_b = (_a = this.workspace) === null || _a === void 0 ? void 0 : _a.focusedPane) === null || _b === void 0 ? void 0 : _b.editor);
                }
                get workspace() {
                    return this.state.get("$workspace");
                }
                get editorSettings() {
                    return PDJS.Shared.Coding.CodeEditorEnvironment.current;
                }
                setState(state) {
                    super.setState(state);
                    if (this.editor != null && !this.initialLoadComplete) {
                        this.onInitialLoad();
                    }
                }
                updateCommandState() {
                    this.editor.setCommandState();
                }
                onInitialLoad() {
                }
            }
            Coding.CodeEditorCommand = CodeEditorCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class EditorCommand extends PDJS.Shared.Coding.CodeEditorCommand {
                    constructor() {
                        super();
                        this.state.set("$module", null);
                        this.state.set("fileId", null);
                        this.state.set("fileName", null);
                        this.state.set("folderId", null);
                        this.state.set("moduleId", null);
                    }
                    get editor() {
                        return this.workspace.pane1.editor;
                    }
                    get module() {
                        return this.state.get("$module");
                    }
                    get fileId() {
                        return this.state.get("fileId");
                    }
                    set fileId(value) {
                        this.state.set("fileId", value);
                    }
                    get fileName() {
                        return this.state.get("fileName");
                    }
                    set fileName(value) {
                        this.state.set("fileName", value);
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    set folderId(value) {
                        this.state.set("folderId", value);
                    }
                    get moduleId() {
                        return this.state.get("moduleId");
                    }
                    set moduleId(value) {
                        this.state.set("moduleId", value);
                    }
                    get editorSettings() {
                        return PDJS.Shared.Coding.CodeEditorEnvironment.current;
                    }
                    setState(state) {
                        super.setState(state);
                        if (this.editor != null && !this.initialLoadComplete) {
                            this.onInitialLoad();
                        }
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/manage/resources/editor": {
                                fileId: this.fileId,
                                fileName: this.fileName,
                                folderId: this.folderId,
                                moduleId: this.moduleId
                            }
                        }, { force: true });
                    }
                    onInitialLoad() {
                    }
                }
                Editor.EditorCommand = EditorCommand;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class OpenCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "script/open",
                            label: "Open",
                            icon: "folder_open_document.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                    }
                }
                Editor.OpenCommand = OpenCommand;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class SaveCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "file/save",
                            label: "Save",
                            tooltip: "Save changes made to the rule script.",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.editor != null && !this.editor.readOnly && this.editor.content.changed;
                    }
                    execute(e) {
                        if (this.enabled) {
                            this.save();
                        }
                    }
                    save() {
                        let service = new PDJS.Services.Rules.RulesService();
                        this.workspace.memos.clearErrors();
                        service.saveRuleScript({
                            id: this.fileId,
                            content: this.workspace.pane1.editor.content.getValue(),
                            success: (e) => {
                                this.workspace.content.setValue(e.data.content, {
                                    silent: true, changed: false
                                });
                                this.workspace.memos.render();
                                this.editor.focus();
                                this.module.settings.hasChanges = false;
                                Editor.EventsHub.savePublish();
                                PDJS.Shared.MessageStack
                                    .instance
                                    .success("Rule script saved successuflly.");
                                this.enabled = false;
                            },
                            error: (e) => {
                                var errors = e.xhr.responseJSON;
                                if (errors != null) {
                                    e.errorHandled = true;
                                    this.showCompileErrorsDialog(errors);
                                }
                            }
                        });
                    }
                    addErrorMarkers(errors) {
                        errors.forEach(error => {
                            if (error.tags != null && ("ScriptLine" in error.tags)) {
                                this.workspace.memos.addErrorMemo({
                                    row: error.tags["ScriptLine"] - 1,
                                    text: error.message
                                });
                            }
                        });
                        this.workspace.memos.render();
                    }
                    showCompileErrorsDialog(errors) {
                        Jade.UI.Dialogs.TaggedMessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "Rule | Compilation Errors",
                            header: "The following errors were found during compilation:",
                            messages: errors,
                            select: (e) => {
                                e.close();
                                this.addErrorMarkers(errors);
                                this.editor.focus();
                            }
                        });
                    }
                }
                Editor.SaveCommand = SaveCommand;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class SaveAsCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "file/save-as",
                            label: "Save As",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    setState(state) {
                        super.setState(state);
                        this.visible = !Jade.Guid.isNullOrEmpty(this.fileId);
                    }
                    execute(e) {
                    }
                }
                Editor.SaveAsCommand = SaveAsCommand;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class EditorCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/rules/editor");
                    }
                    registerCommands(e) {
                        e.commands.add(new Editor.OpenCommand());
                        e.commands.add(new Editor.SaveCommand());
                        e.commands.add(new Editor.SaveAsCommand());
                    }
                }
                Editor.EditorCommands = EditorCommands;
                Jade.CommandGroups.add(EditorCommands);
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class CodeWorkspaceDirective extends PDJS.Manage.ModuleDirective {
                    constructor(options) {
                        super(options);
                        this.m_workspace = options.workspace;
                    }
                    get workspace() {
                        return this.m_workspace;
                    }
                }
                Editor.CodeWorkspaceDirective = CodeWorkspaceDirective;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class EditorModule extends Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get workspace() {
                        return this.m_workspace;
                    }
                    set workspace(value) {
                        this.m_workspace = value;
                    }
                    get scriptId() {
                        return this.settings.targetId;
                    }
                    get scriptName() {
                        return this.settings.label;
                    }
                    get moduleId() {
                        return this.settings.moduleId;
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    get toolbar() {
                        return this.m_toolbar;
                    }
                    set toolbar(value) {
                        this.m_toolbar = value;
                    }
                    onModuleFocus() {
                        setTimeout(() => {
                            var _a, _b;
                            if (this.m_spliiter != null) {
                                this.m_spliiter.resize();
                            }
                            if (this.workspace) {
                                (_b = ((_a = this.workspace.focusedPane) !== null && _a !== void 0 ? _a : this.workspace.pane1)) === null || _b === void 0 ? void 0 : _b.editor.focus();
                            }
                        }, 0);
                    }
                    template() {
                        return `<div class="-pdjs-manage-rules-editor">
                        <div role="splitter">
                            <div data-id="pane-1">
                                <div data-role="content">
                                    <div data-role="toolbar"></div>
                                    <div data-role="editor"></div>
                                </div>
                            </div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.toolbar_init();
                        this.editor_init();
                        this.actions_init();
                        this.m_windowResize =
                            PDJS.ApplicationEventsHub.windowResizedSubscribe(() => {
                                if (this.focused) {
                                    this.workspace.resize();
                                }
                            });
                        this.addSubscribers();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.registerKeyboardShortcuts();
                        this.workspace.pane1.focus();
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        this.destroyControls();
                    }
                    onModuleLoadError(e) {
                        super.onModuleLoadError(e);
                        this.destroyControls();
                    }
                    onModuleLoad(e) {
                        e.addStep(() => this.loadScript());
                    }
                    onRegisterDirectives() {
                        this.directives.add(new Editor.HighlightReferences({ workspace: this.workspace }));
                        this.directives.add(new Editor.HighlightSearchTerm({ workspace: this.workspace }));
                    }
                    actions_init() {
                        this.m_actions = new Editor.EditorActions({
                            insertAt: "div[data-id=pane-2]",
                            workspace: this.workspace
                        });
                        this.controls.add(this.m_actions);
                    }
                    editor_init() {
                        this.m_workspace = new PDJS.Shared.Coding.CodeWorkspace({
                            insertAt: "div[data-role=editor]",
                            change: () => {
                                this.settings.hasChanges = true;
                                this.updateCommandState();
                            },
                            focus: (sender) => {
                                this.updateCommandState();
                            }
                        });
                        this.controls.add(this.m_workspace);
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false },
                                { resizable: true, size: "300px", scrollable: false }
                            ],
                            orientation: "horizontal",
                            resize: () => {
                                if (this.workspace) {
                                    this.workspace.resize();
                                }
                            }
                        }).data("kendoSplitter");
                    }
                    toolbar_init() {
                        this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[data-role=toolbar]",
                            segments: [new Editor.EditorToolbar(), new PDJS.Shared.Coding.CodeEditorToolbar({ target: "rules" })]
                        });
                        this.controls.add(this.toolbar);
                    }
                    updateCommandState() {
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .commands
                            .setState({
                            "pdjs/manage/rules/editor": {
                                $module: this,
                                $workspace: this.workspace,
                                fileId: this.scriptId,
                                fileName: this.scriptName,
                                moduleId: this.moduleId
                            }
                        }, { force: true });
                        this.workspace.setCommandState();
                    }
                    loadScript() {
                        return this.modulePromise((resolve, reject) => {
                            let service = new PDJS.Services.Rules.RulesService();
                            service.loadRuleScript({
                                id: this.scriptId,
                                success: (e) => {
                                    this.workspace.pane1.headerText = "Current";
                                    this.workspace.pane1.editor.load(e.data.content);
                                    this.workspace.pane1.editor.settings.setStyle("text/xml");
                                    this.workspace.pane1.editor.content.resetChangedState();
                                    this.workspace.pane2.editor.settings.setStyle("text/xml");
                                    this.state.set({
                                        fileId: e.data.id,
                                        fileName: e.data.name,
                                        folderPath: ""
                                    });
                                    this.settings.label = e.data.name;
                                    this.m_actions.load(this.scriptId, this.scriptName);
                                    this.updateCommandState();
                                    setTimeout(() => { resolve("success"); }, 250);
                                },
                                error: (e) => { reject(e); }
                            });
                        });
                    }
                    registerKeyboardShortcuts() {
                        let keys = PDJS.Application
                            .instance
                            .contexts
                            .current
                            .hotkeys;
                        keys.simple_combo("ctrl s", () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/rules/editor:file/save");
                        });
                        keys.simple_combo("ctrl o", () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/rules/editor:file/open");
                        });
                    }
                    addSubscribers() {
                        this.subscriptions.add(Editor.EventsHub.ruleRenamedSubscribe(e => {
                            if (this.settings.targetId == e.id) {
                                this.settings.label = e.name;
                            }
                        }));
                    }
                    destroyControls() {
                        if (this.m_spliiter) {
                            this.m_spliiter.destroy();
                            this.m_spliiter.setOptions({ resize: undefined });
                            this.m_spliiter = null;
                        }
                        if (this.m_windowResize) {
                            this.m_windowResize.unsubscribe();
                            this.m_windowResize = null;
                        }
                    }
                }
                Editor.EditorModule = EditorModule;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class EditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/rules/editor";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:file/save`
                        }));
                    }
                }
                Editor.EditorToolbar = EditorToolbar;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                let Events;
                (function (Events) {
                    Events["Save"] = "file/save";
                    Events["SaveAs"] = "file/save-as";
                })(Events = Editor.Events || (Editor.Events = {}));
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                let Events;
                (function (Events) {
                    Events["RuleRenamed"] = "rules/rule-renamed";
                })(Events = Editor.Events || (Editor.Events = {}));
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static ruleRenamedPublish(args) {
                        this.global.publish(Events.RuleRenamed, args);
                    }
                    static savePublish() {
                        this.current.publish(Events.Save);
                    }
                    static saveAsPublish(args) {
                        this.current.publish(Events.SaveAs, args);
                    }
                    static ruleRenamedSubscribe(handler) {
                        return this.global.subscribe(Events.RuleRenamed, handler);
                    }
                    static saveSubscribe(handler) {
                        return this.current.subscribe(Events.Save, handler);
                    }
                    static saveAsSubscribe(handler) {
                        return this.current.subscribe(Events.SaveAs, handler);
                    }
                }
                Editor.EventsHub = EventsHub;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class RuleHistory extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get scriptId() {
                        return this.state.get("scriptId");
                    }
                    get workspace() {
                        return this.state.get("workspace");
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get moreButton() {
                        return this.node.find("div[role=deck] > button");
                    }
                    refresh() {
                        let selectedValue = null;
                        if (this.list.selected.count > 0) {
                            selectedValue = this.list.selected.first().value;
                        }
                        this.list_populate(() => {
                            if (selectedValue != null) {
                                this.list.select([selectedValue]);
                            }
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-rules-editor-history">
                        <div role="head"></div>
                        <div role="main" data-controls></div>
                        <div role="deck">
                            <button class="-pdjs-button">More...</button>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.moreButton.on(Jade.BrowserEvent.CLICK, (e) => {
                            Editor.RuleHistoryDialog.open({
                                scriptId: this.scriptId,
                                select: {
                                    ok: (sender, e) => {
                                        sender.close();
                                        this.loadHistoryToWorkspace(e.auditId, this.formatDate(e.dateTime), e.userName);
                                    }
                                }
                            });
                        });
                        this.head_init();
                        this.list_init();
                        this.subscriptions.add(Editor.EventsHub.saveSubscribe(() => {
                            this.refresh();
                        }));
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.list_populate();
                        this.node.css({ marginBottom: "10px" });
                    }
                    head_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            insertAt: "div[role=head]",
                            label: "History"
                        }));
                    }
                    list_init() {
                        this.m_list = new PDJS.Shared.UI.Controls.ListView({
                            insertAt: "div[role=main]",
                            noItemsMessage: "No history.",
                            height: "160px",
                            selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                            iconSet: "pd",
                            binding: {
                                icon: "icon",
                                label: "label",
                                value: "value"
                            },
                            dblClick: (items) => {
                                let item = items.first().toJSON();
                                this.loadHistoryToWorkspace(item.value, item.name, item.user);
                            }
                        });
                        this.controls.add(this.list);
                    }
                    list_populate(success = () => { }) {
                        let service = new PDJS.Services.Rules.RuleService();
                        this.list.binding = {
                            label: "name",
                            value: "value"
                        };
                        this.list.removeAll();
                        service.getAuditHistory({
                            scriptId: this.scriptId,
                            success: (e) => {
                                this.moreButton.prop("disabled", e.data.count <= 25);
                                e.data.items.forEach(item => {
                                    this.list.addItem({
                                        icon: "clock.png",
                                        name: `${this.formatDate(item.auditDate)}`,
                                        user: item.userName,
                                        value: item.auditId
                                    });
                                });
                                success();
                            }
                        });
                        Date.parse;
                    }
                    loadHistoryToWorkspace(auditId, date, user) {
                        let service = new PDJS.Services.Rules.RuleService();
                        service.getAuditContent({
                            auditId: auditId,
                            success: (e) => {
                                this.workspace.settings
                                    .enterHistoryMode(e.data.content, `${date} - ${user} (READ-ONLY)`);
                            }
                        });
                    }
                    formatDate(dateTime) {
                        let dateNumber = Date.parse(dateTime);
                        return !isNaN(dateNumber) ? kendo.toString(new Date(dateTime), "MMM d yyyy - h:mm:ss tt") : "";
                    }
                }
                Editor.RuleHistory = RuleHistory;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class ScriptTags extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get tagList() {
                        this.ensureTagList();
                        return this.m_tagList;
                    }
                    get tagNode() {
                        return this.node.find("div[role=tags]");
                    }
                    get emptyMessage() {
                        return this.state.get("emptyMessage", "No tags have been added.");
                    }
                    get scriptId() {
                        return this.state.get("scriptId");
                    }
                    get addButton() {
                        return this.node.find("button[role=add]");
                    }
                    addTag(tags) {
                        let list = this.tagList;
                        tags.forEach(tag => {
                            this.addItemToList(tag, list);
                        });
                        this.renderItems(list);
                    }
                    removeTag(tags) {
                        let list = this.tagList;
                        tags.forEach(tag => {
                            this.addItemToList(tag, list);
                        });
                        this.renderItems(list);
                    }
                    template() {
                        return `<div class="-pdjs-manage-rules-editor-script-tags">
                        <div role="header"></div>
                        <div role="tags" data-controls></div>
                        <div role="buttons">
                            <button role="add" class="-pdjs-button">Add</button>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.header_init();
                        this.addButton.on(Jade.BrowserEvent.CLICK, () => {
                            this.addTags();
                        });
                        this.node.css({ marginBottom: "10px" });
                        this.loadData();
                        this.node.on(Jade.BrowserEvent.CLICK, ".icofont-close", (e) => {
                            let tag = $(e.currentTarget).closest(".-visiv-rule-script-tag").data("tag");
                            if (tag != null) {
                                this.removeScriptTag(tag);
                            }
                        });
                    }
                    header_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            insertAt: "div[role=header]",
                            label: "Tags"
                        }));
                    }
                    ensureTagList() {
                        if (this.m_tagList == null) {
                            this.m_tagList = [];
                        }
                    }
                    renderItems(items) {
                    }
                    sortItems(items) {
                        let result = items;
                        return result;
                    }
                    itemExists(item, list) {
                        return list.filter(target => {
                            return item.toLowerCase() == (item === null || item === void 0 ? void 0 : item.toLowerCase());
                        }).length > 0;
                    }
                    addItemToList(item, list) {
                        if (this.itemExists(item, list)) {
                            return;
                        }
                        list.push(item);
                    }
                    removeMessage() {
                        let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message) {
                            this.controls.remove(message);
                        }
                    }
                    addMessage(text) {
                        let message = new PDJS.Shared.UI.Controls.Message({
                            message: text,
                            backgroundColor: "var(--visiv-theme-input-back-color)",
                            textColor: "var(--visiv-theme-base-3-text-color)",
                        });
                        this.removeMessage();
                        this.controls.add(message);
                    }
                    loadData() {
                        let service = new PDJS.Services.Rules.RulesTagsService();
                        service.getTags({
                            scriptIds: [this.scriptId],
                            success: (e) => {
                                let tags = e.data.tags.map(tag => tag.name);
                                if (tags.length > 0) {
                                    this.tagNode.append(this.convertTagsToHtml(tags));
                                    return;
                                }
                                this.addMessage(this.emptyMessage);
                            }
                        });
                    }
                    convertTagsToHtml(tags) {
                        return tags.map((tag) => {
                            return `<div class="-visiv-rule-script-tag -visiv-rule-script-tag-${tag}" data-tag="${tag}">
                            <div>${tag}</div>
                            <div><i class="icofont-close"></i></div>
                        </div>`;
                        }).join("");
                    }
                    addTags() {
                        PDJS.Manage.Rules.Tags.TagsSelectionDialog.open({
                            title: "Select | Tags to Add",
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                            select: {
                                ok: (sender, e) => {
                                    this.addScriptTags(e.tags);
                                }
                            }
                        });
                    }
                    addScriptTags(tags) {
                        let service = new PDJS.Services.Rules.RulesTagsService();
                        service.addScriptTags({
                            scriptId: this.scriptId,
                            tags: tags,
                            success: (e) => {
                                tags.forEach(tag => {
                                    this.removeMessage();
                                    if (this.tagNode.find(`div[data-tag=${tag}]`).length == 0) {
                                        this.tagNode.append(this.convertTagsToHtml([tag]));
                                    }
                                });
                            }
                        });
                    }
                    removeScriptTag(tag) {
                        let service = new PDJS.Services.Rules.RulesTagsService();
                        service.removeScriptTags({
                            scriptId: this.scriptId,
                            tags: [tag],
                            success: (e) => {
                                this.tagNode.find(`div[data-tag=${tag}]`).remove();
                                if (this.tagNode.find(`.-visiv-rule-script-tag`).length == 0) {
                                    this.addMessage(this.emptyMessage);
                                }
                            }
                        });
                    }
                }
                Editor.ScriptTags = ScriptTags;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class RuleHistoryDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get scriptId() {
                        return this.state.get("scriptId");
                    }
                    get selection() {
                        return this.state.get("selection");
                    }
                    set selection(value) {
                        this.state.set("selection", value);
                    }
                    get selectionMode() {
                        return this.state.get("selectionMode", "single");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on("click", (e) => {
                            this.closeAndReturn();
                        });
                        this.cancelButtonNode.on("click", (e) => {
                            this.close();
                        });
                        this.startUp();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | History",
                            height: 350,
                            width: 500
                        };
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-manage-tags-selection-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[role=grid]"),
                            selectionMode: "single",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        auditId: e.ObjectId,
                                        dateTime: e.ModifiedDate,
                                        userName: e.ModifiedBy
                                    };
                                }
                            },
                            change: (e) => {
                                this.selection = _.first(e.selections.toArray());
                            },
                            dblclick: (e) => {
                                this.selection = _.first(e.selections.toArray());
                                this.closeAndReturn();
                            },
                            needContext: (e) => {
                                e.addFilter(PDJS.Core.Views.RuleFilter.auditHistory(this.scriptId).toJSON());
                            }
                        });
                    }
                    startUp() {
                        let service = new PDJS.Services.Views.ViewService();
                        if (this.viewStateId == null) {
                            service.getViewStateId({
                                viewCustomId: PDJS.Services.Views.BuiltInViews.RULE_SCRIPT_HISTORY,
                                success: (e) => {
                                    this.viewStateId = e.data.viewStateId;
                                    this.grid_init();
                                }
                            });
                        }
                    }
                    closeAndReturn() {
                        if (this.selection != null) {
                            this.close({
                                name: "ok",
                                data: this.selection
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Selection Made",
                                message: "Nothing has been selected. Make a selection and try again."
                            });
                        }
                    }
                    static open(options) {
                        return new RuleHistoryDialog(options);
                    }
                }
                Editor.RuleHistoryDialog = RuleHistoryDialog;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class HighlightReferences extends Editor.CodeWorkspaceDirective {
                    constructor(options) {
                        super(options);
                        this.name = Editor.Directives.HighlightReferences;
                    }
                    execute(e) {
                        this.workspace.operations.highlightReferences(e.terms);
                    }
                }
                Editor.HighlightReferences = HighlightReferences;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class HighlightSearchTerm extends Editor.CodeWorkspaceDirective {
                    constructor(options) {
                        super(options);
                        this.name = Editor.Directives.HighlightSearchTerm;
                    }
                    execute(args) {
                        if (!Jade.String.isNullOrWhiteSpace(args.name)) {
                            this.workspace.pane1.editor.finder.showFind(args.text);
                            if (this.workspace.pane2.visible) {
                                this.workspace.pane2.editor.finder.showFind(args.text);
                            }
                        }
                    }
                }
                Editor.HighlightSearchTerm = HighlightSearchTerm;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class FontSizeItem extends PDJS.Shared.UI.Controls.ToolbarCommandList {
                    constructor(options) {
                        super(options);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.items = [];
                        [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 32, 36].forEach(item => {
                            this.items.push({ label: `${item} px`, value: item });
                        });
                    }
                    onPropertiesChanged() {
                        super.onPropertiesChanged();
                        if (this.commander.value != null) {
                            this.inputNode.val(this.commander.value);
                        }
                    }
                }
                Editor.FontSizeItem = FontSizeItem;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Editor;
            (function (Editor) {
                class ThemesItem extends PDJS.Shared.UI.Controls.ToolbarCommandList {
                    constructor(options) {
                        super(options);
                        this.m_themes = [
                            { name: "- Current Manage Theme - ", value: "sys/theme/current" },
                            { name: "Chrome", value: "ace/theme/chrome" },
                            { name: "Clouds", value: "ace/theme/clouds" },
                            { name: "Crimson Editor", value: "ace/theme/crimson_editor" },
                            { name: "Dawn", value: "ace/theme/dawn" },
                            { name: "Dreamweaver", value: "ace/theme/dreamweaver" },
                            { name: "Eclipse", value: "ace/theme/eclipse" },
                            { name: "GitHub", value: "ace/theme/github" },
                            { name: "IPlastic", value: "ace/theme/iplastic" },
                            { name: "Solarized Light", value: "ace/theme/solarized_light" },
                            { name: "TextMate", value: "ace/theme/textmate" },
                            { name: "Tomorrow", value: "ace/theme/tomorrow" },
                            { name: "Xcode", value: "ace/theme/xcode" },
                            { name: "Kuroir", value: "ace/theme/kuroir" },
                            { name: "KatzenMilch", value: "ace/theme/katzenmilch" },
                            { name: "SQL Server", value: "ace/theme/sqlserver" },
                            { name: "Ambiance", value: "ace/theme/ambiance" },
                            { name: "Chaos", value: "ace/theme/chaos" },
                            { name: "Clouds Midnight", value: "ace/theme/clouds_midnight" },
                            { name: "Dracula", value: "ace/theme/dracula" },
                            { name: "Cobalt", value: "ace/theme/cobalt" },
                            { name: "Gruvbox", value: "ace/theme/gruvbox" },
                            { name: "Green on Black", value: "ace/theme/gob" },
                            { name: "Idle Fingera", value: "ace/theme/idle_fingers" },
                            { name: "krTheme", value: "ace/theme/kr_theme" },
                            { name: "Merbivore", value: "ace/theme/merbivore" },
                            { name: "Merbivore Soft", value: "ace/theme/merbivore_soft" },
                            { name: "Mono Industrial", value: "ace/theme/mono_industrial" },
                            { name: "Monokai", value: "ace/theme/monokai" },
                            { name: "Nord Dark", value: "ace/theme/nord_dark" },
                            { name: "Pastel on Dark", value: "ace/theme/pastel_on_dark" },
                            { name: "Solarized Dark", value: "ace/theme/solarized_dark" },
                            { name: "Terminal", value: "ace/theme/terminal" },
                            { name: "Tomorrow Night", value: "ace/theme/tomorrow_night" },
                            { name: "Tomorrow Night Blue", value: "ace/theme/tomorrow_night_blue" },
                            { name: "Tomorrow Night Bright", value: "ace/theme/tomorrow_night_bright" },
                            { name: "Tomorrow Night Eighties", value: "ace/theme/tomorrow_night_eighties" },
                            { name: "Twilight", value: "ace/theme/twilight" },
                            { name: "Vibrant Ink", value: "ace/theme/vibrant_ink" }
                        ];
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.items = [];
                        this.m_themes.forEach(theme => {
                            this.items.push({ label: theme.name, value: theme.value });
                        });
                    }
                    onPropertiesChanged() {
                        super.onPropertiesChanged();
                        if (this.commander.value != null) {
                            this.inputNode.val(this.commander.value);
                        }
                    }
                }
                Editor.ThemesItem = ThemesItem;
            })(Editor = Rules.Editor || (Rules.Editor = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class RuleScriptTagCss {
                    static refresh() {
                        let cssNode = $("#tag-color-css-link");
                        if (cssNode.length > 0) {
                            cssNode.attr("href", Jade.Path.resolve(`~/shared/tagcolor/css?v=${Jade.Guid.new()}`));
                        }
                    }
                }
                Tags.RuleScriptTagCss = RuleScriptTagCss;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get tag() {
                        return this.state.get("tag");
                    }
                    set tag(value) {
                        this.state.set("tag", value);
                    }
                    load(tag) {
                        this.tag = tag;
                    }
                    template() {
                        return `<div class="-pdjs-manage-rules-tags-actions  ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addRulesItems();
                    }
                    addRulesItems() {
                        let label = new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Rules"
                        });
                        this.controls.add(label);
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            url: "#/module/rules",
                            label: "Manage Rules"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "New Rule Script...",
                            click: (e) => {
                                PDJS.Manage.Rules.RuleEditing.create();
                            }
                        }));
                    }
                }
                Tags.TagsActions = TagsActions;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get selections() {
                        return this.grid.selections;
                    }
                    get selectedIds() {
                        return this.grid.selections.map(item => item.id);
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/tags": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                Tags.TagsCommand = TagsCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class DeleteTagCommand extends Tags.TagsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "tag/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Delete a tag.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 0;
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Tags?",
                            message: `Delete the selected tags? Any deleted tags which are current assigned to a rule script will be removed.`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.startTask();
                                }
                            }
                        });
                    }
                    startTask(confirmed = false) {
                        let service = new PDJS.Services.Rules.RulesTagsService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Delete | Tags",
                            taskStart: (e) => {
                                service.deleteTags({
                                    ids: this.selectedIds,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                this.grid.refresh({ clear: true });
                            }
                        });
                    }
                }
                Tags.DeleteTagCommand = DeleteTagCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class EditTagCommand extends Tags.TagsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "tag/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit a tag.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length == 1;
                    }
                    execute(e) {
                        let tag = _.first(this.selections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${tag.name}`,
                            height: 550,
                            width: 500,
                            args: {
                                targetId: tag.id,
                                targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptTagUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptTagArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.grid.refresh();
                                    Tags.RuleScriptTagCss.refresh();
                                }
                            }
                        });
                    }
                }
                Tags.EditTagCommand = EditTagCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class NewTagCommand extends Tags.TagsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "tag/new",
                            label: "New Tag",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Create a new tag.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Manage.Rules.Tags.NewTagDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.grid.refresh({
                                        clear: true,
                                        selections: [e.target.id]
                                    });
                                    Tags.RuleScriptTagCss.refresh();
                                }
                            }
                        });
                    }
                }
                Tags.NewTagCommand = NewTagCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/rules/tags");
                    }
                    registerCommands(e) {
                        e.commands.add(new Tags.DeleteTagCommand());
                        e.commands.add(new Tags.EditTagCommand());
                        e.commands.add(new Tags.NewTagCommand());
                    }
                }
                Tags.TagsCommands = TagsCommands;
                Jade.CommandGroups.add(TagsCommands);
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-tags-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Tags</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Tags.TagsGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "multiple",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No tags."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.ObjectName
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/rules/tags:tag/edit");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.Rules.Tags.TagsGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                Tags.TagsGrid = TagsGrid;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/rules/tags";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:tag/new`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:tag/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:tag/delete`
                        }));
                    }
                }
                Tags.TagsGridContextMenu = TagsGridContextMenu;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/rules/tags";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:tag/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:tag/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:tag/delete`
                        }));
                    }
                }
                Tags.TagsGridToolbar = TagsGridToolbar;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-tags">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.actions_init();
                        this.module_init();
                        this.settings.label = "Rules | Script Tags";
                    }
                    grid_init() {
                        this.m_grid = new Tags.TagsGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.m_actions.load(item);
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    actions_init() {
                        this.m_actions = new Tags.TagsActions({
                            insertAt: "div[data-id=pane-2]"
                        });
                        this.controls.add(this.m_actions);
                    }
                    module_init() {
                        let service = new PDJS.Services.Rules.RulesTagsService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false },
                                { resizable: true, size: "300px", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/rules/tags": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                Tags.TagsModule = TagsModule;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class ChangeTagsDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get selectNode() {
                        return this.node.find("select");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-id=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=cancel]");
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-manage-rules-tags-change-tags-dialog">
                        <div role="toolbar"></div>
                        <div role="editor"></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Entities | Change Tags",
                            height: 250,
                            width: 450,
                            maximized: false,
                            resizable: true
                        };
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.closeAndReturn();
                        });
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                        this.editor_init();
                        this.toolbar_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setCommandState();
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=toolbar]",
                            segments: [new Tags.ChangeTagsDialogToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    editor_init() {
                        this.m_editor = new PDJS.Shared.UI.Controls.TagEditorBatch({
                            insertAt: "div[role=editor]"
                        });
                        this.controls.add(this.m_editor);
                    }
                    closeAndReturn() {
                        this.close({
                            name: "ok",
                            data: this.m_editor.items
                        });
                    }
                    setCommandState() {
                        let setState = this.m_editor != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/rules/tags/change-tags-dialog": {
                                $editor: this.m_editor
                            }
                        }, { force: true });
                    }
                    static open(options) {
                        return new ChangeTagsDialog(options);
                    }
                }
                Tags.ChangeTagsDialog = ChangeTagsDialog;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class ChangeTagsDialogCommand extends Jade.Command {
                    constructor(options) {
                        super(options);
                        this.state.set("$editor", null);
                    }
                    get editor() {
                        return this.state.get("$editor");
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/rules/tags/change-tags-dialog": {
                                $editor: this.editor
                            }
                        }, { force: true });
                    }
                }
                Tags.ChangeTagsDialogCommand = ChangeTagsDialogCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class AddTagsCommand extends Tags.ChangeTagsDialogCommand {
                    onExecute(e) {
                        super.onExecute(e);
                        Tags.TagsSelectionDialog.open({
                            title: "Select | Tags to Add",
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                            select: {
                                ok: (sender, e) => {
                                    this.editor.addTag(e.tags);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "tags/add",
                            tooltip: "Add tags to be added to the selected entities.",
                            label: "Add Tags",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                Tags.AddTagsCommand = AddTagsCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class RemoveTagsCommand extends Tags.ChangeTagsDialogCommand {
                    onExecute(e) {
                        super.onExecute(e);
                        Tags.TagsSelectionDialog.open({
                            title: "Select | Tags to Remove",
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                            select: {
                                ok: (sender, e) => {
                                    this.editor.removeTag(e.tags);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "tags/remove",
                            tooltip: "Add tags to be removed from the selected entities.",
                            label: "Remove Tags",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                Tags.RemoveTagsCommand = RemoveTagsCommand;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class ChangeTagsDialogCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/rules/tags/change-tags-dialog");
                    }
                    registerCommands(e) {
                        e.commands.add(new Tags.AddTagsCommand());
                        e.commands.add(new Tags.RemoveTagsCommand());
                    }
                }
                Tags.ChangeTagsDialogCommands = ChangeTagsDialogCommands;
                Jade.CommandGroups.add(ChangeTagsDialogCommands);
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class ChangeTagsDialogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/rules/tags/change-tags-dialog";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:tags/add`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:tags/remove`
                        }));
                    }
                }
                Tags.ChangeTagsDialogToolbar = ChangeTagsDialogToolbar;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            class FeatureDialogForNhib extends Features.FeatureDialog {
                getRequestData() {
                    return {
                        "initialized": false,
                        "arbiter": {
                            type: this.arbiterType,
                            targetType: this.targetType,
                            id: this.targetId,
                            attributes: this.attributes,
                            properties: this.properties
                        }
                    };
                }
                static open(options) {
                    return new FeatureDialogForNhib(options);
                }
            }
            Features.FeatureDialogForNhib = FeatureDialogForNhib;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class NewTagDialog extends PDJS.Shared.Features.FeatureDialogForNhib {
                    static open(options = {}) {
                        return new NewTagDialog(_.extend({
                            title: "New | Script Tag",
                            height: 400,
                            width: 500,
                            args: {
                                targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptTagUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptTagArbiter"
                            }
                        }, options));
                    }
                }
                Tags.NewTagDialog = NewTagDialog;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Rules;
        (function (Rules) {
            var Tags;
            (function (Tags) {
                class TagsSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get selections() {
                        return this.state.get("selection");
                    }
                    set selections(value) {
                        this.state.set("selection", value);
                    }
                    get selectionMode() {
                        return this.state.get("selectionMode", "single");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on("click", (e) => {
                            this.closeAndReturn();
                        });
                        this.cancelButtonNode.on("click", (e) => {
                            this.close();
                        });
                        this.startUp();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Tags",
                            height: 350,
                            width: 500
                        };
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-manage-rules-tags-selection-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[role=grid]"),
                            selectionMode: this.selectionMode,
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            selection: {
                                mapping: (e) => {
                                    return e.ObjectName;
                                }
                            },
                            change: (e) => {
                                this.selections = e.selections.toArray();
                            },
                            dblclick: (e) => {
                                this.selections = e.selections.toArray();
                                this.closeAndReturn();
                            }
                        });
                    }
                    startUp() {
                        let service = new PDJS.Services.Views.ViewService();
                        if (this.viewStateId == null) {
                            service.getViewStateId({
                                viewCustomId: PDJS.Services.Views.BuiltInViews.RULE_SCRIPT_TAG_SELECTION,
                                success: (e) => {
                                    this.viewStateId = e.data.viewStateId;
                                    this.grid_init();
                                }
                            });
                        }
                    }
                    closeAndReturn() {
                        if (this.selections.length > 0) {
                            this.close({
                                name: "ok",
                                data: {
                                    tags: this.selections
                                }
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Selection Made",
                                message: "Nothing has been selected. Make a selection and try again."
                            });
                        }
                    }
                    static open(options) {
                        return new TagsSelectionDialog(options);
                    }
                }
                Tags.TagsSelectionDialog = TagsSelectionDialog;
            })(Tags = Rules.Tags || (Rules.Tags = {}));
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get user() {
                        return this.state.get("user");
                    }
                    set user(value) {
                        this.state.set("user", value);
                    }
                    load(user) {
                        this.user = user;
                    }
                    template() {
                        return `<div class="-pdjs-manage-security-groups-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addItems();
                    }
                    addItems() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Manage"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Users",
                            url: "#/module/users"
                        }));
                        if (!PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                                label: "Active Directory",
                                url: "#/module/active-directory"
                            }));
                        }
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Insights"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Group Members",
                            url: "#/module/insights-viewer/groupmembers"
                        }));
                    }
                }
                Groups.GroupsActions = GroupsActions;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get selection() {
                        return _.first(this.grid.selections);
                    }
                    get selections() {
                        return this.grid.selections;
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/groups": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                Groups.GroupsCommand = GroupsCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class DeleteGroupCommand extends Groups.GroupsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "group/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Delete the selected groups.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 0;
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Groups?",
                            message: "Delete the selected groups?",
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeServiceCall();
                                }
                            }
                        });
                    }
                    executeServiceCall() {
                        let service = new PDJS.Services.Security.GroupService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Delete | Groups",
                            taskStart: (e) => {
                                service.delete({
                                    ids: this.selections.map(group => group.id),
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                this.grid.refresh({ clear: true });
                            }
                        });
                    }
                }
                Groups.DeleteGroupCommand = DeleteGroupCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class EditGroupCommand extends Groups.GroupsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "group/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit the properties of the selected group.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length == 1;
                    }
                    execute(e) {
                        let group = _.first(this.selections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${group.name}`,
                            height: 550,
                            width: 650,
                            args: {
                                targetId: group.id,
                                targetType: "ProspectDirector.Web.Manage.Modules.Security.GroupUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Security.GroupArbiter"
                            },
                            select: {
                                "ok": (sender, e) => {
                                    sender.close();
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                }
                Groups.EditGroupCommand = EditGroupCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class NewGroupCommand extends Groups.GroupsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "group/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Create a new group.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "New | Group",
                            height: 550,
                            width: 650,
                            args: {
                                targetType: "ProspectDirector.Web.Manage.Modules.Security.GroupUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Security.GroupArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.grid.refresh({
                                        clear: true,
                                        selections: [e.target.id]
                                    });
                                }
                            }
                        });
                    }
                }
                Groups.NewGroupCommand = NewGroupCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class SyncGroupCommand extends Groups.GroupsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "sync/group",
                            label: "Sync Group",
                            icon: "arrows_circle.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Sync the selected group with Active Directory.",
                            iconSetId: "pdv2"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length === 1;
                    }
                    execute(e) {
                        this.startTask();
                    }
                    startTask() {
                        let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Sync Group",
                            showDetail: true,
                            taskStart: (args) => {
                                service.syncGroup({
                                    id: this.selection.id,
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e);
                                    }
                                });
                            },
                            close: (e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                }
                Groups.SyncGroupCommand = SyncGroupCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class SyncGroupsCommand extends Groups.GroupsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "sync/all-groups",
                            label: "Sync All Groups",
                            icon: "arrows_circle.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Sync all groups with Active Directory.",
                            iconSetId: "pdv2"
                        };
                    }
                    execute(e) {
                        this.startTask();
                    }
                    startTask() {
                        let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Sync Groups",
                            showDetail: true,
                            taskStart: (args) => {
                                service.syncGroups({
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e);
                                    }
                                });
                            },
                            close: (e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                }
                Groups.SyncGroupsCommand = SyncGroupsCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/security/groups");
                    }
                    registerCommands(e) {
                        e.commands.add(new Groups.DeleteGroupCommand());
                        e.commands.add(new Groups.EditGroupCommand());
                        e.commands.add(new Groups.NewGroupCommand());
                        e.commands.add(new Groups.SyncGroupCommand());
                        e.commands.add(new Groups.SyncGroupsCommand());
                    }
                }
                Groups.GroupsCommands = GroupsCommands;
                Jade.CommandGroups.add(GroupsCommands);
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-security-groups-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Groups</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Groups.GroupsGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "multiple",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No groups."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.ObjectName
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/security/groups:group/edit");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.Security.Groups.GroupsGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                Groups.GroupsGrid = GroupsGrid;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsGridContextMenu extends Jade.UI.ContextMenuSegment {
                    constructor() {
                        super(...arguments);
                        this.prefix = "pdjs/manage/security/groups";
                    }
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:group/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:group/delete`
                        }));
                        this.addActiveDirectoryCommands(e);
                    }
                    addActiveDirectoryCommands(e) {
                        if (PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            return;
                        }
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:sync/group`
                        }));
                    }
                }
                Groups.GroupsGridContextMenu = GroupsGridContextMenu;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    constructor() {
                        super(...arguments);
                        this.prefix = "pdjs/manage/security/groups";
                    }
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:group/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:group/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:group/delete`
                        }));
                        this.addActiveDirectoryCommands(e);
                    }
                    addActiveDirectoryCommands(e) {
                        if (PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            return;
                        }
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:sync/group`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:sync/all-groups`
                        }));
                    }
                }
                Groups.GroupsGridToolbar = GroupsGridToolbar;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupsModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-security-groups">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.actions_init();
                        this.module_init();
                    }
                    grid_init() {
                        this.m_grid = new Groups.GroupsGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.m_actions.load(item);
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    actions_init() {
                        this.m_actions = new Groups.GroupsActions({
                            insertAt: "div[data-id=pane-2]"
                        });
                        this.controls.add(this.m_actions);
                    }
                    module_init() {
                        let service = new PDJS.Services.Security.GroupService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false },
                                { resizable: true, size: "300px", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/groups": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                Groups.GroupsModule = GroupsModule;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupMembershipCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$editor", null);
                    }
                    get editor() {
                        return this.state.get("$editor");
                    }
                    get grid() {
                        return this.editor.grid;
                    }
                    get memberships() {
                        return this.editor.memberships;
                    }
                    get selections() {
                        return this.grid.getSelections().toArray();
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/groups/memberships": {
                                $editor: this.editor
                            }
                        }, { force: true });
                    }
                }
                Groups.GroupMembershipCommand = GroupMembershipCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class AddMembershipCommand extends Groups.GroupMembershipCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "membership/add",
                            label: "Add User",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Add a user to this group.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.memberships != null
                            && _.isArray(this.memberships.add)
                            && _.isArray(this.memberships.remove);
                    }
                    execute(e) {
                        PDJS.Shared.Security.IdentityBrowserDialog.open({
                            title: "Find Users",
                            filters: [PDJS.Core.Views.IdentityFilter.usersOnly()],
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.updateMemberships(e);
                                }
                            }
                        });
                    }
                    updateMemberships(selections) {
                        var members = [];
                        _.each(selections, (member) => {
                            members.push(member.id);
                            this.memberships.remove =
                                _.without(this.memberships.remove, member.id);
                            if (!_.includes(this.memberships.add, member.id)) {
                                this.memberships.add.push(member.id);
                            }
                        });
                        this.grid.refresh({
                            clear: true,
                            selections: selections.map(item => item.id)
                        });
                        this.editor.commit();
                    }
                }
                Groups.AddMembershipCommand = AddMembershipCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class RemoveMembershipCommand extends Groups.GroupMembershipCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "membership/remove",
                            label: "Remove User",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Remove a user from this group.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 0
                            && this.memberships != null
                            && _.isArray(this.memberships.add)
                            && _.isArray(this.memberships.remove);
                    }
                    execute(e) {
                        this.updateMemberships();
                    }
                    updateMemberships() {
                        _.each(this.selections, (member) => {
                            if (_.includes(this.memberships.add, member.id)) {
                                this.memberships.add = _.without(this.memberships.add, member.id);
                            }
                            if (!_.includes(this.memberships.remove, member.id)) {
                                this.memberships.remove.push(member.id);
                            }
                        });
                        this.grid.refresh({
                            clear: true
                        });
                        this.editor.commit();
                    }
                }
                Groups.RemoveMembershipCommand = RemoveMembershipCommand;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupMembershipCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/security/groups/memberships");
                    }
                    registerCommands(e) {
                        e.commands.add(new Groups.AddMembershipCommand());
                        e.commands.add(new Groups.RemoveMembershipCommand());
                    }
                }
                Groups.GroupMembershipCommands = GroupMembershipCommands;
                Jade.CommandGroups.add(GroupMembershipCommands);
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupMembershipEditor extends FeatureBlendJS.Views.MacroEditorBase {
                    get groupId() {
                        return this.source.getFeatureValue("groupId");
                    }
                    get viewStateId() {
                        return this.source.getFeatureValue("viewStateId");
                    }
                    get memberships() {
                        return this.state.get("memberships");
                    }
                    set memberships(value) {
                        this.state.set("memberships", value);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    commit() {
                        this.source.setFeatureValue("usersToAdd", this.memberships.add);
                        this.source.setFeatureValue("usersToRemove", this.memberships.remove);
                    }
                    resize() {
                        if (this.m_grid) {
                            this.m_grid.redraw();
                        }
                    }
                    template() {
                        return `<div class="-fb-group-membership-editor">
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.memberships = {
                            add: [],
                            remove: []
                        };
                        this.grid_init();
                        this.toolbar_init();
                        this.setCommandState();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `div[id=${this.ID}] div[role=grid]`,
                            height: "100%",
                            viewStateId: this.viewStateId,
                            defaultSelectionEnabled: false,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.ObjectName
                                    };
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            needContext: (e) => {
                                e.filters[0] = {
                                    id: "Members",
                                    params: {
                                        targetId: this.groupId,
                                        include: this.memberships.add,
                                        exclude: this.memberships.remove
                                    }
                                };
                            }
                        });
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Groups.GroupMembershipToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/groups/memberships": {
                                $editor: this
                            }
                        }, { force: true });
                    }
                }
                Groups.GroupMembershipEditor = GroupMembershipEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Users.GroupMembershipEditor", GroupMembershipEditor);
                });
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Groups;
            (function (Groups) {
                class GroupMembershipToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/security/groups/memberships";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:membership/add`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:membership/remove`
                        }));
                    }
                }
                Groups.GroupMembershipToolbar = GroupMembershipToolbar;
            })(Groups = Security.Groups || (Security.Groups = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get users() {
                        return this.state.get("users", []);
                    }
                    set users(value) {
                        this.state.set("users", value);
                    }
                    load(users) {
                        this.users = users;
                        this.m_chart.load(users);
                    }
                    template() {
                        return `<div class="-pdjs-manage-jobs-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addItems();
                    }
                    addItems() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Manage"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Groups",
                            url: "#/module/groups"
                        }));
                        if (!PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                                label: "Active Directory",
                                url: "#/module/active-directory"
                            }));
                        }
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "User Logins"
                        }));
                        this.m_chart = new Users.UserLoginsChart({
                            users: this.users
                        });
                        this.controls.add(this.m_chart);
                    }
                }
                Users.UsersActions = UsersActions;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get selection() {
                        return _.first(this.grid.selections);
                    }
                    get selections() {
                        return this.grid.selections;
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/users": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                Users.UsersCommand = UsersCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class BulkEditUserCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "user/bulk-edit",
                            label: "Bulk Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edit properties across selected users.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 1;
                    }
                    execute(e) {
                        Users.BulkEditDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    this.startTask(e);
                                }
                            }
                        });
                    }
                    startTask(args) {
                        let service = new PDJS.Services.Security.UserService();
                        let ids = this.selections.map(item => item.id);
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Bulk Edit | Users",
                            taskStart: (e) => {
                                service.bulkEdit({
                                    ids: ids,
                                    disabled: args.disabled,
                                    licensed: args.licensed,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                }
                Users.BulkEditUserCommand = BulkEditUserCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class DeleteUserCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "user/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Delete the selected users.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 0;
                    }
                    execute(e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Users?",
                            message: `Delete the selected users?`,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.executeServiceCall();
                                }
                            }
                        });
                    }
                    executeServiceCall() {
                        let service = new PDJS.Services.Security.UserService();
                        let ids = this.selections.map(item => item.id);
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Delete | Users",
                            taskStart: (e) => {
                                service.delete({
                                    ids: ids,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                this.grid.refresh({ clear: true });
                            }
                        });
                    }
                }
                Users.DeleteUserCommand = DeleteUserCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class EditUserCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "user/edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Edits the properties of the selected user.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length == 1;
                    }
                    execute(e) {
                        let user = _.first(this.selections);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `Edit | ${user.name}`,
                            height: 550,
                            width: 650,
                            args: {
                                targetId: user.id,
                                targetType: "ProspectDirector.Web.Manage.Modules.Security.UserUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Security.UserArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                }
                Users.EditUserCommand = EditUserCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class NewUserCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "user/new",
                            label: "New",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Create a new user.",
                            iconSetId: "pdjs"
                        };
                    }
                    execute(e) {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "New | User",
                            height: 550,
                            width: 650,
                            args: {
                                targetType: "ProspectDirector.Web.Manage.Modules.Security.UserUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Security.UserArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.grid.refresh({
                                        clear: true,
                                        selections: [e.target.id]
                                    });
                                }
                            }
                        });
                    }
                }
                Users.NewUserCommand = NewUserCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class SyncUserCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "sync/user",
                            label: "Sync User",
                            icon: "arrows_circle.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Sync the selected user with Active Directory.",
                            iconSetId: "pdv2"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length === 1;
                    }
                    execute(e) {
                        this.startTask();
                    }
                    startTask() {
                        let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Sync User",
                            showDetail: true,
                            taskStart: (args) => {
                                service.syncUser({
                                    id: this.selection.id,
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e);
                                    }
                                });
                            },
                            close: (e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                }
                Users.SyncUserCommand = SyncUserCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class SyncUsersCommand extends Users.UsersCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "sync/all-users",
                            label: "Sync All Users",
                            icon: "arrows_circle.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Sync all users with Active Directory.",
                            iconSetId: "pdv2"
                        };
                    }
                    execute(e) {
                        this.startTask();
                    }
                    startTask() {
                        let service = new PDJS.Services.ActiveDirectory.ActiveDirectoryService();
                        PDJS.Shared.TaskStatusDialog.open({
                            title: "Sync Users",
                            showDetail: true,
                            taskStart: (args) => {
                                service.syncUsers({
                                    success: (e) => {
                                        args.startPolling(e.data);
                                    },
                                    error: (e) => {
                                        args.abort(e);
                                    }
                                });
                            },
                            close: (e) => {
                                this.grid.refresh();
                            }
                        });
                    }
                }
                Users.SyncUsersCommand = SyncUsersCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/security/users");
                    }
                    registerCommands(e) {
                        e.commands.add(new Users.BulkEditUserCommand());
                        e.commands.add(new Users.DeleteUserCommand());
                        e.commands.add(new Users.EditUserCommand());
                        e.commands.add(new Users.NewUserCommand());
                        e.commands.add(new Users.SyncUserCommand());
                        e.commands.add(new Users.SyncUsersCommand());
                    }
                }
                Users.UsersCommands = UsersCommands;
                Jade.CommandGroups.add(UsersCommands);
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-security-users-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Users</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Users.UsersGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "multiple",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No users."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.ObjectName
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/security/users:user/edit");
                            },
                            change: (e) => {
                                this.changeCallback(e.selections.toArray());
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.Security.Users.UsersGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                Users.UsersGrid = UsersGrid;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersGridContextMenu extends Jade.UI.ContextMenuSegment {
                    constructor() {
                        super(...arguments);
                        this.prefix = "pdjs/manage/security/users";
                    }
                    onAddItems(e) {
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:user/edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:user/bulk-edit`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:user/delete`
                        }));
                        this.addActiveDirectoryCommands(e);
                    }
                    addActiveDirectoryCommands(e) {
                        if (PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            return;
                        }
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${this.prefix}:sync/user`
                        }));
                    }
                }
                Users.UsersGridContextMenu = UsersGridContextMenu;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    constructor() {
                        super(...arguments);
                        this.prefix = "pdjs/manage/security/users";
                    }
                    onAddItems(e) {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:user/new`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:user/edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:user/bulk-edit`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:user/delete`
                        }));
                        this.addActiveDirectoryCommands(e);
                    }
                    addActiveDirectoryCommands(e) {
                        if (PDJS.System.Environment.current.settings.isLocalAuthMode) {
                            return;
                        }
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:sync/user`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${this.prefix}:sync/all-users`
                        }));
                    }
                }
                Users.UsersGridToolbar = UsersGridToolbar;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UsersModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-security-users">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.actions_init();
                        this.module_init();
                    }
                    grid_init() {
                        this.m_grid = new Users.UsersGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (items) => {
                                this.m_actions.load(items);
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    actions_init() {
                        this.m_actions = new Users.UsersActions({
                            insertAt: "div[data-id=pane-2]"
                        });
                        this.controls.add(this.m_actions);
                    }
                    module_init() {
                        let service = new PDJS.Services.Security.UserService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false },
                                { resizable: true, min: "50px", size: "350px", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/users": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                Users.UsersModule = UsersModule;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UserLoginsChart extends Jade.UI.Control {
                    get chart() {
                        return this.chartNode.data("kendoChart");
                    }
                    get chartNode() {
                        return this.node.find("div[role=chart]");
                    }
                    get chartData() {
                        return this.state.get("chartData", []);
                    }
                    set chartData(value) {
                        this.state.set("chartData", value);
                    }
                    get users() {
                        return this.state.get("users", []);
                    }
                    set users(value) {
                        this.state.set("users", value);
                    }
                    get filterInput() {
                        return this.node.find("div[role=menu] select");
                    }
                    get showSelectedUsers() {
                        return this.filterInput.val() === "1";
                    }
                    load(users) {
                        this.users = users;
                        if (this.showSelectedUsers) {
                            this.getChartData();
                        }
                    }
                    template() {
                        return `<div class="-pdjs-manage-users-logins-chart">
                        <div role="menu">
                            <div>
                                <select>
                                    <option value="0">Show All Users</option>
                                    <option value="1">Show Selected Users</option>
                                </select>
                            </div>
                        </div>
                        <div role="chart"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.chart_init();
                        this.observer_init();
                        this.filterInput.on(Jade.BrowserEvent.CHANGE, () => { this.getChartData(); });
                    }
                    onResize(e) {
                        this.chart.setOptions({
                            chartArea: {
                                width: this.node.width(),
                                dataSource: this.chartData
                            },
                        });
                        this.chart.refresh();
                    }
                    observer_init() {
                        let debounced = _.debounce((e) => {
                            if (this.node.is(":visible")) {
                                this.onResize(e);
                            }
                        }, 250);
                        this.m_observer = new ResizeObserver((e) => {
                            debounced(e);
                        });
                        this.m_observer.observe(this.node.get(0));
                    }
                    chart_init() {
                        let existingChart = this.chartNode.data("kendoChart");
                        if (existingChart != null) {
                            existingChart.destroy();
                        }
                        this.chartNode.kendoChart({
                            title: {
                                color: "var(--visiv-theme-base-1-text-color)",
                                font: "14px Arial"
                            },
                            chartArea: {
                                background: "var(--visiv-theme-base-1-back-color)",
                                width: 250,
                                height: 250
                            },
                            plotArea: {
                                background: "var(--visiv-theme-base-1-back-color)"
                            },
                            legend: {
                                visible: false
                            },
                            axisDefaults: {
                                color: "var(--visiv-theme-base-1-text-color)",
                                labels: {
                                    color: "var(--visiv-theme-base-1-text-color)"
                                },
                                line: {
                                    color: "var(--visiv-theme-base-1-text-color)"
                                },
                                majorGridLines: {
                                    color: "var(--visiv-theme-base-1-text-color)"
                                },
                                minorGridLines: {
                                    color: "var(--visiv-theme-base-1-text-color)"
                                }
                            },
                            xAxis: [
                                {
                                    color: "var(--visiv-theme-base-1-text-color)",
                                    labels: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    }
                                }
                            ],
                            yAxis: [
                                {
                                    color: "var(--visiv-theme-base-1-text-color)",
                                    labels: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    }
                                }
                            ],
                            valueAxis: [
                                {
                                    color: "var(--visiv-theme-base-1-text-color)",
                                    labels: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    },
                                    majorGridLines: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    },
                                    minorGridLines: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    }
                                }
                            ],
                            categoryAxis: [
                                {
                                    color: "var(--visiv-theme-base-1-text-color)",
                                    field: "month",
                                    majorGridLines: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    },
                                    minorGridLines: {
                                        color: "var(--visiv-theme-base-1-text-color)"
                                    },
                                    labels: {
                                        template: (e) => {
                                            let year = e.dataItem.year.toString();
                                            return `${e.dataItem.monthName} ${year = year.substring(2)}`;
                                        },
                                        rotation: -90
                                    }
                                }
                            ],
                            series: [
                                {
                                    field: "count",
                                    name: "Logins",
                                    type: "line",
                                    color: "var(--visiv-theme-select-back-color)"
                                }
                            ]
                        });
                        this.getChartData();
                    }
                    getChartData() {
                        let service = new PDJS.Services.Security.UserService();
                        let userIds = this.showSelectedUsers ?
                            this.users.map(i => i.id) : [];
                        let title = ``;
                        if (!this.showSelectedUsers) {
                            title = "Logins for All Users";
                        }
                        else {
                            userIds.length === 1 ?
                                title = `Logins for ${_.first(this.users).name}` :
                                title = `Logins for ${userIds.length} Users`;
                        }
                        service.getLoginData({
                            userIds: userIds,
                            months: 12,
                            cutoff: Date.now(),
                            success: (e) => {
                                this.chartData = e.data;
                                this.chart.setOptions({
                                    title: {
                                        text: title
                                    },
                                    valueAxis: [{
                                            majorUnit: this.getMajorUnit(e.data)
                                        }]
                                });
                                this.chart.dataSource.data(e.data);
                                this.chart.refresh();
                            }
                        });
                    }
                    getMajorUnit(items) {
                        let max = 0;
                        items.forEach((item) => {
                            max = Math.max(max, item.count);
                        });
                        let digits = max.toString().length;
                        let lines = 5;
                        let unit = max / lines;
                        let pow = Math.pow(10, digits - 2);
                        let step = Math.ceil(unit / pow) * pow;
                        if (max == step * lines) {
                            step = step + pow;
                        }
                        return step < 1 ? 1 : step;
                    }
                }
                Users.UserLoginsChart = UserLoginsChart;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class BulkEditDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get upload() {
                        return this.m_upload;
                    }
                    set upload(value) {
                        this.m_upload = value;
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get licensedValue() {
                        return this.node.find("[role=ddl-licensed]").val();
                    }
                    get disabledValue() {
                        return this.node.find("[role=ddl-disabled]").val();
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-manage-security-users-batch-edit-dialog">
                    <div role="description">
                        Bulk edit "Licensed" and "Disabled" values for each selected user.
                    </div>
                    <div role="content">
                        <div role="group">
                            <div role="title">License:</div>
                            <select role="ddl-licensed">
                                <option value="">No Change</option>
                                <option value="0">Not Licensed</option>
                                <option value="1">Full</option>
                                <option value="2">Read-Only</option>
                            </select>
                        </div>
                        <div role="group">
                            <div role="title">Disabled:</div>
                            <select role="ddl-disabled">
                                <option value="">No Change</option>
                                <option value="true">True</option>
                                <option value="false">False</option>
                            </select>
                        </div>
                    </div>
                    <div class="-pd-dialog-button-deck">
                        <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                        <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return {
                            title: "User Bulk Edit",
                            width: "300px",
                            maximized: false,
                            resizable: false
                        };
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    okButton_onClick(e) {
                        let licensedValue = Jade.String.isNullOrWhiteSpace(this.licensedValue) ?
                            null : parseInt(this.licensedValue);
                        let disabledValue = Jade.String.isNullOrWhiteSpace(this.disabledValue) ?
                            null : (this.disabledValue == "true" ? true : false);
                        if (licensedValue == null && disabledValue == null) {
                            this.close();
                            return;
                        }
                        this.close({
                            name: "ok",
                            data: {
                                licensed: licensedValue,
                                disabled: disabledValue
                            }
                        });
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    static open(options = {}) {
                        return new BulkEditDialog(options);
                    }
                }
                Users.BulkEditDialog = BulkEditDialog;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UserMembershipCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$editor", null);
                    }
                    get editor() {
                        return this.state.get("$editor");
                    }
                    get grid() {
                        return this.editor.grid;
                    }
                    get memberships() {
                        return this.editor.memberships;
                    }
                    get selections() {
                        return this.grid.getSelections().toArray();
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/users/memberships": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                Users.UserMembershipCommand = UserMembershipCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class AddMembershipCommand extends Users.UserMembershipCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "membership/add",
                            label: "Add Group",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Add the user to a group.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.memberships != null
                            && _.isArray(this.memberships.add)
                            && _.isArray(this.memberships.remove);
                    }
                    execute(e) {
                        PDJS.Shared.Security.IdentityBrowserDialog.open({
                            title: "Find Groups",
                            filters: [
                                PDJS.Core.Views.IdentityFilter.groupsOnly(),
                                PDJS.Core.Views.IdentityFilter.excludeEveryone()
                            ],
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.updateMemberships(e);
                                }
                            }
                        });
                    }
                    updateMemberships(selections) {
                        var members = [];
                        _.each(selections, (member) => {
                            members.push(member.id);
                            this.memberships.remove =
                                _.without(this.memberships.remove, member.id);
                            if (!_.includes(this.memberships.add, member.id)) {
                                this.memberships.add.push(member.id);
                            }
                        });
                        this.grid.refresh({
                            clear: true,
                            selections: selections.map(item => item.id)
                        });
                        this.editor.commit();
                    }
                }
                Users.AddMembershipCommand = AddMembershipCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class RemoveMembershipCommand extends Users.UserMembershipCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "membership/remove",
                            label: "Remove Group",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            tooltip: "Remove the user from a group.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selections.length > 0
                            && this.memberships != null
                            && _.isArray(this.memberships.add)
                            && _.isArray(this.memberships.remove);
                    }
                    execute(e) {
                        this.updateMemberships();
                    }
                    updateMemberships() {
                        _.each(this.selections, (member) => {
                            if (_.includes(this.memberships.add, member.id)) {
                                this.memberships.add = _.without(this.memberships.add, member.id);
                            }
                            if (!_.includes(this.memberships.remove, member.id)) {
                                this.memberships.remove.push(member.id);
                            }
                        });
                        this.grid.refresh({
                            clear: true
                        });
                        this.editor.commit();
                    }
                }
                Users.RemoveMembershipCommand = RemoveMembershipCommand;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UserMembershipCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/security/users/memberships");
                    }
                    registerCommands(e) {
                        e.commands.add(new Users.AddMembershipCommand());
                        e.commands.add(new Users.RemoveMembershipCommand());
                    }
                }
                Users.UserMembershipCommands = UserMembershipCommands;
                Jade.CommandGroups.add(UserMembershipCommands);
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UserMembershipEditor extends FeatureBlendJS.Views.MacroEditorBase {
                    get userId() {
                        return this.source.getFeatureValue("userId");
                    }
                    get viewStateId() {
                        return this.source.getFeatureValue("viewStateId");
                    }
                    get memberships() {
                        return this.state.get("memberships");
                    }
                    set memberships(value) {
                        this.state.set("memberships", value);
                    }
                    get grid() {
                        return this.m_grid;
                    }
                    commit() {
                        this.source.setFeatureValue("membershipsToAdd", this.memberships.add);
                        this.source.setFeatureValue("membershipsToRemove", this.memberships.remove);
                    }
                    resize() {
                        if (this.m_grid) {
                            this.m_grid.redraw();
                        }
                    }
                    template() {
                        return `<div class="-fb-user-membership-editor">
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.memberships = {
                            add: [],
                            remove: []
                        };
                        this.grid_init();
                        this.toolbar_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `div[id=${this.ID}] div[role=grid]`,
                            height: "100%",
                            viewStateId: this.viewStateId,
                            defaultSelectionEnabled: false,
                            change: (e) => {
                                this.setCommandState();
                            },
                            needContext: (e) => {
                                e.filters[0] = {
                                    id: "Members",
                                    params: {
                                        targetId: this.userId,
                                        include: this.memberships.add,
                                        exclude: this.memberships.remove
                                    }
                                };
                            }
                        });
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Users.UserMembershipToolbar()]
                        });
                        this.controls.add(this.m_toolbar);
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/security/users/memberships": {
                                $editor: this
                            }
                        }, { force: true });
                    }
                }
                Users.UserMembershipEditor = UserMembershipEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Users.UserMembershipEditor", UserMembershipEditor);
                });
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Security;
        (function (Security) {
            var Users;
            (function (Users) {
                class UserMembershipToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/security/users/memberships";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:membership/add`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:membership/remove`
                        }));
                    }
                }
                Users.UserMembershipToolbar = UserMembershipToolbar;
            })(Users = Security.Users || (Security.Users = {}));
        })(Security = Manage.Security || (Manage.Security = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                template() {
                    return `<div class="-pdjs-manage-settings-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    let prefix = "pdjs/manage/settings";
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "System Configuration"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Import",
                        click: (e) => {
                            PDJS.Application.instance
                                .contexts
                                .current
                                .commands
                                .execute(`${prefix}:setting/import-config`);
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Export",
                        click: (e) => {
                            PDJS.Application.instance
                                .contexts
                                .current
                                .commands
                                .execute(`${prefix}:setting/export-config`);
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "System Cache"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Clear",
                        click: (e) => {
                            PDJS.Application.instance
                                .contexts
                                .current
                                .commands
                                .execute(`${prefix}:setting/clear-cache`);
                        }
                    }));
                }
            }
            Settings.SettingsActions = SettingsActions;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selection() {
                    return _.first(this.grid.selections);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/settings": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Settings.SettingsCommand = SettingsCommand;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class ClearCacheCommand extends Settings.SettingsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "setting/clear-cache",
                        label: "Clear Cache",
                        icon: "refresh.16px.font",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Clear the application cache.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Clear Cache?",
                        message: "Clear the application cache?",
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.callService();
                            }
                        }
                    });
                }
                callService() {
                    let service = new PDJS.Services.Settings.SettingsService();
                    service.clearCache({
                        success: (e) => {
                            PDJS.Shared.MessageStack.instance.success("Application cache has been cleared.");
                        }
                    });
                }
            }
            Settings.ClearCacheCommand = ClearCacheCommand;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class EditSettingCommand extends Settings.SettingsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "setting/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the selected setting.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selection != null;
                }
                execute(e) {
                    var uiSettings = this.getUiSettings();
                    uiSettings != null ?
                        this.showEditorDialog(uiSettings) :
                        this.showErrorDialog();
                }
                showEditorDialog(ui) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "Setting Editor",
                        minHeight: 100,
                        height: parseInt(ui.height),
                        width: parseInt(ui.width),
                        args: {
                            targetId: this.selection.id,
                            targetType: ui.model,
                            arbiterType: ui.arbiter,
                            layoutType: (ui.layout || FeatureBlendJS.Views.FeatureBlendLayoutType.Simple)
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh();
                            }
                        }
                    });
                }
                showErrorDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: "Error",
                        message: "Unable to edit system setting."
                    });
                }
                getUiSettings() {
                    let ui = null;
                    try {
                        ui = JSON.parse(this.selection.uiSettings);
                    }
                    catch (ex) {
                        return {};
                    }
                    return {
                        arbiter: ui.arbiter || "ProspectDirector.Web.Manage.Modules.Settings.SettingArbiter",
                        model: ui.model,
                        height: ui.height || "110px",
                        width: ui.width || "350px",
                        layout: ui.layout || FeatureBlendJS.Views.FeatureBlendLayoutType.Simple
                    };
                }
            }
            Settings.EditSettingCommand = EditSettingCommand;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class ExportConfigCommand extends Settings.SettingsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "setting/export-config",
                        label: "Export Configuration",
                        icon: "inbox_out.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Export an application configuration file.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Export Configuration?",
                        message: "Export application configuration?",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startExportTask();
                            }
                        }
                    });
                }
                startExportTask() {
                    let service = new PDJS.Services.Settings.SettingsService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Export | Configuration",
                        taskStart: (e) => {
                            service.exportConfig({
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            var _a;
                            if (((_a = e.output) === null || _a === void 0 ? void 0 : _a.path) != null) {
                                PDJS.Shared.Downloader.download({
                                    url: "~/Manage/Settings/DownloadConfigFile",
                                    params: {
                                        path: e.output.path,
                                        name: e.output.name
                                    }
                                });
                            }
                        }
                    });
                }
            }
            Settings.ExportConfigCommand = ExportConfigCommand;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class ImportConfigCommand extends Settings.SettingsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "setting/import-config",
                        label: "Import Configuration",
                        icon: "inbox_into.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Export the application's configuration.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Manage.Settings.ImportConfigDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.startImportTask(e.uploadId);
                            }
                        }
                    });
                }
                startImportTask(uploadId) {
                    let service = new PDJS.Services.Settings.SettingsService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Import | Configuration",
                        taskStart: (e) => {
                            service.importConfig({
                                uploadId: uploadId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        }
                    });
                }
            }
            Settings.ImportConfigCommand = ImportConfigCommand;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/settings");
                }
                registerCommands(e) {
                    e.commands.add(new Settings.ClearCacheCommand());
                    e.commands.add(new Settings.EditSettingCommand());
                    e.commands.add(new Settings.ExportConfigCommand());
                    e.commands.add(new Settings.ImportConfigCommand());
                }
            }
            Settings.SettingsCommands = SettingsCommands;
            Jade.CommandGroups.add(SettingsCommands);
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/settings";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:setting/edit`
                    }));
                }
            }
            Settings.SettingsContextMenu = SettingsContextMenu;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-settings-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">System Settings</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Settings.SettingsToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No settings."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name,
                                    uiSettings: e.UiSettings
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/settings:setting/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Settings.SettingsContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Settings.SettingsGrid = SettingsGrid;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-settings">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Settings.SettingsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Settings.SettingsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Settings.SettingsService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/settings": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Settings.SettingsModule = SettingsModule;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/settings";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:setting/edit`
                    }));
                }
            }
            Settings.SettingsToolbar = SettingsToolbar;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class ImportConfigDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                get uploadName() {
                    return this.state.get("uploadName");
                }
                set uploadName(value) {
                    this.state.set("uploadName", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-upload-zip-dialog">
                    <div role="text">Select a ".vpc" file to upload and import a previously exported configuration into the system.</div>
                    <div role="progress"></div>
                    <div role="buttons">
                        <button class="-pdjs-dialog-button" data-id="ok" disabled>Import</button>
                        <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Import | Configuration",
                        width: "400px",
                        resizable: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                uploadId: this.uploadId,
                                uploadName: this.uploadName
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=progress]",
                        mimeTypes: [{ title: "Configuration File", extensions: "vpc" }],
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.uploadName = e.name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options) {
                    return new ImportConfigDialog(options);
                }
            }
            Settings.ImportConfigDialog = ImportConfigDialog;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class SettingEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get label() {
                    return this.source.getFeatureValue("label");
                }
                get isReadOnly() {
                    return this.source.getFeatureValue("isReadOnly", false);
                }
                get labelNode() {
                    return this.node.children("label");
                }
                get contentNode() {
                    return this.node.children("div");
                }
                template() {
                    return `
            <div>
                <label style="display:inline-block;font-weight:bold;height:25px;line-height:25px;padding-right:25px;">${this.label}</label>
                <div>
                    ${this.contentTemplate()}
                </div>
            </div>`;
                }
                contentTemplate() {
                    return ``;
                }
                onValidationErrors() {
                    if (this.source.feature.errors.length == 0) {
                        this.labelNode.css({
                            color: "var(--visiv-error-fore-color)",
                            backgroundImage: ""
                        });
                        return;
                    }
                    this.labelNode.css({
                        color: "var(--",
                        backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x16)})`,
                        backgroundRepeat: "no-repeat",
                        backgroundPosition: "right 5px top 5px"
                    });
                    let text = this.source.feature.errors.flatMap((item) => {
                        return item.message;
                    }).join("</div><div>");
                    PDJS.Shared.PopOver.validation(this.labelNode, `<div>${text}</div>`);
                }
            }
            Settings.SettingEditor = SettingEditor;
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class BooleanSettingEditor extends Settings.SettingEditor {
                get trueNode() {
                    return this.contentNode.find("input[value=true]");
                }
                get falseNode() {
                    return this.contentNode.find("input[value=false]");
                }
                contentTemplate() {
                    return `
                <label style="display:inline-block;margin-bottom:10px;">
                    <input type="radio" name="value" value="true" class="-pd-macro-editor-input" />&nbsp;True
                </label>
                <br/>
                <label style="display:inline-block;">
                    <input type="radio" name="value" value="false" class="-pd-macro-editor-input" />&nbsp;False
                </label>
                <br/>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    if (this.source.primaryValue === true) {
                        this.trueNode.prop("checked", true);
                    }
                    else {
                        this.falseNode.prop("checked", true);
                    }
                    this.node.find("[type=radio]:checked").focus();
                    this.trueNode.prop("disabled", this.isReadOnly);
                    this.falseNode.prop("disabled", this.isReadOnly);
                    this.falseNode.on(Jade.BrowserEvent.CLICK, () => {
                        this.source.primaryValue = false;
                    });
                    this.trueNode.on(Jade.BrowserEvent.CLICK, () => {
                        this.source.primaryValue = true;
                    });
                }
            }
            Settings.BooleanSettingEditor = BooleanSettingEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.BooleanSettingFeature", BooleanSettingEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class IntegerSettingEditor extends Settings.SettingEditor {
                get input() {
                    return this.contentNode.find("input[type=text]");
                }
                contentTemplate() {
                    return `
                <input type='text' class='-pd-macro-editor-input' style='box-sizing:border-box;width:100%;padding:3px;height:22px;'/><br/>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input.val(this.source.primaryValue);
                    this.input.select();
                    this.input.focus();
                    this.input.prop("disabled", this.isReadOnly);
                    this.input.on(Jade.BrowserEvent.BLUR, () => {
                        this.source.primaryValue = this.input.val();
                    });
                }
            }
            Settings.IntegerSettingEditor = IntegerSettingEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.IntegerSettingFeature", IntegerSettingEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class ListSettingEditor extends Settings.SettingEditor {
                get input() {
                    return this.contentNode.find("select");
                }
                get items() {
                    return this.source.getFeatureValue("values");
                }
                contentTemplate() {
                    return `<select style="box-sizing:border-box;width:100%;padding:3px;" class="-pd-macro-editor-input"></select><br/>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.items.forEach((item) => {
                        this.input.append(`<option value="${item.value}">${item.key}</option>`);
                    });
                    this.input.val(this.source.primaryValue);
                    this.input.focus();
                    this.input.prop("disabled", this.isReadOnly);
                    this.input.on(Jade.BrowserEvent.CHANGE, () => {
                        this.source.primaryValue = this.input.val();
                    });
                }
            }
            Settings.ListSettingEditor = ListSettingEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.ListSettingFeature", ListSettingEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class MarkupTextualEditor extends Settings.SettingEditor {
                get editorNode() {
                    return this.node.find(".-pd-ace-editor");
                }
                get editor() {
                    return this.m_editor;
                }
                set editor(value) {
                    this.m_editor = value;
                }
                focus() {
                    super.focus();
                    setTimeout(() => {
                        this.setEditorValueAndFocus();
                    }, 200);
                }
                template() {
                    return `
                <div style="font-size:12px;position:absolute;inset:0;border:1px solid #AAAAAA;">
                    <div class='-pd-ace-editor'></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                    this.m_editor = ace.edit(this.editorNode[0]);
                    this.editor.setTheme("ace/theme/chrome");
                    this.editor.getSession().setMode("ace/mode/html");
                    this.editor.renderer.setShowPrintMargin(false);
                    this.editor.setOption("highlightActiveLine", false);
                    this.editor.setOption("scrollPastEnd", true);
                    this.editor.getSession().on("change", () => {
                        if (this.editor) {
                            this.source.primaryValue = this.editor.getSession().getValue();
                        }
                    });
                    this.setEditorValueAndFocus();
                }
                setEditorValueAndFocus() {
                    let value = this.source.primaryValue;
                    if (this.editor != null && value != null) {
                        this.editor.setValue(value);
                        this.editor.focus();
                        this.editor.selection.moveCursorTo(0, 0);
                    }
                }
            }
            Settings.MarkupTextualEditor = MarkupTextualEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.MarkupTextualEditorFeature", MarkupTextualEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class MarkupVisualEditor extends Settings.SettingEditor {
                get containerNode() {
                    return this.node.find("div[role=container]");
                }
                get editorNode() {
                    return this.node.find(".mce-tinymce");
                }
                get editor() {
                    return this.m_editor;
                }
                set editor(value) {
                    this.m_editor = value;
                }
                get content() {
                    return this.source.getRemoteFeatureValue("value", "");
                }
                set content(value) {
                    this.source.setRemoteFeatureValue("value", value);
                }
                focus() {
                    super.focus();
                    if (this.editor != null) {
                        setTimeout(() => {
                            this.editor.setContent(this.content);
                            this.editor_resize();
                        }, 200);
                    }
                }
                template() {
                    return `<div class="-fb-rich-text-editor">
                        <div role="container">
                            <textarea></textarea>
                        </div>
                    </div>`;
                }
                resize() {
                    this.editor_resize();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                    setTimeout(() => { this.editor_resize(); }, 300);
                    this.addResizeObserver();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.m_observer) {
                        this.m_observer.unobserve(this.node.get(0));
                    }
                }
                editor_init() {
                    tinymce.init({
                        selector: `#${this.ID} > DIV > TEXTAREA`,
                        document_base_url: Jade.Path.resolve("~/scripts/pdjs/external/tinymce"),
                        content_css: Jade.Path.resolve("~/shared/theme/manage", { v: Jade.Guid.new().toString() }),
                        apply_source_formatting: true,
                        plugins: "link hr textcolor colorpicker",
                        menubar: false,
                        statusbar: false,
                        toolbar: [
                            "undo redo | fontsizeselect forecolor backcolor | bold italic | alignleft aligncenter alignright | bullist numlist hr | outdent indent | link unlink"
                        ],
                        color_picker_callback: (sender, e) => { this.editor_onShowColorPicker(e); },
                        fontsize_formats: "8px 10px 11px 12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 28px 32px 36px 40px",
                        setup: (editor) => { this.editor_onSetup(editor); }
                    });
                }
                editor_onSetup(editor) {
                    this.m_editor = editor;
                    editor.on('init', (e) => {
                        this.editor_loadContent();
                        this.editorNode.css({
                            borderWidth: 0,
                            borderStyle: "none"
                        });
                    });
                    editor.on('change', () => {
                        this.content = this.editor.getContent();
                    });
                }
                editor_onShowColorPicker(callback) {
                    PDJS.JS.ProspectDirector.Web.UI.FeatureSets.Editors.ColorEditorDialog.open({
                        config: {
                            title: "Text Color"
                        },
                        data: {
                            hex: "#000000"
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                callback(e);
                            }
                        }
                    });
                }
                editor_loadContent() {
                    if (_.isString(this.content)) {
                        this.editor.setContent(this.content);
                    }
                }
                editor_resize() {
                    let max = this.containerNode.outerHeight() - 4;
                    max -= this.containerNode.find('.mce-menubar.mce-toolbar').outerHeight();
                    max -= this.containerNode.find('.mce-toolbar-grp').outerHeight();
                    this.containerNode.find('.mce-edit-area').height(max);
                    this.containerNode.find('IFRAME').height(max);
                }
                addResizeObserver() {
                    let debounced = _.debounce((e) => {
                        this.editor_resize();
                    }, 100);
                    this.m_observer = new ResizeObserver((e) => {
                        debounced(e);
                    });
                    this.m_observer.observe(this.node.get(0));
                }
            }
            Settings.MarkupVisualEditor = MarkupVisualEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.MarkupVisualEditorFeature", MarkupVisualEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class RichTextEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get richText() {
                    return this.m_richText;
                }
                set richText(value) {
                    this.m_richText = value;
                }
                get content() {
                    return this.source.getFeatureValue(this.contentPropertyName, "");
                }
                set content(value) {
                    this.source.setFeatureValue(this.contentPropertyName, value);
                }
                get contentPropertyName() {
                    return this.getPropertyName("primaryValue");
                }
                get htmlTheme() {
                    return this.source.state.get("htmlTheme");
                }
                get textTheme() {
                    return this.source.state.get("textTheme");
                }
                get textStyle() {
                    return this.source.state.get("textStyle");
                }
                get views() {
                    return this.source.state.get("views");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.richText_init();
                }
                richText_init() {
                    this.richText = new PDJS.Shared.UI.Controls.RichText({
                        change: (e) => {
                            this.content = e.value;
                        },
                        content: this.content,
                        htmlTheme: this.htmlTheme,
                        textTheme: this.textTheme,
                        textStyle: this.textStyle,
                        views: this.views
                    });
                    this.controls.add(this.richText);
                }
            }
            Settings.RichTextEditor = RichTextEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.Macro.RichTextEditor", RichTextEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Settings;
        (function (Settings) {
            class StringSettingEditor extends Settings.SettingEditor {
                get input() {
                    return this.contentNode.find("input[type=text]");
                }
                contentTemplate() {
                    return `<input type="text" class="-pd-macro-editor-input" style="box-sizing:border-box;width:100%;padding:3px;height:22px;"/><br/>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input.val(this.source.primaryValue);
                    this.input.select();
                    this.input.focus();
                    this.input.prop("disabled", this.isReadOnly);
                    this.input.on(Jade.BrowserEvent.BLUR, () => {
                        this.source.primaryValue = this.input.val();
                    });
                }
            }
            Settings.StringSettingEditor = StringSettingEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PD.Manage.Modules.StringSettingFeature", StringSettingEditor);
            });
        })(Settings = Manage.Settings || (Manage.Settings = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get variable() {
                    return this.state.get("variable");
                }
                set variable(value) {
                    this.state.set("variable", value);
                }
                load(variable) {
                    this.variable = variable;
                }
                template() {
                    return `<div class="-pdjs-manage-system-variables-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Variables"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Placeholder Link",
                        click: (e) => {
                            Jade.UI.Dialogs.MessageDialog.open({
                                message: "Not Implemented"
                            });
                        }
                    }));
                }
            }
            SystemVariables.SystemVariablesActions = SystemVariablesActions;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/system-variables": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            SystemVariables.SystemVariablesCommand = SystemVariablesCommand;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class DeleteVariableCommand extends SystemVariables.SystemVariablesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "variable/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete the selected system variables.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Variables?",
                        message: `Delete the selected system variable(s)?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startTask();
                            }
                        }
                    });
                }
                startTask(confirmed = false) {
                    let service = new PDJS.Services.SystemVariables.SystemVariablesService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete | Variables",
                        taskStart: (e) => {
                            service.deleteVariables({
                                ids: this.selections.map(item => item.id),
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
            }
            SystemVariables.DeleteVariableCommand = DeleteVariableCommand;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class EditVariableCommand extends SystemVariables.SystemVariablesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "variable/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit the selected system variable.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let variable = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${variable.name}`,
                        height: 550,
                        width: 500,
                        args: {
                            targetId: variable.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.SystemVariables.SystemVariableUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.SystemVariables.SystemVariableArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                var _a;
                                ((_a = e.output) === null || _a === void 0 ? void 0 : _a.taskId) != null ?
                                    this.openTaskStatusDialog(e.output.taskId) :
                                    this.grid.refresh();
                            }
                        }
                    });
                }
                openTaskStatusDialog(taskId) {
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Edit | Variable",
                        taskStart: (e) => {
                            e.startPolling({ taskId: taskId });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh();
                        }
                    });
                }
            }
            SystemVariables.EditVariableCommand = EditVariableCommand;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class NewVariableCommand extends SystemVariables.SystemVariablesCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "variable/new",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new system variable.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | System Variable",
                        height: 450,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.SystemVariables.SystemVariableUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.SystemVariables.SystemVariableArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            SystemVariables.NewVariableCommand = NewVariableCommand;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/system-variables");
                }
                registerCommands(e) {
                    e.commands.add(new SystemVariables.DeleteVariableCommand());
                    e.commands.add(new SystemVariables.EditVariableCommand());
                    e.commands.add(new SystemVariables.NewVariableCommand());
                }
            }
            SystemVariables.SystemVariablesCommands = SystemVariablesCommands;
            Jade.CommandGroups.add(SystemVariablesCommands);
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-system-variables-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">System Variables</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new SystemVariables.SystemVariablesToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No system variables."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName,
                                    type: e.Type
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/system-variables:variable/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.SystemVariables.SystemVariablesGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            SystemVariables.SystemVariablesGrid = SystemVariablesGrid;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/system-variables";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:variable/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:variable/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:variable/delete`
                    }));
                }
            }
            SystemVariables.SystemVariablesGridContextMenu = SystemVariablesGridContextMenu;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-system-variables">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new SystemVariables.SystemVariablesGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new SystemVariables.SystemVariablesActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.SystemVariables.SystemVariablesService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/system-variables": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            SystemVariables.SystemVariablesModule = SystemVariablesModule;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/system-variables";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:variable/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:variable/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:variable/delete`
                    }));
                }
            }
            SystemVariables.SystemVariablesToolbar = SystemVariablesToolbar;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get tag() {
                    return this.state.get("tag");
                }
                set tag(value) {
                    this.state.set("tag", value);
                }
                load(tag) {
                    this.tag = tag;
                }
                template() {
                    return `<div class="-pdjs-manage-tags-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Expressions"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "New Expression...",
                        click: (e) => {
                            PDJS.Manage.Tags.NewExpressionDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/tag-expressions",
                        label: "Manage Expressions"
                    }));
                }
            }
            Tags.TagsActions = TagsActions;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsCommand extends Jade.Command {
                constructor(options = {}) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                get selectedIds() {
                    return this.grid.selections.map(item => item.id);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/tags": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Tags.TagsCommand = TagsCommand;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class DeleteTagCommand extends Tags.TagsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "tag/delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Delete a tag.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length > 0;
                }
                execute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Tags?",
                        message: `Delete the selected tags?`,
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.startTask();
                            }
                        }
                    });
                }
                startTask(confirmed = false) {
                    let service = new PDJS.Services.Tags.TagService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Delete | Tags",
                        taskStart: (e) => {
                            service.delete({
                                ids: this.selectedIds,
                                confirmed: confirmed,
                                success: (e2) => {
                                    if (e2.data.requiresConfirmation && !confirmed) {
                                        this.showInUseDialog(e);
                                        return;
                                    }
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskSuccess: (e) => {
                            this.grid.refresh({ clear: true });
                        }
                    });
                }
                showInUseDialog(taskArgs) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        title: "Tags In Use",
                        message: "Some of the selected tags are in use. Proceed with the tag deletion?",
                        select: {
                            yes: (sender, e) => {
                                sender.close();
                                taskArgs.close();
                                this.startTask(true);
                            },
                            no: (sender, e) => {
                                sender.close();
                                taskArgs.abort();
                                taskArgs.close();
                            }
                        }
                    });
                }
            }
            Tags.DeleteTagCommand = DeleteTagCommand;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class EditTagCommand extends Tags.TagsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "tag/edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: false,
                        display: "icon label",
                        tooltip: "Edit a tag.",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length == 1;
                }
                execute(e) {
                    let tag = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${tag.name}`,
                        height: 550,
                        width: 500,
                        args: {
                            targetId: tag.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.TagUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.TagArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh();
                            }
                        }
                    });
                }
            }
            Tags.EditTagCommand = EditTagCommand;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class NewTagCommand extends Tags.TagsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "tag/new",
                        label: "New Tag",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        tooltip: "Create a new tag.",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Tag",
                        height: 550,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.TagUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.TagArbiter"
                        },
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            Tags.NewTagCommand = NewTagCommand;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/tags");
                }
                registerCommands(e) {
                    e.commands.add(new Tags.DeleteTagCommand());
                    e.commands.add(new Tags.EditTagCommand());
                    e.commands.add(new Tags.NewTagCommand());
                }
            }
            Tags.TagsCommands = TagsCommands;
            Jade.CommandGroups.add(TagsCommands);
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-tags-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Tags</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Tags.TagsGridToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No tags."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.ObjectName
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/tags:tag/edit");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [{
                                type: "PDJS.Manage.Tags.TagsGridContextMenu"
                            }]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Tags.TagsGrid = TagsGrid;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/tags";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:tag/new`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:tag/edit`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:tag/delete`
                    }));
                }
            }
            Tags.TagsGridContextMenu = TagsGridContextMenu;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/tags";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:tag/new`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:tag/edit`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:tag/delete`
                    }));
                }
            }
            Tags.TagsGridToolbar = TagsGridToolbar;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-tags">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Tags.TagsGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Tags.TagsActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Tags.TagService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/tags": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Tags.TagsModule = TagsModule;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class ExpressionsSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get selection() {
                    return this.state.get("selection");
                }
                set selection(value) {
                    this.state.set("selection", value);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on("click", (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on("click", (e) => {
                        this.close({
                            name: "cancel"
                        });
                    });
                    this.startUp();
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Expression",
                        height: 350,
                        width: 500
                    };
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-tags-expressions-selection-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        expressionId: item.ObjectId,
                                        expressionName: item.ObjectName
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.selection = e.selection;
                        },
                        dblclick: (e) => {
                            this.selection = e.selection;
                            this.closeAndReturn();
                        }
                    });
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    if (this.viewStateId == null) {
                        service.getViewStateId({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.EXPRESSION_SELECTION,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                            }
                        });
                    }
                }
                closeAndReturn() {
                    if (this.selection != null) {
                        this.close({
                            name: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "Nothing has been selected. Make a selection and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                static open(options) {
                    return new ExpressionsSelectionDialog(options);
                }
            }
            Tags.ExpressionsSelectionDialog = ExpressionsSelectionDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class NewExpressionDialog extends PDJS.Shared.Features.FeatureDialogForNhib {
                static open(options = {}) {
                    return new Tags.NewTagDialog({
                        title: "New | Expression",
                        height: 400,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionArbiter"
                        }
                    });
                }
            }
            Tags.NewExpressionDialog = NewExpressionDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class NewTagDialog extends PDJS.Shared.Features.FeatureDialogForNhib {
                static open(options = {}) {
                    return new NewTagDialog({
                        title: "New | Tag",
                        height: 400,
                        width: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.TagUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.TagArbiter"
                        }
                    });
                }
            }
            Tags.NewTagDialog = NewTagDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagPatternDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get pattern() {
                    return this.state.get("pattern", "");
                }
                get buttonOk() {
                    return this.node.find("button[data-command=ok]");
                }
                get buttonCancel() {
                    return this.node.find("button[data-command=cancel]");
                }
                get variableTitle() {
                    return (Jade.String.isNullOrWhiteSpace(this.pattern) ? "Add" : "Edit")
                        + " | Tag Pattern";
                }
                template() {
                    return super.template(`
                <div class="-pdjs-tag-pattern-dialog">
                    <div role="input"></div>
                    <div role="deck">
                        <button
                            data-command="ok"
                            class="-jadeui-dialog-button">
                            OK
                        </button>
                        <button 
                            data-command="cancel"
                            class="-jadeui-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input_init();
                    this.buttonCancel.on(Jade.BrowserEvent.CLICK, () => {
                        this.close();
                    });
                    this.buttonOk.on(Jade.BrowserEvent.CLICK, () => {
                        this.closeAndReturn();
                    });
                    this.setWindowOptions({
                        title: this.variableTitle
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.m_input.value = this.pattern;
                }
                onInputReturnKeystroke() {
                    this.buttonOk.focus();
                    this.buttonOk.click();
                }
                getDefaultOptions() {
                    return {
                        title: `Add | Tag Pattern`,
                        height: "105px",
                        width: "400px",
                        resizable: false
                    };
                }
                input_init() {
                    this.m_input = new PDJS.Shared.UI.Controls.Fields.StringField({
                        insertAt: "div[role=input]",
                        label: "Tag Pattern",
                        enabled: true,
                        required: true,
                        validateOnBlur: false
                    });
                    this.controls.add(this.m_input);
                    this.m_input.validators.add(new PDJS.Shared.UI.Controls.Fields.FieldValidatorRegex({
                        regularExpression: "^([A-Za-z]|_|\\*)+([\\w]|[\\d]|_|\\*)*$",
                        expectedResult: true,
                        flags: "gi",
                        message: "Pattern must begin with an _ or letter."
                    }));
                    this.m_input.validators.add(new PDJS.Shared.UI.Controls.Fields.FieldValidatorRegex({
                        regularExpression: "\\*+",
                        expectedResult: true,
                        flags: "gi",
                        message: `Pattern must contain at least one wildcard "*" "character.`
                    }));
                }
                closeAndReturn() {
                    this.m_input.validate();
                    if (this.m_input.isValid) {
                        this.close({
                            name: "ok",
                            data: {
                                oldPattern: this.pattern,
                                newPattern: this.m_input.value
                            }
                        });
                    }
                }
                static open(options) {
                    return new TagPatternDialog(options);
                }
            }
            Tags.TagPatternDialog = TagPatternDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class TagsSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get selections() {
                    return this.state.get("selection");
                }
                set selections(value) {
                    this.state.set("selection", value);
                }
                get selectionMode() {
                    return this.state.get("selectionMode", "single");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on("click", (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on("click", (e) => {
                        this.close();
                    });
                    this.startUp();
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Tags",
                        height: 350,
                        width: 500
                    };
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-tags-selection-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[role=grid]"),
                        selectionMode: this.selectionMode,
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            mapping: (e) => {
                                return e.ObjectName;
                            }
                        },
                        change: (e) => {
                            this.selections = e.selections.toArray();
                        },
                        dblclick: (e) => {
                            this.selections = e.selections.toArray();
                            this.closeAndReturn();
                        }
                    });
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    if (this.viewStateId == null) {
                        service.getViewStateId({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.TAG_SELECTION,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                            }
                        });
                    }
                }
                closeAndReturn() {
                    if (this.selections.length > 0) {
                        this.close({
                            name: "ok",
                            data: {
                                tags: this.selections
                            }
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "Nothing has been selected. Make a selection and try again."
                        });
                    }
                }
                static open(options) {
                    return new TagsSelectionDialog(options);
                }
            }
            Tags.TagsSelectionDialog = TagsSelectionDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Tags;
        (function (Tags) {
            class ExpressionGeneralFeature extends FeatureBlendJS.Views.MacroEditorBase {
                get name() {
                    return this.source.getFeatureValue("name");
                }
                set name(value) {
                    this.source.setFeatureValue("name", value);
                }
                get description() {
                    return this.source.getFeatureValue("description");
                }
                set description(value) {
                    this.source.setFeatureValue("description", value);
                }
                get expression() {
                    return this.source.getFeatureValue("text");
                }
                set expression(value) {
                    this.source.setFeatureValue("text", value);
                }
                get buttonNode() {
                    return this.node.children("button");
                }
                resize() {
                    if (this.m_editor != null) {
                        this.m_editor.redraw();
                    }
                }
                template() {
                    return `<div style="position:absolute;inset:0;">
                        <button title="Insert tag..."><img src="${Jade.IconSet.get("pdv2").resolve("tags.png", Jade.IconSetSizeSpecificDirectory.x16)}"/></button>
                    </div>`;
                }
                onActivate(e) {
                    this.m_name = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Name",
                        required: true,
                        blur: () => {
                            this.name = this.m_name.value;
                        }
                    });
                    this.m_description = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Description",
                        multiline: true,
                        height: 110,
                        blur: () => {
                            this.description = this.m_description.value;
                        }
                    });
                    this.m_editor = new PDJS.Shared.UI.Controls.Fields.ExpressionField({
                        label: "Expression",
                        required: true,
                        change: () => {
                            this.expression = this.m_editor.value;
                        }
                    });
                    this.controls.add(this.m_name);
                    this.controls.add(this.m_description);
                    this.controls.add(this.m_editor);
                    this.m_editor.node.css({
                        position: "absolute",
                        top: "160px",
                        right: 0,
                        left: 0,
                        bottom: 0
                    });
                    this.buttonNode.css({
                        padding: "1px",
                        minHeight: "20px",
                        maxHeight: "20px",
                        minWidth: "20px",
                        maxWidth: "20px",
                        position: "absolute",
                        top: "163px",
                        right: 0,
                        zIndex: 1,
                        boxSizing: "border-box"
                    });
                    this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                        Tags.TagsSelectionDialog.open({
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    this.m_editor.insertTag(_.first(e.tags));
                                    this.m_editor.focus();
                                },
                                cancel: () => {
                                    this.m_editor.focus();
                                }
                            }
                        });
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.m_name.value = this.name;
                    this.m_description.value = this.description;
                    this.m_editor.value = this.expression;
                    this.m_name.focus();
                }
                onValidationErrors() {
                    _.each(this.source.feature.errors, (error) => {
                        switch (error.propertyName) {
                            case "Name":
                                this.m_name.errors.clear();
                                this.m_name.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                                    message: error.message
                                }));
                                break;
                            case "Description":
                                this.m_description.errors.clear();
                                this.m_description.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                                    message: error.message
                                }));
                                break;
                            case "Text":
                                this.m_editor.errors.clear();
                                this.m_editor.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                                    message: error.message
                                }));
                                if (error.tags["tags"]) {
                                    this.m_editor.highlight(error.tags["tags"]);
                                }
                                break;
                        }
                    });
                }
            }
            Tags.ExpressionGeneralFeature = ExpressionGeneralFeature;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Tags.ExpressionGeneralFeature", ExpressionGeneralFeature);
            });
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            let Events;
            (function (Events) {
                Events["ThemeCreate"] = "ThemeCreate";
                Events["LoadThemes"] = "LoadThemes";
            })(Events = Themes.Events || (Themes.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static loadThemesPublish() {
                    this.global.publish(Events.LoadThemes);
                }
                static setThemePublish() {
                    this.global.publish(Events.LoadThemes);
                }
                static loadThemesSubscribe(handler) {
                    return this.global.subscribe(Events.LoadThemes, handler);
                }
                static setThemeSubscribe(handler) {
                    this.global.subscribe(Events.LoadThemes, handler);
                }
            }
            Themes.EventsHub = EventsHub;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get themeId() {
                    var _a;
                    return (_a = this.theme) === null || _a === void 0 ? void 0 : _a.id;
                }
                get theme() {
                    return this.state.get("theme");
                }
                set theme(value) {
                    this.state.set("theme", value);
                }
                template() {
                    return `<div class="-pdjs-manage-themes-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                load(theme) {
                    this.theme = theme;
                    this.controls.clear();
                    this.addThemeItems();
                    this.addThemesItems();
                    this.addCustomColorItems();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addThemeItems();
                    this.addThemesItems();
                }
                addThemeItems() {
                    if (this.themeId == null) {
                        return;
                    }
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Current Theme"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Export",
                        click: (e) => {
                            PDJS.Shared.Downloader.download({
                                url: "~/Manage/Theme/ExportTheme",
                                params: {
                                    themeId: this.themeId
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Batch Update Colors",
                        click: (e) => {
                            Themes.UpdateColorsDialog.open({
                                theme: this.theme
                            });
                        }
                    }));
                }
                addThemesItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Themes"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Import",
                        click: (e) => {
                            Themes.ImportDialog.open();
                        }
                    }));
                }
                addCustomColorItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "System Colors"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Branding Colors",
                        click: (e) => {
                            PDJS.Shared.Features.FeatureDialogForNhib.open({
                                title: "Edit | Branding Colors",
                                width: 420,
                                height: 510,
                                args: {
                                    targetType: "ProspectDirector.Web.Shared.Modules.Themes.BrandingUIO",
                                    arbiterType: "ProspectDirector.Web.Manage.Modules.Themes.BrandingArbiter"
                                },
                                select: {
                                    ok: (sender, e) => {
                                        PDJS.Shared.Themes.Theme.manage.refreshTheme();
                                    }
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Custom Colors",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/themes:theme/manage-custom-colors");
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Import",
                        click: (e) => {
                            Themes.Custom.ImportDialog.open();
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Export",
                        click: (e) => {
                            PDJS.Shared.Downloader.download({
                                url: "~/Manage/ThemeColor/ExportColors",
                                params: {
                                    themeId: this.themeId
                                }
                            });
                        }
                    }));
                }
            }
            Themes.ThemesActions = ThemesActions;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$editor", null);
                    this.state.set("$list", null);
                    this.state.set("$theme", null);
                }
                get editor() {
                    return this.state.get("$editor");
                }
                get list() {
                    return this.state.get("$list");
                }
                get theme() {
                    var _a;
                    return this.state.get("$theme", (_a = this.list) === null || _a === void 0 ? void 0 : _a.selection);
                }
                get themeId() {
                    var _a;
                    return (_a = this.theme) === null || _a === void 0 ? void 0 : _a.id;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/themes": {}
                    }, { force: true });
                    PDJS.Application
                        .instance
                        .contexts
                        .current.commands.setState({
                        "pdjs/manage/themes": {}
                    }, { discriminatorId: "context-menu", force: true });
                }
            }
            Themes.ThemesCommand = ThemesCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class BatchUpdateColorsCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.theme != null;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Themes.UpdateColorsDialog.open({
                        theme: this.theme
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/batch-update-colors",
                        tooltip: "Batch update the colors of the selected theme.",
                        label: "Batch Update Colors",
                        icon: "paint_bucket.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Themes.BatchUpdateColorsCommand = BatchUpdateColorsCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class CreateThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Theme",
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.Themes.ThemeUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Themes.ThemeArbiter"
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/create",
                        tooltip: "Create a new theme.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Themes.CreateThemeCommand = CreateThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class DeleteThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.theme != null && this.theme.isBuiltIn != true && this.theme.isDefault != true;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Theme",
                        message: `Delete the "${this.theme.name}" theme?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/delete",
                        tooltip: "Delete the selected theme.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeDelete() {
                    let service = new PDJS.Services.Themes.ThemeService();
                    service.deleteTheme({
                        themeId: this.themeId,
                        success: (e) => {
                            this.list.refresh();
                            PDJS.Shared.Themes.EventsHub.themeListChangedPublish();
                        }
                    });
                }
            }
            Themes.DeleteThemeCommand = DeleteThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class DuplicateThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.theme != null;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Themes.DuplicateThemeDialog.open({
                        theme: this.theme,
                        select: {
                            ok: (sender, e) => {
                                this.list.refresh(e.id);
                                PDJS.Shared.Themes.EventsHub.themeListChangedPublish();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/duplicate",
                        tooltip: "Create a new theme using the selected theme as a template.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Themes.DuplicateThemeCommand = DuplicateThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class EnableThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    var _a, _b;
                    super.onStateChanged(e);
                    this.enabled = this.theme != null && !((_a = this.theme) === null || _a === void 0 ? void 0 : _a.isDefault);
                    this.updateLabelAndTooltip((_b = this.theme) === null || _b === void 0 ? void 0 : _b.isEnabled);
                }
                onExecute(e) {
                    var _a;
                    super.onExecute(e);
                    let service = new PDJS.Services.Themes.ThemeService();
                    let enabled = (_a = this.theme) === null || _a === void 0 ? void 0 : _a.isEnabled;
                    service.enableTheme({
                        themeId: this.themeId,
                        enabled: !enabled,
                        success: (e) => {
                            this.theme.isEnabled = !enabled;
                            this.list.refresh();
                            PDJS.Shared.Themes.EventsHub.themeListChangedPublish();
                            this.setCommandState();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/enable",
                        tooltip: "",
                        label: "",
                        icon: "contrast.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                updateLabelAndTooltip(enabled) {
                    if (enabled) {
                        this.label = "Disable";
                        this.tooltip = "Disable the selected theme.";
                        return;
                    }
                    this.label = "Enable";
                    this.tooltip = "Enable the selected theme.";
                }
            }
            Themes.EnableThemeCommand = EnableThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ExportThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Downloader.download({
                        url: "~/Manage/Theme/ExportTheme",
                        params: {
                            themeId: this.themeId
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/export",
                        tooltip: "Export the selected theme.",
                        label: "Export",
                        icon: "nav_down.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Themes.ExportThemeCommand = ExportThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ManageCustomColorsCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    Themes.Custom.ColorsDialog.open({
                        select: (sender, e) => {
                            sender.close();
                            PDJS.Shared.Themes.Theme.manage.refreshTheme();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/manage-custom-colors",
                        tooltip: "Manage Custom Colors",
                        label: "Manage Custom Colors",
                        enabled: true,
                        display: "label"
                    };
                }
            }
            Themes.ManageCustomColorsCommand = ManageCustomColorsCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ResetThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.theme != null;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Reset | Theme",
                        message: `Reset the "${this.theme.name}" theme to its orginal colors?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/reset",
                        tooltip: "Reset the selected theme.",
                        label: "Reset",
                        icon: "rotate_left.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeDelete() {
                    let service = new PDJS.Services.Themes.ThemeService();
                    service.resetTheme({
                        themeId: this.themeId,
                        success: (e) => {
                            this.list.refresh();
                            this.editor.load(this.theme);
                        }
                    });
                }
            }
            Themes.ResetThemeCommand = ResetThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class UpdateThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.editor.commit({
                        success: (e) => {
                            PDJS.Shared.Themes.EventsHub.themeListChangedPublish();
                            if (this.themeId === PDJS.Profiles.Profile.current.themes.manage) {
                                PDJS.Shared.Themes.Theme.manage.refreshTheme();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/update",
                        tooltip: "Save changes made to the selected theme.",
                        label: "Save",
                        icon: "floppy_disk.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Themes.UpdateThemeCommand = UpdateThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/themes");
                }
                registerCommands(e) {
                    e.commands.add(new Themes.BatchUpdateColorsCommand());
                    e.commands.add(new Themes.CreateThemeCommand());
                    e.commands.add(new Themes.DeleteThemeCommand());
                    e.commands.add(new Themes.DuplicateThemeCommand());
                    e.commands.add(new Themes.EnableThemeCommand());
                    e.commands.add(new Themes.ExportThemeCommand());
                    e.commands.add(new Themes.ManageCustomColorsCommand());
                    e.commands.add(new Themes.ResetThemeCommand());
                    e.commands.add(new Themes.UpdateThemeCommand());
                }
            }
            Themes.ThemesCommands = ThemesCommands;
            Jade.CommandGroups.add(ThemesCommands);
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get theme() {
                    return this.m_theme;
                }
                set theme(value) {
                    this.m_theme = value;
                }
                get onCommitCallback() {
                    return this.state.get("onCommit", () => { });
                }
                get hasChanges() {
                    return this.m_editor.rootModel.context.featureSet.hasChanges();
                }
                get styleNode() {
                    return this.node.children("style");
                }
                template() {
                    return `<div class="-pdjs-manage-module-themes-editor">
                        <style></style>
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Settings</div>
                        <div data-controls></div>
                    </div>`;
                }
                load(theme) {
                    this.theme = theme;
                    let service = new PDJS.Services.Themes.ThemeService();
                    service.getThemeDesignerCss({
                        themeId: theme.id,
                        success: (e) => {
                            this.styleNode.empty();
                            this.styleNode.html(e.data.css);
                        }
                    });
                    this.theme_load();
                }
                commit(args = {}) {
                    let successFunction = (args.success || (() => { }));
                    let wrappedFunction = (e) => {
                        successFunction(e);
                        this.onCommitCallback();
                    };
                    args.success = wrappedFunction;
                    this.m_editor.commit(args);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Features.FeatureEditor({
                        onCommitSuccess: (e) => {
                            PDJS.Shared
                                .MessageStack
                                .instance
                                .success("Changes Saved");
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                theme_load() {
                    this.m_editor.load({
                        arbiter: {
                            id: this.theme.id,
                            targetType: "ProspectDirector.Web.Shared.Modules.Themes.ThemeUIO",
                            type: "ProspectDirector.Web.Manage.Modules.Themes.ThemeArbiter"
                        },
                        initialized: false
                    });
                }
            }
            Themes.ThemesEditor = ThemesEditor;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/update"
                    }));
                }
            }
            Themes.ThemesEditorToolbar = ThemesEditorToolbar;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesList extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_silentSelect = false;
                    this.subscriptions.add(Themes.EventsHub.loadThemesSubscribe(() => {
                        this.refresh();
                    }));
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selection() {
                    var _a, _b;
                    return _.first((_b = (_a = this.m_list) === null || _a === void 0 ? void 0 : _a.selected) === null || _b === void 0 ? void 0 : _b.toArray().map(item => {
                        return item.data.toJSON();
                    }));
                }
                template() {
                    return `<div class="-pdjs-manage-themes-list ${Manage.CssClass.NavigationPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Themes</div>
                        <div role="list" class="${Manage.CssClass.ModuleSectionBody}" data-controls></div>
                    </div>`;
                }
                refresh(selection = null) {
                    this.populateList(selection);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                    this.contextMenu_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.populateList();
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.single,
                        binding: {
                            value: "id",
                            label: "name"
                        },
                        data: [],
                        height: "100%",
                        iconSet: "pd",
                        noItemsMessage: "No themes have been defined.",
                        createItem: (e) => {
                            return new Themes.ListViewItem(e);
                        },
                        change: (items) => {
                            if (this.m_list != null && this.selection && this.m_silentSelect !== true) {
                                this.changeCallback(this.selection);
                            }
                        }
                    });
                    this.controls.add(this.m_list);
                }
                contextMenu_init() {
                    this.m_contentMenu = new PDJS.Shared.UI.Controls.ListViewContextMenu({
                        filter: ".-pdjs-manage-themes-list-item",
                        list: this.m_list,
                        segments: [{
                                type: "PDJS.Manage.Themes.ThemesListContextMenu"
                            }],
                        close: (e) => {
                            this.updateContextMenuCommandState(this.selection);
                        },
                        show: (e) => {
                            this.updateContextMenuCommandState(e.toJSON());
                        }
                    });
                    this.controls.add(this.m_contentMenu);
                }
                populateList(selection = null) {
                    var _a;
                    let service = new PDJS.Services.Themes.ThemeService();
                    let currentThemeId = (_a = this.selection) === null || _a === void 0 ? void 0 : _a.id;
                    service.list({
                        success: (e) => {
                            this.m_list.removeAll(true);
                            e.data.forEach(item => {
                                this.m_list.addItem(item);
                            });
                            if (selection != null) {
                                this.m_list.select([selection]);
                                return;
                            }
                            if (currentThemeId != null) {
                                this.m_silentSelect = true;
                                this.m_list.select([currentThemeId]);
                                this.m_silentSelect = false;
                                if (this.selection != null) {
                                    return;
                                }
                            }
                            let firstItem = this.m_list.items.first();
                            if (firstItem != null) {
                                this.m_list.select([firstItem.data.value]);
                            }
                            setTimeout(() => {
                                this.updateContextMenuCommandState();
                            }, 100);
                        }
                    });
                }
                updateContextMenuCommandState(theme = null) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/themes": {
                            $list: this
                        }
                    }, {
                        force: true
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/themes": {
                            $theme: theme
                        }
                    }, {
                        discriminatorId: "context-menu",
                        force: true
                    });
                }
            }
            Themes.ThemesList = ThemesList;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesListContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = Jade.CommandPath
                        .buildGroup("pdjs/manage/themes", "context-menu");
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/duplicate`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/enable`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/reset`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/batch-update-colors`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:theme/export`
                    }));
                }
            }
            Themes.ThemesListContextMenu = ThemesListContextMenu;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesListToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/create"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/delete"
                    }));
                }
            }
            Themes.ThemesListToolbar = ThemesListToolbar;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get editorNode() {
                    return this.node.find("div[role=editor]");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                get toolbarNode() {
                    return this.node.find("div[role=toolbar]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="-pdjs-manage-themes ${Manage.CssClass.Module}">
                        <div role="toolbar"></div>
                        <div>
                            <div role="splitter">
                                <div data-id="pane-1"></div>
                                <div data-id="pane-2"></div>
                                <div data-id="pane-3"></div>
                            </div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.editor_init();
                    this.actions_init();
                    this.toolbar_init();
                    this.list_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Themes.ThemesToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                list_init() {
                    this.m_list = new Themes.ThemesList({
                        insertAt: "div[data-id=pane-1]",
                        change: (item) => {
                            this.m_editor.load(this.m_list.selection);
                            this.m_actions.load(this.m_list.selection);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_list);
                }
                editor_init() {
                    this.m_editor = new Themes.ThemesEditor({
                        insertAt: "div[data-id=pane-2]",
                        onCommit: (e) => {
                            this.m_list.refresh();
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                actions_init() {
                    this.m_actions = new Themes.ThemesActions({
                        insertAt: "div[data-id=pane-3]"
                    });
                    this.controls.add(this.m_actions);
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, size: "300px" },
                            { resizable: true },
                            { resizable: true, size: "300px" }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    if (this.m_list == null || this.m_editor == null) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/themes": {
                            $editor: this.m_editor,
                            $list: this.m_list
                        }
                    }, { force: true });
                }
            }
            Themes.ThemesModule = ThemesModule;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ThemesToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/duplicate"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/delete"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/update"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/enable"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/reset"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/batch-update-colors"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/themes:theme/export"
                    }));
                }
            }
            Themes.ThemesToolbar = ThemesToolbar;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ImportThemeCommand extends Themes.ThemesCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "theme/import",
                        tooltip: "Import",
                        label: "Import",
                        enabled: true,
                        display: "label"
                    };
                }
            }
            Themes.ImportThemeCommand = ImportThemeCommand;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ListViewItem extends PDJS.Shared.UI.Controls.ListViewItem {
                get isDefault() {
                    return this.data.get("isDefault", false);
                }
                get isEnabled() {
                    return this.data.get("isEnabled", true);
                }
                get labelNode() {
                    return this.node.find("div[role=label]");
                }
                get swatches() {
                    return this.data.get("swatches", []);
                }
                template() {
                    return `<div class="-pdjs-manage-themes-list-item">
                        <div>
                            <div role="swatches">
                                ${this.getSwatch()}
                            </div>
                        </div>
                        <div role="label">${this.data.label}</div>
                        <div role="marker">
                            <i class="icofont-favourite" style="display:${this.isDefault ? "inline" : "none"}"></i>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.labelNode.css({
                        textDecoration: this.isEnabled ? "none" : "line-through"
                    });
                }
                getSwatch() {
                    return `<div role="swatch" style="background: linear-gradient(45deg, ${this.swatches[0]} 50%, ${this.swatches[1]} 50%);"></div>`;
                }
            }
            Themes.ListViewItem = ListViewItem;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class DuplicateThemeDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get theme() {
                    return this.state.get("theme");
                }
                get headingNode() {
                    return this.node.children("div[role=heading]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-manage-themes-duplicate-theme-dialog">
                        <div role="heading">Create a new theme using the "${this.theme.name}" theme as a template.</div>
                        <div data-controls></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.commit();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.fields_init();
                }
                onInputReturnKeystroke() {
                    super.onInputReturnKeystroke();
                    this.commit();
                }
                getDefaultOptions() {
                    return {
                        title: "New | Theme",
                        width: 350,
                        resizable: false
                    };
                }
                fields_init() {
                    this.nameField_init();
                }
                nameField_init() {
                    this.m_nameField = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Name",
                        validateOnBlur: false,
                        errorCodeMaps: [PDJS.Services.Themes.IThemeServiceError.InvalidName]
                    });
                    this.controls.add(this.m_nameField);
                }
                commit() {
                    let service = new PDJS.Services.Themes.ThemeService();
                    service.copyTheme({
                        themeId: this.theme.id,
                        themeName: this.m_nameField.value,
                        success: (e) => {
                            this.close({
                                name: "ok",
                                data: {
                                    id: e.data.id
                                }
                            });
                        },
                        error: (e) => {
                            if (_.isArray(e.xhr.responseJSON)) {
                                this.validate(e.xhr.responseJSON);
                                e.errorHandled = true;
                            }
                        }
                    });
                }
                validate(e) {
                    PDJS.Shared.UI.Controls.Fields.ServiceValidation.mapServiceErrors(this, e);
                    this.controls.getByType(PDJS.Shared.UI.Controls.Fields.Field).each(field => {
                        field.validate();
                    });
                }
                static open(options) {
                    return new DuplicateThemeDialog(options);
                }
            }
            Themes.DuplicateThemeDialog = DuplicateThemeDialog;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class ImportDialog extends Jade.UI.Dialogs.Dialog {
                get okButtonNode() {
                    return this.node.find("button[data-id=button-ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=button-cancel]");
                }
                get themeName() {
                    return this.state.get("themeName");
                }
                set themeName(value) {
                    this.state.set("themeName", value);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                template() {
                    return super.template(`<div class="-pdjs-manage-themes-import-dialog">
                        <div role="upload" data-controls></div>
                        <div role="buttons">
                            <button 
                                data-id="button-ok"  
                                class="-pdjs-dialog-button"
                                style="margin-right:5px;">
                                OK
                            </button>
                            <button ,
                                data-id="button-cancel" 
                                class="-pdjs-dialog-button">
                                Cancel
                            </button>
                        </div>
                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.executeServiceCall();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                    this.enableOkButton(false);
                }
                getDefaultOptions() {
                    return {
                        title: "Import | Theme",
                        width: 350
                    };
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        watermark: "Select theme file...",
                        mimeTypes: [{ title: "Theme File", extensions: "theme" }],
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.themeName = Jade.Path.getFileNameWithoutExtension(e.name);
                            this.enableOkButton(true);
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                closeAndReturn() {
                    this.close({
                        name: "ok"
                    });
                }
                enableOkButton(enabled) {
                    this.okButtonNode.prop("disabled", !enabled);
                }
                executeServiceCall() {
                    let service = new PDJS.Services.Themes.ThemeService();
                    this.closeAndReturn();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Task | Import Theme",
                        showDetail: true,
                        taskStart: (e) => {
                            service.importTheme({
                                themeName: this.themeName,
                                uploadId: this.uploadId,
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskComplete: (e) => {
                            Themes.EventsHub.loadThemesPublish();
                        }
                    });
                }
                static open() {
                    return new ImportDialog({});
                }
            }
            Themes.ImportDialog = ImportDialog;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            class UpdateColorsDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=button-ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=button-cancel]");
                }
                get editor() {
                    return this.m_editor;
                }
                get themeId() {
                    var _a;
                    return (_a = this.theme) === null || _a === void 0 ? void 0 : _a.id;
                }
                get theme() {
                    return this.state.get("theme");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-themes-update-colors-dialog">
                    <div role="header">
                        Input the formatted text to update the "${this.theme.name}" theme's colors in batch.
                    </div>
                    <div role="editor" data-controls></div>
                    <div role="buttons">
                        <button 
                            data-id="button-ok"  
                            class="-pdjs-dialog-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-pdjs-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.executeServiceCall();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.editor_init();
                    this.enableOkButton(false);
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.m_editor.load("");
                }
                getDefaultOptions() {
                    return {
                        title: "Theme | Batch Update Colors",
                        height: 500,
                        width: 600
                    };
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Coding.CodeEditor({
                        change: () => {
                            this.enableOkButton(true);
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                closeAndReturn() {
                    this.close({
                        name: "ok",
                        data: {
                            value: this.editor.content.getValue()
                        }
                    });
                }
                enableOkButton(enabled) {
                    this.okButtonNode.prop("disabled", !enabled);
                }
                executeServiceCall() {
                    let service = new PDJS.Services.Themes.ThemeService();
                    this.closeAndReturn();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Task | Batch Update Colors",
                        showDetail: true,
                        taskStart: (e) => {
                            service.updateColors({
                                themeId: this.themeId,
                                content: this.editor.content.getValue(),
                                success: (e2) => {
                                    e.startPolling(e2.data);
                                },
                                error: (e2) => {
                                    e.abort(e2);
                                }
                            });
                        },
                        taskComplete: (e) => {
                        }
                    });
                }
                static open(options) {
                    return new UpdateColorsDialog(options);
                }
            }
            Themes.UpdateColorsDialog = UpdateColorsDialog;
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorEditorDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get colorId() {
                        return this.state.get("colorId");
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-id=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=cancel]");
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-manage-themes-custom-color-editor-dialog">
                        <div data-controls></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.commit();
                        });
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                        this.fields_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (this.colorId != null) {
                            this.loadData();
                        }
                    }
                    onInputReturnKeystroke() {
                        super.onInputReturnKeystroke();
                        this.commit();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Edit | Custom Color",
                            height: 282,
                            width: 350,
                            resizable: false
                        };
                    }
                    fields_init() {
                        this.idField_init();
                        this.nameField_init();
                        this.categoryField_init();
                        this.descriptionField_init();
                    }
                    idField_init() {
                        this.m_idField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "ID",
                            required: true,
                            enabled: this.colorId == null,
                            validateOnBlur: false,
                            errorCodeMaps: [PDJS.Services.Themes.IThemeColorServiceError.InvalidId]
                        });
                        this.controls.add(this.m_idField);
                    }
                    nameField_init() {
                        this.m_nameField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Name",
                            required: true,
                            validateOnBlur: false,
                            errorCodeMaps: [PDJS.Services.Themes.IThemeColorServiceError.InvalidName]
                        });
                        this.controls.add(this.m_nameField);
                    }
                    categoryField_init() {
                        this.m_categoryField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Category",
                            required: true,
                            enabled: true,
                            validateOnBlur: false,
                            errorCodeMaps: [PDJS.Services.Themes.IThemeColorServiceError.InvalidCategory]
                        });
                        this.controls.add(this.m_categoryField);
                    }
                    descriptionField_init() {
                        this.m_descriptionField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Description",
                            height: 75,
                            multiline: true,
                            validateOnBlur: false,
                            errorCodeMaps: [PDJS.Services.Themes.IThemeColorServiceError.InvalidDescription]
                        });
                        this.controls.add(this.m_descriptionField);
                    }
                    loadData() {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        service.loadCustomColor({
                            colorId: this.colorId,
                            success: (e) => {
                                this.m_idField.value = e.data.id;
                                this.m_nameField.value = e.data.name;
                                this.m_descriptionField.value = e.data.description;
                            }
                        });
                    }
                    commit() {
                        this.colorId == null ?
                            this.addColor() :
                            this.saveColor();
                    }
                    addColor() {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        service.addCustomColor({
                            color: {
                                id: this.m_idField.value,
                                name: this.m_nameField.value,
                                description: this.m_descriptionField.value
                            },
                            success: (e) => {
                                this.close({
                                    name: "ok",
                                    data: e.data.color
                                });
                            },
                            error: (e) => {
                                if (_.isArray(e.xhr.responseJSON)) {
                                    this.validate(e.xhr.responseJSON);
                                    e.errorHandled = true;
                                }
                            }
                        });
                    }
                    saveColor() {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        service.saveCustomColor({
                            color: {
                                id: this.m_idField.value,
                                name: this.m_nameField.value,
                                description: this.m_descriptionField.value
                            },
                            success: (e) => {
                                this.close({
                                    name: "ok"
                                });
                            },
                            error: (e) => {
                                if (_.isArray(e.xhr.responseJSON)) {
                                    this.validate(e.xhr.responseJSON);
                                    e.errorHandled = true;
                                }
                            }
                        });
                    }
                    validate(e) {
                        PDJS.Shared.UI.Controls.Fields.ServiceValidation.mapServiceErrors(this, e);
                        this.controls.getByType(PDJS.Shared.UI.Controls.Fields.Field).each(field => {
                            field.validate();
                        });
                    }
                    static open(options) {
                        return new ColorEditorDialog(options);
                    }
                }
                Custom.ColorEditorDialog = ColorEditorDialog;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsCommand extends Jade.Command {
                    constructor() {
                        super({});
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                    }
                    onExecute(e) {
                        super.onExecute(e);
                    }
                }
                Custom.ColorsCommand = ColorsCommand;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class CreateColorCommand extends Custom.ColorsCommand {
                    onStateChanged(e) {
                        super.onStateChanged(e);
                    }
                    onExecute(e) {
                        super.onExecute(e);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "Custom Color | New",
                            width: 400,
                            height: 430,
                            args: {
                                targetType: "ProspectDirector.Web.Shared.Modules.Themes.CustomColorUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Themes.CustomColorArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    PDJS.Shared.Themes.Theme.refreshColors();
                                    PDJS.Shared.Themes.Theme.manage.refreshTheme();
                                    sender.close();
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "color/create",
                            tooltip: "New",
                            label: "New",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                Custom.CreateColorCommand = CreateColorCommand;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class DeleteColorCommand extends Custom.ColorsCommand {
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.grid.selections.length > 0;
                    }
                    onExecute(e) {
                        super.onExecute(e);
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete | Custom Color",
                            message: `Delete the selected custom color(s)?`,
                            select: (e) => {
                                e.close();
                                if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                    this.executeDelete();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "color/delete",
                            tooltip: "Delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    executeDelete() {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        let customColorName = _.first(this.grid.selections).name;
                        service.deleteCustomColor({
                            colorIds: _.map(this.grid.selections, "id"),
                            success: (e) => {
                                this.grid.refresh({
                                    clear: true
                                });
                                PDJS.Shared.MessageStack.instance.success(`Custom color "${customColorName}" deleted.`);
                            }
                        });
                    }
                }
                Custom.DeleteColorCommand = DeleteColorCommand;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class UpdateColorCommand extends Custom.ColorsCommand {
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.enabled = this.grid.selections.length == 1;
                    }
                    onExecute(e) {
                        super.onExecute(e);
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: "Custom Color | New",
                            width: 400,
                            height: 430,
                            args: {
                                targetId: _.first(this.grid.selections).id,
                                targetType: "ProspectDirector.Web.Shared.Modules.Themes.CustomColorUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Themes.CustomColorArbiter"
                            },
                            select: {
                                ok: (sender, e) => {
                                    PDJS.Shared.Themes.Theme.refreshColors();
                                    PDJS.Shared.Themes.Theme.manage.refreshTheme();
                                    sender.close();
                                    this.grid.refresh();
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "color/update",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                }
                Custom.UpdateColorCommand = UpdateColorCommand;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/themes/custom");
                    }
                    registerCommands(e) {
                        e.commands.add(new Custom.CreateColorCommand());
                        e.commands.add(new Custom.DeleteColorCommand());
                        e.commands.add(new Custom.UpdateColorCommand());
                    }
                }
                Custom.ColorsCommands = ColorsCommands;
                Jade.CommandGroups.add(ColorsCommands);
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=cancel]");
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-manage-themes-custom-colors-dialog">
                        <div role="head">
                                Custom colors allow the addition of colors for use across all themes 
                                in the system, when standard theme colors are not sufficient.
                        </div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="cancel">Close</button>
                        </div>
                    </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                        this.grid_init();
                        this.menu_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Manage | Custom Colors",
                            height: 400,
                            width: 600
                        };
                    }
                    grid_init() {
                        this.m_grid = new Custom.ColorsGrid({
                            insertAt: "div[role=grid]"
                        });
                        this.controls.add(this.m_grid);
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Custom.ColorsToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    static open(options = {}) {
                        return new ColorsDialog(options);
                    }
                }
                Custom.ColorsDialog = ColorsDialog;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsGrid extends Jade.UI.Control {
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    refresh(e = {}) {
                        this.loadData(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-themes-custom-colors-grid"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.loadData();
                    }
                    contextMenu_init(grid) {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: grid,
                            segments: [{
                                    type: "PDJS.Manage.Themes.Custom.ColorsGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                    grid_init() {
                        let icon = Jade.IconSet.get("pdv2")
                            .resolve("photographic_filters.png", Jade.IconSetSizeSpecificDirectory.x16);
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            pk: "id",
                            container: this.node,
                            showToolbar: false,
                            height: "100%",
                            footer: {
                                visible: false
                            },
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true,
                                sort: [
                                    { field: "name", dir: "asc" }
                                ]
                            },
                            messaging: {
                                noRecordsMessage: "No custom colors exist."
                            },
                            sortable: {
                                allowUnsort: true
                            },
                            selectionMode: "multiple",
                            selectOnRightClick: true,
                            defaultSelectionEnabled: true,
                            resizable: true,
                            columns: [
                                new PD.Web.UI.Controls.GridColumn({
                                    title: "&nbsp;",
                                    width: 30,
                                    template: (e) => {
                                        var _a;
                                        return `<div class="-pdjs-manage-themes-custom-colors-grid-swatch">
                                        <div style="background-color:${(_a = e.lightValue) !== null && _a !== void 0 ? _a : "transparent"};"></div>
                                    </div>`;
                                    }
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "id",
                                    title: "ID",
                                    width: "200px"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "name",
                                    title: "Name",
                                    width: "250px"
                                }),
                                new PD.Web.UI.Controls.GridColumn({
                                    field: "description",
                                    title: "Description",
                                    width: "400px"
                                }),
                                new PD.Web.UI.Controls.GridFillColumn()
                            ],
                            change: (e) => {
                                if (this.m_grid != null) {
                                    this.setCommandState();
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/themes/custom:color/update");
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init(e);
                            }
                        });
                    }
                    loadData(options = {}) {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        service.listCustomColors({
                            success: (e) => {
                                this.m_grid.get_dataSource().data([]);
                                this.m_grid.get_dataSource().data(e.data);
                                this.m_grid.refresh(options);
                                this.setCommandState();
                            }
                        });
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/themes/custom": {
                                $grid: this
                            }
                        }, { force: true });
                    }
                }
                Custom.ColorsGrid = ColorsGrid;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/themes/custom";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:color/update`
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:color/delete`
                        }));
                    }
                }
                Custom.ColorsGridContextMenu = ColorsGridContextMenu;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ColorsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/themes/custom";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:color/create`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:color/update`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:color/delete`
                        }));
                    }
                }
                Custom.ColorsToolbar = ColorsToolbar;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Themes;
        (function (Themes) {
            var Custom;
            (function (Custom) {
                class ImportDialog extends Jade.UI.Dialogs.Dialog {
                    get okButtonNode() {
                        return this.node.find("button[data-id=button-ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-id=button-cancel]");
                    }
                    get uploadId() {
                        return this.state.get("uploadId");
                    }
                    set uploadId(value) {
                        this.state.set("uploadId", value);
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-manage-themes-custom-import-dialog">
                    <div role="upload" data-controls></div>
                    <div role="buttons">
                        <button 
                            data-id="button-ok"  
                            class="-pdjs-dialog-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-pdjs-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.executeServiceCall();
                        });
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.close();
                        });
                        this.upload_init();
                        this.enableOkButton(false);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Import | Custom Colors",
                            width: 350,
                            resizable: false
                        };
                    }
                    upload_init() {
                        this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                            watermark: "Select export file...",
                            mimeTypes: [{ title: "Custom Color Export", extensions: "cxp" }],
                            onUploadComplete: (e) => {
                                this.uploadId = `${e.id}${e.extension}`;
                                this.enableOkButton(true);
                            }
                        });
                        this.controls.add(this.m_upload);
                    }
                    closeAndReturn() {
                        this.close({
                            name: "ok"
                        });
                    }
                    enableOkButton(enabled) {
                        this.okButtonNode.prop("disabled", !enabled);
                    }
                    executeServiceCall() {
                        let service = new PDJS.Services.Themes.ThemeColorService();
                        service.importColors({
                            uploadId: this.uploadId,
                            success: (e) => {
                                this.closeAndReturn();
                                PDJS.Shared.Themes.Theme.manage.refreshTheme();
                            }
                        });
                    }
                    static open() {
                        return new ImportDialog({});
                    }
                }
                Custom.ImportDialog = ImportDialog;
            })(Custom = Themes.Custom || (Themes.Custom = {}));
        })(Themes = Manage.Themes || (Manage.Themes = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDeleteDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(options) {
                    return new ViewDeleteDialog({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Linked View Handling",
                        header: `<span style="color:var(--visiv-required-text-color)">WARNING: This operation cannot be undone.</span><br/>
                         Deleting this view will also delete its linked views.
                         How do you want to handle linked views during the deletion process?`,
                        items: [
                            {
                                title: "Delete the view and all of its linked views.",
                                message: `This will permanently delete this view and all views users have created using this view from the system.
                                  Suggested if the view is considered completely invalid.`,
                                value: "delete",
                                selected: true
                            },
                            {
                                title: "Delete the view and unlink its linked views.",
                                message: `This will allow users that may have created new views from this view to retain those views.
                                  Suggested if the view is no longer required, but the view is still considered valid.`,
                                value: "unlink"
                            }
                        ],
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                if (e.selection) {
                                    options.select(e.selection.value);
                                }
                            }
                        }
                    });
                }
            }
            Views.ViewDeleteDialog = ViewDeleteDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherActions extends PDJS.Shared.UI.Controls.PanelMenu {
                get viewId() {
                    return this.state.get("viewId");
                }
                set viewId(value) {
                    this.state.set("viewId", value);
                }
                get viewName() {
                    return this.state.get("viewName");
                }
                set viewName(value) {
                    this.state.set("viewName", value);
                }
                load(viewId) {
                    this.viewId = viewId;
                }
                template() {
                    return `<div class="-pdjs-manage-views-publisher-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addViewsItems();
                    this.addRelatedItems();
                }
                addViewsItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Views"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: "Reset All Views",
                        click: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/views/publisher:views/reset-all");
                        }
                    }));
                }
                addRelatedItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Related"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/builtin",
                        label: "Built-In Views"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "~/Hub/ViewBrowser/Global",
                        target: "_blank",
                        label: "Global Views"
                    }));
                }
            }
            Views.PublisherActions = PublisherActions;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get selections() {
                    return this.grid.selections;
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/publisher": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Views.PublisherCommand = PublisherCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class CreateViewCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | View",
                        height: 550,
                        width: 700,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.ViewUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Views.ViewArbiter"
                        },
                        select: {
                            "ok": (sender, data) => {
                                this.grid.refresh({
                                    selections: [data.target.id],
                                    clear: true
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/create",
                        tooltip: "Create a new view.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Views.CreateViewCommand = CreateViewCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class DeleteViewCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Views.DeleteViewDialog.open({
                        select: (sender, e) => {
                            this.executeDelete(e.deleteLinkedViews);
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/delete",
                        tooltip: "Delete the selected view.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeDelete(deleteLinkedViews) {
                    let service = new PDJS.Services.Views.ViewPublisherService();
                    service.deleteView({
                        viewId: _.first(this.selections).id,
                        deleteLinked: deleteLinkedViews,
                        success: (e) => {
                            this.grid.refresh({
                                clear: true
                            });
                        }
                    });
                }
            }
            Views.DeleteViewCommand = DeleteViewCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class DuplicateViewCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let view = _.first(this.selections);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Information,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Duplicate | View",
                        message: `Make a duplicate copy of the "${view.name}" view?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                this.executeDuplicate();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/duplicate",
                        tooltip: "Duplicate the selected view.",
                        label: "Duplicate",
                        icon: "copy.16px.font",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeDuplicate() {
                    let service = new PDJS.Services.Views.ViewPublisherService();
                    let view = _.first(this.selections);
                    service.duplicateView({
                        viewId: view.id,
                        success: (e) => {
                            this.grid.refresh({
                                selections: [e.data.viewId],
                                clear: true
                            });
                        }
                    });
                }
            }
            Views.DuplicateViewCommand = DuplicateViewCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ResetViewCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Views.ResetViewDialog.open({
                        viewIds: this.selections.map(item => item.id),
                        select: {
                            ok: (sender, e) => {
                                this.executeReset(e.userIds);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/reset",
                        tooltip: "Reset the selected views.",
                        label: "Reset",
                        icon: "undo.16px.font",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                executeReset(userIds) {
                    let service = new PDJS.Services.Views.ViewPublisherService();
                    service.reset({
                        viewIds: this.selections.map(item => item.id),
                        userIds: userIds,
                        success: (e) => {
                            this.grid.refresh();
                            userIds.length == 0 ?
                                PDJS.Shared.MessageStack.instance.success("Selected views have been reset.") :
                                PDJS.Shared.MessageStack.instance.success("Selected views have been reset for the specified users.");
                        }
                    });
                }
            }
            Views.ResetViewCommand = ResetViewCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ResetAllViewsCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length > 0;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Question,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        message: "Reset all published views in the system to their current view settings?",
                        select: (e) => {
                            if (e.name == "yes") {
                                this.resetAllViews();
                            }
                            e.close();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "views/reset-all",
                        tooltip: "Reset All",
                        label: "Reset All",
                        icon: "undo.16px.font",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                resetAllViews() {
                    let service = new PDJS.Services.Views.ViewPublisherService();
                    service.reset({
                        viewIds: [],
                        userIds: [],
                        success: (e) => {
                            PDJS.Shared.MessageStack.instance.success("All views have been reset.");
                        }
                    });
                }
            }
            Views.ResetAllViewsCommand = ResetAllViewsCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class UpdateViewCommand extends Views.PublisherCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let view = _.first(this.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${view.name}`,
                        height: 550,
                        width: 700,
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.ViewUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Views.ViewArbiter",
                            targetId: view.id
                        },
                        select: {
                            "ok": (sender, data) => {
                                this.grid.refresh({
                                    reselect: true
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/update",
                        tooltip: "Edit the selected view.",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Views.UpdateViewCommand = UpdateViewCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/manage/views/publisher");
                }
                registerCommands(e) {
                    e.commands.add(new Views.CreateViewCommand());
                    e.commands.add(new Views.DeleteViewCommand());
                    e.commands.add(new Views.DuplicateViewCommand());
                    e.commands.add(new Views.ResetAllViewsCommand());
                    e.commands.add(new Views.ResetViewCommand());
                    e.commands.add(new Views.UpdateViewCommand());
                }
            }
            Views.PublisherCommands = PublisherCommands;
            Jade.CommandGroups.add(PublisherCommands);
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-views-publisher-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Views</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.grid_init();
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=menu]",
                        segments: [new Views.PublisherToolbar()]
                    });
                    this.controls.add(this.m_menu);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        messaging: {
                            noRecordsMessage: "No views exist."
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name,
                                    isPublic: e.IsPublic,
                                    isShortcut: e.isShortcut,
                                    linkedCount: e.linkedCount
                                };
                            }
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("pdjs/manage/views/publisher:view/update");
                        },
                        change: (e) => {
                            this.changeCallback(e.selection);
                        },
                        contextMenu: (e) => {
                            this.contextMenu_init();
                        }
                    });
                }
                contextMenu_init() {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: this.m_grid,
                        segments: [
                            { type: "PDJS.Manage.Views.PublisherGridContextMenu" }
                        ]
                    });
                    this.controls.add(contextMenu);
                }
            }
            Views.PublisherGrid = PublisherGrid;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherGridContextMenu extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/views/publisher";
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:view/create`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:view/update`
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:view/delete`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:view/duplicate`
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: `${prefix}:view/reset`
                    }));
                }
            }
            Views.PublisherGridContextMenu = PublisherGridContextMenu;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherModule extends Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-publisher">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.actions_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Views.PublisherGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.m_actions.load(item === null || item === void 0 ? void 0 : item.id);
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                actions_init() {
                    this.m_actions = new Views.PublisherActions({
                        insertAt: "div[data-id=pane-2]"
                    });
                    this.controls.add(this.m_actions);
                }
                module_init() {
                    let service = new PDJS.Services.Views.ViewPublisherService();
                    service.index({
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false },
                            { resizable: true, size: "300px", scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/publisher": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Views.PublisherModule = PublisherModule;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class PublisherToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = "pdjs/manage/views/publisher";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/create`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/update`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/delete`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/duplicate`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/reset`
                    }));
                }
            }
            Views.PublisherToolbar = PublisherToolbar;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class DeleteViewDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(options) {
                    return new DeleteViewDialog({
                        title: "Delete | View",
                        height: 350,
                        header: `The view you are attempting to delete may have views created by an end user that use this view as its source.<br/><br/>
                         How do you want to handle any linked views found during the deletion process.`,
                        items: [
                            {
                                title: "Delete the view and all of its linked views.",
                                message: "This will permanently delete this view and all views users have created using this view from the system. Suggested if the view is considered completely invalid.",
                                value: 1,
                                selected: true
                            },
                            {
                                title: "Delete the view and unlink its linked views.",
                                message: "This will allow users that may have created new views from this view to retain those views. Suggested if the view is no longer required, but the view is still considered valid.",
                                value: 0
                            }
                        ],
                        select: (sender, e) => {
                            sender.close();
                            if (sender.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                if (e.selection != null && options.select instanceof Function) {
                                    e.deleteLinkedViews = e.selection.value === 1;
                                    options.select(sender, e);
                                }
                            }
                        }
                    });
                }
            }
            Views.DeleteViewDialog = DeleteViewDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ResetViewDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get radioAllChecked() {
                    return this.radioAllNode.is(":checked");
                }
                get radioAllNode() {
                    return this.node.find("input[type=radio][value=all]");
                }
                get radioUsersChecked() {
                    return this.radioUsersNode.is(":checked");
                }
                get radioUsersNode() {
                    return this.node.find("input[type=radio][value=users]");
                }
                get selectedUsers() {
                    return this.m_batch.items.filter(item => item.selected).map(item => item.id);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return `<div class="-pdjs-manage-reset-views-dialog">
                        <div role="content">
                            <label>
                                <div>
                                    <input type="radio" name="type" value="all" />
                                </div>
                                <div>
                                    Reset the selected views for all users.
                                </div>
                            </label>
                            <label>
                                <div>
                                    <input type="radio" name="type" value="users" />
                                </div>
                                <div>
                                    Reset the selected views for only the following users.
                                </div>
                            </label>
                            <div>
                                <div></div>
                                <div role="users"></div>
                            </div>
                        </div>
                        <div role="buttons">
                            <button class="-pdjs-dialog-button" data-id="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                        </div>
                    </div>`;
                }
                static open(options) {
                    return new ResetViewDialog(options);
                }
                getDefaultOptions() {
                    return {
                        title: "Reset | Views",
                        height: 300,
                        width: 450,
                        resizable: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.dialog_init();
                    this.radioAllNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.m_batch.enabled = false;
                    });
                    this.radioUsersNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.m_batch.enabled = true;
                    });
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        let selectedUsers = this.selectedUsers;
                        if (this.radioUsersChecked && selectedUsers.length == 0) {
                            this.close();
                            return;
                        }
                        if (this.radioAllChecked) {
                            this.close({
                                name: "ok",
                                data: {
                                    userIds: []
                                }
                            });
                            return;
                        }
                        if (this.radioUsersChecked) {
                            this.close({
                                name: "ok",
                                data: {
                                    userIds: selectedUsers
                                }
                            });
                            return;
                        }
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                }
                dialog_init() {
                    let service = new PDJS.Services.Views.ViewService();
                    service.getViewStateId({
                        viewCustomId: PDJS.Services.Views.BuiltInViews.IDENTITY_SELECTION,
                        success: (e) => {
                            this.batch_init(e.data.viewStateId);
                        }
                    });
                    this.radioAllNode.prop("checked", true);
                    this.m_batch.enabled = false;
                }
                batch_init(viewStateId) {
                    this.m_batch = new PDJS.Shared.UI.Controls.BatchField({
                        insertAt: "div[role=users]",
                        tabIndex: 0,
                        noItemsMessage: "No users selected.",
                        dialogViewStateId: viewStateId,
                        dialogTitle: "Select | Users",
                        dialogHeight: 400,
                        dialogWidth: 500,
                        dialogFilters: [PDJS.Core.Views.IdentityFilter.usersOnly()],
                        showCheckboxes: false,
                        change: (items) => {
                        }
                    });
                    this.controls.add(this.m_batch);
                }
            }
            Views.ResetViewDialog = ResetViewDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchGroupsCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        entityTypeId: null,
                        documentTypeId: null,
                        $groupsGrid: null,
                        $columnsGrid: null
                    });
                }
                get columnsGrid() {
                    return this.state.get("$columnsGrid");
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId");
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get groupsGrid() {
                    return this.state.get("$groupsGrid");
                }
                get selectedColumnIds() {
                    return this.columnsGrid.selections.map(item => item.id);
                }
                get selectedGroupId() {
                    var _a;
                    return (_a = _.first(this.groupsGrid.selections)) === null || _a === void 0 ? void 0 : _a.id;
                }
            }
            Views.SearchGroupsCommand = SearchGroupsCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class AddSearchGroupCommand extends Views.SearchGroupsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/add",
                        tooltip: "Create a new search group.",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onExecute(e) {
                    if (this.entityTypeId == null && this.documentTypeId == null) {
                        return;
                    }
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Search Group",
                        height: "500px",
                        width: "650px",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupArbiter",
                            properties: {
                                entityTypeId: this.entityTypeId,
                                documentTypeId: this.documentTypeId
                            }
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.groupsGrid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
            }
            Views.AddSearchGroupCommand = AddSearchGroupCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class EditSearchGroupCommand extends Views.SearchGroupsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/edit",
                        tooltip: "Edit the selected search group.",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(e) {
                    this.enabled = this.selectedGroupId != null;
                }
                onExecute(e) {
                    let group = _.first(this.groupsGrid.selections);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Edit | ${group.name}`,
                        height: "400px",
                        width: "400px",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupArbiter",
                            targetId: this.selectedGroupId
                        },
                        select: {
                            "ok": (sender, e) => {
                                this.groupsGrid.refresh();
                            }
                        }
                    });
                }
            }
            Views.EditSearchGroupCommand = EditSearchGroupCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class RemoveSearchGroupCommand extends Views.SearchGroupsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/remove",
                        tooltip: "Delete the selected search group.",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(e) {
                    this.enabled = this.selectedGroupId != null;
                }
                onExecute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Delete | Search Group",
                        message: `Delete the selected search group?`,
                        select: (e) => {
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                PDJS.Ajax.call({
                                    type: "DELETE",
                                    url: Jade.Path.resolve("~/Manage/View/DeleteSearchGroup"),
                                    data: {
                                        id: this.selectedGroupId
                                    },
                                    success: (e) => {
                                        this.groupsGrid.refresh({ clear: true });
                                    }
                                });
                            }
                            e.close();
                        }
                    });
                }
            }
            Views.RemoveSearchGroupCommand = RemoveSearchGroupCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class AddSearchItemCommand extends Views.SearchGroupsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "searchitem/add",
                        tooltip: "Add columns to the selected search group.",
                        label: "Add",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(e) {
                    this.enabled = this.selectedGroupId != null;
                }
                onExecute(e) {
                    PDJS.Manage.Views.SearchItemsSelectionDialog.open({
                        searchGroupId: this.selectedGroupId,
                        select: {
                            ok: (sender, e) => {
                                PDJS.Ajax.call({
                                    type: "POST",
                                    url: Jade.Path.resolve("~/Manage/View/AddSearchItems"),
                                    data: {
                                        searchGroupId: this.selectedGroupId,
                                        ids: e.ids
                                    },
                                    success: (e2) => {
                                        this.columnsGrid.refresh({
                                            clear: true,
                                            selections: e.ids
                                        });
                                    }
                                });
                            }
                        }
                    });
                }
            }
            Views.AddSearchItemCommand = AddSearchItemCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class RemoveSearchItemCommand extends Views.SearchGroupsCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "searchitem/remove",
                        tooltip: "Remove the selected columns from the search group.",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(e) {
                    this.enabled = this.selectedColumnIds.length > 0;
                }
                onExecute(e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel,
                        title: "Remove | Columns",
                        message: `Remove the selected columns from the search group?`,
                        select: (e) => {
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.ok) {
                                PDJS.Ajax.call({
                                    type: "DELETE",
                                    url: Jade.Path.resolve("~/Manage/View/DeleteSearchItems"),
                                    data: {
                                        ids: this.selectedColumnIds
                                    },
                                    success: (e) => {
                                        this.columnsGrid.refresh({ clear: true });
                                    }
                                });
                            }
                            e.close();
                        }
                    });
                }
            }
            Views.RemoveSearchItemCommand = RemoveSearchItemCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchGroupCommands extends Jade.CommandGroup {
                constructor() {
                    super("views/searchgroups");
                }
                registerCommands(e) {
                    e.commands.add(new Views.AddSearchGroupCommand({}));
                    e.commands.add(new Views.EditSearchGroupCommand({}));
                    e.commands.add(new Views.RemoveSearchGroupCommand({}));
                    e.commands.add(new Views.AddSearchItemCommand({}));
                    e.commands.add(new Views.RemoveSearchItemCommand({}));
                }
            }
            Views.SearchGroupCommands = SearchGroupCommands;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
Jade.Application.onStart(function () {
    Jade.CommandGroups.add(PDJS.Manage.Views.SearchGroupCommands);
});
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchGroups extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId", null);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                get grid() {
                    return this.state.get("grid");
                }
                set grid(value) {
                    this.state.add("grid", value);
                }
                get selections() {
                    var _a;
                    return ((_a = this.grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray()) || [];
                }
                get toolbar() {
                    return this.state.get("toolbar");
                }
                set toolbar(value) {
                    this.state.add("toolbar", value);
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.toolbar_init();
                }
                refresh(e = {}) {
                    this.grid.refresh(e);
                }
                template() {
                    return `
                <div class="-pdjs-manage-views-search-groups-dialog-groups">
                    <div class="${Manage.CssClass.ModuleSectionTitle}">Groups</div>
                    <div data-id="toolbar"></div>
                    <div data-id="grid"></div>
                </div>`;
                }
                grid_init() {
                    this.grid = new window["PD"].Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-id='grid']"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.ObjectName
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.changeCallback();
                        },
                        dblclick: function (e) {
                            Jade.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("views/searchgroups:searchgroup/edit");
                        },
                        needContext: (e) => {
                            if (this.entityTypeId != null) {
                                e.filters[e.filters.length] = {
                                    id: "EntType",
                                    params: {
                                        id: this.entityTypeId
                                    }
                                };
                            }
                            if (this.documentTypeId != null) {
                                e.filters[e.filters.length] = {
                                    id: "DocType",
                                    params: {
                                        id: this.documentTypeId
                                    }
                                };
                            }
                        }
                    });
                }
                toolbar_init() {
                    this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[data-id=toolbar]",
                        segments: [new Views.SearchGroupsToolbarSegment()]
                    });
                    this.controls.add(this.toolbar);
                }
            }
            Views.SearchGroups = SearchGroups;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            let DocumentTypeCommandKey;
            (function (DocumentTypeCommandKey) {
                DocumentTypeCommandKey["name"] = "pd/document-type";
            })(DocumentTypeCommandKey || (DocumentTypeCommandKey = {}));
            class SearchGroupsDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get splitter() {
                    return this.state.get("splitter", null);
                }
                set splitter(value) {
                    this.state.set("splitter", value);
                }
                get splitterNode() {
                    return this.node.find("[data-id=splitter]");
                }
                get closeButtonNode() {
                    return this.node.find("button[data-command=close]");
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId", null);
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-views-search-groups-dialog">
                    <div>
                        <div data-id="splitter" class="-pd-minimal-splitter">
                            <div data-role="groups"></div>
                            <div data-role="items"></div>
                        </div>
                    </div>
                    <div>
                        <button data-command="close" class="-jadeui-dialog-button">Close</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Search Groups",
                        height: "600px",
                        width: "800px",
                        maximized: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.maximize();
                    this.splitter = this.splitterNode.kendoSplitter({
                        orientation: "horizontal",
                        panes: [
                            { size: "275px" },
                            {}
                        ],
                        resize: _.debounce(() => {
                            var _a;
                            if (((_a = this.splitter) === null || _a === void 0 ? void 0 : _a.element) != null) {
                                this.splitter.resize(true);
                            }
                        }, 50)
                    }).data("kendoSplitter");
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve("~/Manage/View/SearchGroups"),
                        success: (e) => {
                            this.loadControls(e);
                        }
                    });
                    this.closeButtonNode.on("click", (e) => {
                        this.close();
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter != null && this.splitter.element != null) {
                        this.splitter.destroy();
                    }
                }
                loadControls(e) {
                    this.m_groupsGrid = new Views.SearchGroups({
                        insertAt: "[data-role=groups]",
                        viewStateId: e.searchGroupsViewStateId,
                        entityTypeId: this.entityTypeId,
                        documentTypeId: this.documentTypeId,
                        change: () => {
                            var _a;
                            this.setCommandState();
                            this.m_itemsGrid.load((_a = _.first(this.m_groupsGrid.selections)) === null || _a === void 0 ? void 0 : _a.id);
                        }
                    });
                    this.controls.add(this.m_groupsGrid);
                    this.m_itemsGrid = new Views.SearchItems({
                        insertAt: "[data-role=items]",
                        viewStateId: e.searchGroupItemsViewStateId,
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_itemsGrid);
                }
                setCommandState() {
                    let setState = this.m_itemsGrid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "views/searchgroups": {
                            entityTypeId: this.entityTypeId,
                            documentTypeId: this.documentTypeId,
                            $groupsGrid: this.m_groupsGrid,
                            $columnsGrid: this.m_itemsGrid
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new SearchGroupsDialog(options);
                }
            }
            Views.SearchGroupsDialog = SearchGroupsDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchGroupsEventsHub extends PDJS.Shared.EventsHubBase {
                static moduleChangeDataPublish(args) {
                }
                static moduleChangeDataSubscribe(handler) {
                    return this.global.subscribe(Manage.Events.ModuleChangeData, handler);
                }
            }
            Views.SearchGroupsEventsHub = SearchGroupsEventsHub;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchGroupsToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "views/searchgroups:searchgroup/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "views/searchgroups:searchgroup/edit"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "views/searchgroups:searchgroup/remove"
                    }));
                }
            }
            Views.SearchGroupsToolbarSegment = SearchGroupsToolbarSegment;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchItems extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_grid = null;
                    this.m_toolbar = null;
                    this.m_selectedSearchGroupId = Jade.Guid.empty();
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get selections() {
                    var _a;
                    return ((_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray()) || [];
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                onActivate(e) {
                    this.grid_init();
                    this.toolbar_init();
                }
                load(searchGroupId) {
                    this.m_selectedSearchGroupId = searchGroupId || Jade.Guid.empty();
                    this.refresh({
                        clear: true
                    });
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `
                <div class="-pdjs-manage-views-search-groups-dialog-items">
                    <div class="${Manage.CssClass.ModuleSectionTitle}">Columns</div>
                    <div data-id="toolbar"></div>
                    <div data-id="grid"></div>
                </div>`;
                }
                grid_init() {
                    this.m_grid = new window["PD"].Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-id='grid']"),
                        selectionMode: "multiple",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: false,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.Name
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.changeCallback();
                        },
                        needContext: (e) => {
                            e.filters[e.filters.length] = {
                                id: "Group",
                                params: {
                                    id: this.m_selectedSearchGroupId
                                }
                            };
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[data-id=toolbar]",
                        segments: [new Views.SearchItemsToolbarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
            }
            Views.SearchItems = SearchItems;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchItemsToolbarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "views/searchgroups:searchitem/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "views/searchgroups:searchitem/remove"
                    }));
                }
            }
            Views.SearchItemsToolbarSegment = SearchItemsToolbarSegment;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SearchItemsSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                    this.m_grid = null;
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get gridNode() {
                    return this.node.find("div[data-role=grid]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get searchGroupId() {
                    return this.state.get("searchGroupId");
                }
                onActivate(e) {
                    super.onActivate(e);
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve("~/Manage/View/SearchItemsSelection"),
                        error: (e) => {
                            this.close();
                        },
                        success: (e) => {
                            this.init_grid(e.viewStateId);
                        }
                    });
                    this.cancelButtonNode.on("click", (e) => {
                        this.close();
                    });
                    this.okButtonNode.on("click", (e) => {
                        this.okAndClose();
                    });
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-search-item-selection-dialog">
                    <div data-role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Add | Columns",
                        height: "450px",
                        width: "600px"
                    };
                }
                init_grid(viewStateId) {
                    this.m_grid = new window["PD"].Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role='grid']"),
                        selectionMode: "multiple",
                        viewStateId: viewStateId,
                        selectOnRightClick: true,
                        defaultSelectionEnabled: false,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.Name
                                    };
                                });
                            }
                        },
                        dblclick: (e) => {
                            this.okAndClose();
                        },
                        needContext: (e) => {
                            e.filters[e.filters.length] = {
                                id: "Group",
                                params: {
                                    id: this.searchGroupId
                                }
                            };
                        }
                    });
                    ;
                }
                okAndClose() {
                    let selections = this.m_grid.getSelections().toArray();
                    let ids = _.map(selections, (item) => {
                        return item.id;
                    });
                    this.close({
                        name: "ok",
                        data: {
                            ids: ids
                        }
                    });
                }
                static open(options) {
                    return new SearchItemsSelectionDialog(options);
                }
            }
            Views.SearchItemsSelectionDialog = SearchItemsSelectionDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$grid", null);
                }
                get grid() {
                    return this.state.get("$grid");
                }
                get viewStateId() {
                    return this.grid.get_viewStateId();
                }
                get viewId() {
                    return parseInt(this.viewStateId.split(".")[3]);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/view-design-editor": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Views.ViewDesignCommand = ViewDesignCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class AnchorCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    var _a, _b;
                    super.onStateChanged(e);
                    this.visible = (_b = (_a = this.grid.get_configuration()) === null || _a === void 0 ? void 0 : _a.get_settings()) === null || _b === void 0 ? void 0 : _b.allowAnchor;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "View Anchors",
                        width: 600,
                        height: 500,
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.Views.ViewAnchorsUIO",
                            arbiterType: "ProspectDirector.Web.Shared.Modules.Views.ViewAnchorsArbiter",
                            properties: {
                                viewStateId: this.viewStateId
                            }
                        },
                        select: {
                            ok: (sender, e) => {
                                this.grid.build();
                                this.grid.refresh();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/anchor",
                        tooltip: "Edit the anchors of this view.",
                        label: "Anchor",
                        icon: "anchor.16px.font",
                        enabled: true,
                        visible: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Views.AnchorCommand = AnchorCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class BoundsColumnsCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    var _a, _b;
                    super.onStateChanged(e);
                    this.visible = (_b = (_a = this.grid.get_configuration()) === null || _a === void 0 ? void 0 : _a.get_settings()) === null || _b === void 0 ? void 0 : _b.isEditor;
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Views.ColumnsDialog.open({
                        viewStateId: this.viewStateId,
                        componentType: "bounds",
                        select: {
                            ok: () => {
                                this.grid.build();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/bounds-columns",
                        tooltip: "Edit the bounds columns of this view.",
                        label: "Bounds Columns",
                        icon: "plus.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.BoundsColumnsCommand = BoundsColumnsCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class BoundsFiltersCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Views.FiltersDialog.open({
                        viewStateId: this.viewStateId,
                        componentType: "bounds",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.build();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/bounds-filters",
                        tooltip: "Edit the bounds filters of this view",
                        label: "Bounds Filters",
                        icon: "filter.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.BoundsFiltersCommand = BoundsFiltersCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class DesignColumnsCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Views.ColumnsDialog.open({
                        viewStateId: this.viewStateId,
                        componentType: "design",
                        select: {
                            ok: () => {
                                this.grid.build();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/design-columns",
                        tooltip: "Edit the design columns of this view",
                        label: "Design Columns",
                        icon: "plus.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.DesignColumnsCommand = DesignColumnsCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class DesignFiltersCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Views.FiltersDialog.open({
                        viewStateId: this.viewStateId,
                        componentType: "design",
                        select: {
                            ok: (sender, e) => {
                                sender.close();
                                this.grid.build();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/design-filters",
                        tooltip: "Edit the design filters of this view",
                        label: "Design Filters",
                        icon: "filter.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.DesignFiltersCommand = DesignFiltersCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class FindInResultsCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Shared.Views.ColumnsDialog.open({
                        viewStateId: this.viewStateId,
                        componentType: "findinresults",
                        select: {
                            ok: () => {
                                this.grid.build();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/find-in-results",
                        tooltip: "Find In Results Columns",
                        label: "Find In Results Columns",
                        icon: "search-1.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.FindInResultsCommand = FindInResultsCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class SaveCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    let service = new PDJS.Services.Views.ViewService();
                    service.commitView({
                        viewId: this.viewId,
                        success: (e) => {
                            PDJS.Shared.MessageStack.instance.success("View settings have been saved.");
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/save",
                        tooltip: "Save",
                        label: "Save",
                        icon: "save.16px.font",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Views.SaveCommand = SaveCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class UndoCommand extends Views.ViewDesignCommand {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    super.onExecute(e);
                    PDJS.Ajax.call({
                        type: "POST",
                        url: Jade.Path.resolve("~/view/undo", {
                            viewStateId: this.viewStateId
                        }),
                        success: (e) => {
                            this.grid.build();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "view/undo",
                        tooltip: "Undo changes made to this view.",
                        label: "Undo",
                        icon: "undo.16px.font",
                        enabled: true,
                        display: "icon label"
                    };
                }
            }
            Views.UndoCommand = UndoCommand;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignCommands extends Jade.CommandGroup {
                constructor() {
                    super(ViewDesignCommands.commandGroupName);
                }
                registerCommands(e) {
                    e.commands.add(new Views.AnchorCommand());
                    e.commands.add(new Views.BoundsColumnsCommand());
                    e.commands.add(new Views.BoundsFiltersCommand());
                    e.commands.add(new Views.DesignColumnsCommand());
                    e.commands.add(new Views.DesignFiltersCommand());
                    e.commands.add(new Views.FindInResultsCommand());
                    e.commands.add(new Views.SaveCommand());
                    e.commands.add(new Views.UndoCommand());
                }
                static get commandGroupName() {
                    return "pdjs/manage/views/publisher/designer";
                }
            }
            Views.ViewDesignCommands = ViewDesignCommands;
            Jade.CommandGroups.add(ViewDesignCommands);
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignerDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get gridNode() {
                    return this.node.find("div[role=grid]");
                }
                get toolbarNode() {
                    return this.node.find("div[role=toolbar]");
                }
                get cancelButton() {
                    return this.node.find("button[data-command=cancel]");
                }
                get okButton() {
                    return this.node.find("button[data-command=ok]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-canvas-shared-view-designer-dialog">
                    <div role="toolbar"></div>
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.m_service =
                        new PDJS.Services.Views.ViewService();
                    this.m_service.getViewState({
                        viewStateId: this.viewStateId,
                        success: (e) => {
                            this.m_viewState = e.data.state;
                            this.grid_init();
                            this.toolbar_init();
                        }
                    });
                }
                getDefaultOptions() {
                    return {
                        title: "View Designer",
                        height: 600,
                        width: 800
                    };
                }
                okButton_onClick(e) {
                    this.close({
                        name: "ok"
                    });
                }
                cancelButton_onClick(e) {
                    if (this.m_viewState == null) {
                        this.close();
                        return;
                    }
                    this.m_service.setViewState({
                        viewStateId: this.viewStateId,
                        state: this.m_viewState,
                        success: (e) => {
                            this.close();
                        }
                    });
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.gridNode,
                        height: "100%",
                        viewStateId: this.viewStateId,
                        defaultSelectionEnabled: false,
                        ready: () => {
                            setTimeout(() => {
                                this.setCommandState();
                            }, 250);
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: `div[role=toolbar]`,
                        segments: [
                            new Views.ViewDesignDialogToolbar()
                        ]
                    });
                    this.controls.add(this.m_toolbar);
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/publisher/designer": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new ViewDesignerDialog(options);
                }
            }
            Views.ViewDesignerDialog = ViewDesignerDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignDialogToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = Views.ViewDesignCommands.commandGroupName;
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/anchor`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/bounds-columns`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/bounds-filters`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/design-columns`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/design-filters`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/undo`
                    }));
                }
            }
            Views.ViewDesignDialogToolbar = ViewDesignDialogToolbar;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get viewStateId() {
                    return this.source.getFeatureValue("viewStateId");
                }
                resize() {
                    if (this.m_grid) {
                        this.m_grid.redraw();
                    }
                }
                focus() {
                    super.focus();
                    if (this.m_grid) {
                        this.m_grid.redraw();
                    }
                }
                template() {
                    return `
                <div class="-fb-view-design-editor">
                    <div role="menu"></div>
                    <div role="grid"></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `#${this.ID} div[role=grid]`,
                        height: "100%",
                        viewStateId: this.viewStateId,
                        defaultSelectionEnabled: false,
                        ready: () => {
                            this.menu_init();
                            this.setCommandState();
                        }
                    });
                }
                menu_init() {
                    this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                        container: `#${this.ID} div[role=menu]`,
                        segments: [
                            new Views.ViewDesignEditorToolbar()
                        ]
                    });
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/publisher/designer": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Views.ViewDesignEditor = ViewDesignEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Views.ViewDesignEditor", ViewDesignEditor);
            });
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDesignEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    let prefix = Views.ViewDesignCommands.commandGroupName;
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/anchor`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/bounds-columns`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/bounds-filters`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/design-columns`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/design-filters`
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:view/undo`
                    }));
                }
            }
            Views.ViewDesignEditorToolbar = ViewDesignEditorToolbar;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewerGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewName() {
                    return this.state.get("viewName");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `<div class="-pdjs-manage-views-viewer-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">${this.viewName}</div>
                        <div role="grid"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: `[id=${this.ID}] [role=grid]`,
                        viewStateId: this.viewStateId,
                        selectionMode: "none",
                        messaging: {
                            noRecordsMessage: "No results."
                        }
                    });
                }
            }
            Views.ViewerGrid = ViewerGrid;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewerModule extends PDJS.Manage.Module {
                constructor(options) {
                    super(options);
                }
                get viewId() {
                    return this.settings.targetId;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get viewName() {
                    return this.state.get("viewName");
                }
                set viewName(value) {
                    this.state.set("viewName", value);
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                resize() {
                    if (this.m_spliiter) {
                        this.m_spliiter.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-viewer">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.module_init();
                }
                grid_init() {
                    this.m_grid = new Views.ViewerGrid({
                        insertAt: "div[data-id=pane-1]",
                        viewName: this.viewName,
                        viewStateId: this.viewStateId,
                        change: (item) => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                module_init() {
                    let service = new PDJS.Services.Views.ViewerService();
                    service.index({
                        id: this.viewId,
                        editor: true,
                        success: (e) => {
                            this.viewName = e.data.name;
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.setCommandState();
                        }
                    });
                }
                splitter_init() {
                    this.m_spliiter = this.splitterNode.kendoSplitter({
                        panes: [
                            { resizable: true, scrollable: false }
                        ],
                        orientation: "horizontal"
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    let setState = this.m_grid != null;
                    if (!setState) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "pdjs/manage/views/viewer": {
                            $grid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Views.ViewerModule = ViewerModule;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get view() {
                        return this.state.get("view");
                    }
                    set view(value) {
                        this.state.set("view", value);
                    }
                    load(view) {
                        this.view = view;
                    }
                    template() {
                        return `<div class="-pdjs-manage-tags-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addItems();
                    }
                    addItems() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Views"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Placeholder Link",
                            click: (e) => {
                                Jade.UI.Dialogs.MessageDialog.open({
                                    message: "Not Implemented"
                                });
                            }
                        }));
                    }
                }
                BuiltIn.BuiltInActions = BuiltInActions;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get selection() {
                        return _.first(this.grid.selections);
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/built-in": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                BuiltIn.BuiltInCommand = BuiltInCommand;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class OpenViewCommand extends BuiltIn.BuiltInCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open",
                            label: "Open View",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Open the selected view.",
                            iconSetId: "pdjs"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selection != null;
                    }
                    execute(e) {
                        window.location.href = `#/module/builtin-viewer/${this.selection.customId}`;
                    }
                }
                BuiltIn.OpenViewCommand = OpenViewCommand;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/views/built-in");
                    }
                    registerCommands(e) {
                        e.commands.add(new BuiltIn.OpenViewCommand());
                    }
                }
                BuiltIn.BuiltInCommands = BuiltInCommands;
                Jade.CommandGroups.add(BuiltInCommands);
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-views-built-in-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Built In Views</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No results."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.Name,
                                        customId: e.CustomId
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/views/built-in:view/open");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new BuiltIn.BuiltInGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.Views.BuiltIn.BuiltInGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                BuiltIn.BuiltInGrid = BuiltInGrid;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/views/built-in";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:view/open`
                        }));
                    }
                }
                BuiltIn.BuiltInGridContextMenu = BuiltInGridContextMenu;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/views/built-in";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/open`
                        }));
                    }
                }
                BuiltIn.BuiltInGridToolbar = BuiltInGridToolbar;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-built-in">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.settings.label = "Built In Views";
                        this.splitter_init();
                        this.module_init();
                    }
                    grid_init() {
                        this.m_grid = new BuiltIn.BuiltInGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    module_init() {
                        let service = new PDJS.Services.Views.BuiltIn.BuiltInService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/built-in": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                BuiltIn.BuiltInModule = BuiltInModule;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class ViewerCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/views/built-in/viewer");
                    }
                    registerCommands(e) {
                        e.commands.add(new Views.AnchorCommand());
                        e.commands.add(new Views.BoundsColumnsCommand());
                        e.commands.add(new Views.BoundsFiltersCommand());
                        e.commands.add(new Views.DesignColumnsCommand());
                        e.commands.add(new Views.DesignFiltersCommand());
                        e.commands.add(new Views.FindInResultsCommand());
                        e.commands.add(new Views.SaveCommand());
                        e.commands.add(new Views.UndoCommand());
                    }
                }
                BuiltIn.ViewerCommands = ViewerCommands;
                Jade.CommandGroups.add(ViewerCommands);
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class ViewerGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get builtCallback() {
                        return this.state.get("built", () => { });
                    }
                    get viewGrid() {
                        return this.m_grid;
                    }
                    get viewName() {
                        return this.state.get("viewName");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-views-built-in-viewer-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Built In | ${this.viewName}</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "none",
                            built: () => {
                                this.builtCallback();
                            },
                            messaging: {
                                noRecordsMessage: "No results."
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new BuiltIn.ViewerGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                }
                BuiltIn.ViewerGrid = ViewerGrid;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class ViewerGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/views/built-in/viewer";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/save`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/undo`
                        }));
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/anchor`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/design-columns`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/design-filters`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/bounds-columns`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/bounds-filters`
                        }));
                    }
                }
                BuiltIn.ViewerGridToolbar = ViewerGridToolbar;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class ViewerModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get targetId() {
                        return this.settings.targetId;
                    }
                    get viewId() {
                        return this.state.get("viewId");
                    }
                    set viewId(value) {
                        this.state.set("viewId", value);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get viewName() {
                        return this.state.get("viewName");
                    }
                    set viewName(value) {
                        this.state.set("viewName", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-built-in-viewer">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.module_init();
                    }
                    grid_init() {
                        this.m_grid = new BuiltIn.ViewerGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewName: this.viewName,
                            viewStateId: this.viewStateId,
                            built: () => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    module_init() {
                        let service = new PDJS.Services.Views.ViewerService();
                        service.index({
                            id: this.targetId,
                            editor: true,
                            success: (e) => {
                                this.viewId = e.data.viewId;
                                this.viewName = e.data.name;
                                this.viewStateId = e.data.viewStateId;
                                this.settings.label = `Built In | ${this.viewName}`;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null &&
                            this.m_grid.viewGrid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/built-in/viewer": {
                                $grid: this.m_grid.viewGrid,
                                viewId: this.viewId
                            }
                        }, { force: true });
                    }
                }
                BuiltIn.ViewerModule = ViewerModule;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsActions extends PDJS.Shared.UI.Controls.PanelMenu {
                    get view() {
                        return this.state.get("view");
                    }
                    set view(value) {
                        this.state.set("view", value);
                    }
                    load(view) {
                        this.view = view;
                    }
                    template() {
                        return `<div class="-pdjs-manage-views-insights-actions ${Manage.CssClass.ActionPane}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls class="${Manage.CssClass.ModuleSectionBody}"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addItems();
                    }
                    addItems() {
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                            label: "Views"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                            label: "Placeholder Link",
                            click: (e) => {
                                Jade.UI.Dialogs.MessageDialog.open({
                                    message: "Not Implemented"
                                });
                            }
                        }));
                    }
                }
                Insights.InsightsActions = InsightsActions;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsCommand extends Jade.Command {
                    constructor(options = {}) {
                        super(options);
                        this.state.set("$grid", null);
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get selection() {
                        return _.first(this.grid.selections);
                    }
                    setCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/insights": {
                                $grid: this.grid
                            }
                        }, { force: true });
                    }
                }
                Insights.InsightsCommand = InsightsCommand;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class OpenViewCommand extends Insights.InsightsCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "view/open",
                            label: "Open View",
                            icon: "arrow_right_green.png",
                            enabled: false,
                            display: "icon label",
                            tooltip: "Open the selected view.",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selection != null;
                    }
                    execute(e) {
                        window.location.href = `#/module/insights-viewer/${this.selection.customId}`;
                    }
                }
                Insights.OpenViewCommand = OpenViewCommand;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsCommands extends Jade.CommandGroup {
                    constructor() {
                        super("pdjs/manage/views/insights");
                    }
                    registerCommands(e) {
                        e.commands.add(new Insights.OpenViewCommand());
                    }
                }
                Insights.InsightsCommands = InsightsCommands;
                Jade.CommandGroups.add(InsightsCommands);
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get selections() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().toArray();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-views-insights-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Insights</div>
                        <div role="menu"></div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            selectOnRightClick: true,
                            messaging: {
                                noRecordsMessage: "No results."
                            },
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.Name,
                                        customId: e.CustomId
                                    };
                                }
                            },
                            dblclick: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("pdjs/manage/views/insights:view/open");
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            },
                            contextMenu: (e) => {
                                this.contextMenu_init();
                            }
                        });
                    }
                    menu_init() {
                        this.m_menu = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[role=menu]",
                            segments: [new Insights.InsightsGridToolbar()]
                        });
                        this.controls.add(this.m_menu);
                    }
                    contextMenu_init() {
                        let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                            grid: this.m_grid,
                            segments: [{
                                    type: "PDJS.Manage.Views.Insights.InsightsGridContextMenu"
                                }]
                        });
                        this.controls.add(contextMenu);
                    }
                }
                Insights.InsightsGrid = InsightsGrid;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsGridContextMenu extends Jade.UI.ContextMenuSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/views/insights";
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: `${prefix}:view/open`
                        }));
                    }
                }
                Insights.InsightsGridContextMenu = InsightsGridContextMenu;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsGridToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                    onAddItems(e) {
                        let prefix = "pdjs/manage/views/insights";
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:view/open`
                        }));
                    }
                }
                Insights.InsightsGridToolbar = InsightsGridToolbar;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-built-in">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                        this.module_init();
                    }
                    grid_init() {
                        this.m_grid = new Insights.InsightsGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    module_init() {
                        let service = new PDJS.Services.Views.Insights.InsightsService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                                this.setCommandState();
                            }
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/insights": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                Insights.InsightsModule = InsightsModule;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class ViewerGrid extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get viewName() {
                        return this.state.get("viewName");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    refresh(e = {}) {
                        this.m_grid.refresh(e);
                    }
                    template() {
                        return `<div class="-pdjs-manage-views-insights-viewer-grid">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Insights | ${this.viewName}</div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "none",
                            messaging: {
                                noRecordsMessage: "No results."
                            }
                        });
                    }
                }
                Insights.ViewerGrid = ViewerGrid;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class ViewerModule extends PDJS.Manage.Module {
                    constructor(options) {
                        super(options);
                    }
                    get viewId() {
                        return this.settings.targetId;
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get viewName() {
                        return this.state.get("viewName");
                    }
                    set viewName(value) {
                        this.state.set("viewName", value);
                    }
                    get splitterNode() {
                        return this.node.children("div[role=splitter]");
                    }
                    resize() {
                        if (this.m_spliiter) {
                            this.m_spliiter.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-views-insights-viewer">
                        <div role="splitter">
                            <div data-id="pane-1"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter_init();
                    }
                    onModuleLoad(e) {
                        super.onModuleLoad(e);
                        e.addStep(() => this.module_init());
                    }
                    grid_init() {
                        this.m_grid = new Insights.ViewerGrid({
                            insertAt: "div[data-id=pane-1]",
                            viewName: this.viewName,
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_grid);
                    }
                    module_init() {
                        return this.modulePromise((resolve, reject) => {
                            let service = new PDJS.Services.Views.ViewerService();
                            service.index({
                                id: this.viewId,
                                editor: false,
                                success: (e) => {
                                    this.viewName = e.data.name;
                                    this.viewStateId = e.data.viewStateId;
                                    this.grid_init();
                                    this.setCommandState();
                                    this.settings.label = `Insights | ${this.viewName}`;
                                    resolve();
                                },
                                error: (e) => { reject(e); }
                            });
                        });
                    }
                    splitter_init() {
                        this.m_spliiter = this.splitterNode.kendoSplitter({
                            panes: [
                                { resizable: true, scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_grid != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/views/viewer": {
                                $grid: this.m_grid
                            }
                        }, { force: true });
                    }
                }
                Insights.ViewerModule = ViewerModule;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        let Events;
        (function (Events) {
            Events["PreferencesChanged"] = "PDJS.Shared.Profiles.PreferencesChanged";
            Events["ThemeChanged"] = "PDJS.Shared.Profiles.ThemeChanged";
        })(Events = Profiles.Events || (Profiles.Events = {}));
        class EventsHub extends PDJS.Shared.EventsHubBase {
            static get broadcaster() {
                if (this.m_broadcaster == null) {
                    this.m_broadcaster = new Profiles.ProfileBroadcaster();
                }
                return this.m_broadcaster;
            }
            static preferencesChangedPublish(e) {
                this.global.publish(Events.PreferencesChanged, e);
                if (e.sourceId == null) {
                    e.sourceId = PDJS.Application.instance.instanceId;
                }
                if (e.sourceId == PDJS.Application.instance.instanceId) {
                    this.broadcaster.publishPreferencesChanged(e);
                }
            }
            static themeChangedPublish() {
                this.global.publish(Events.ThemeChanged);
            }
            static preferencesChangedSubscribe(callback) {
                return this.global.subscribe(Events.PreferencesChanged, callback);
            }
            static themeChangedSubscribe(callback) {
                return this.global.subscribe(Events.ThemeChanged, callback);
            }
        }
        Profiles.EventsHub = EventsHub;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class Profile extends PDJS.Core.Model {
            constructor(options) {
                super(options);
                this.m_identity = new Profiles.ProfileIdentity(options.identity);
                this.m_preferences = new Profiles.ProfilePreferences(options.preferences);
                this.m_recent = new Profiles.ProfileRecent(options.recent);
                this.m_themes = new Profiles.ProfileThemes(options.themes);
            }
            static get current() {
                return this.m_current;
            }
            get identity() {
                return this.m_identity;
            }
            get preferences() {
                return this.m_preferences;
            }
            get recent() {
                return this.m_recent;
            }
            get themes() {
                return this.m_themes;
            }
            static load(options) {
                if (this.m_current == null) {
                    this.m_current = new Profile(options);
                }
            }
        }
        Profiles.Profile = Profile;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Messaging;
        (function (Messaging) {
            class Broadcaster {
                constructor(options) {
                    this.m_channel = new BroadcastChannel(options.name);
                }
                get channel() {
                    return this.m_channel;
                }
                subscribe(handler, sourceName) {
                    return this.channel.addEventListener("message", (e) => {
                        let message = e.data;
                        if (message.sourceName == sourceName) {
                            handler(message.sourceData);
                        }
                    });
                }
                unsubscribe(handler) {
                    this.channel.removeEventListener("message", handler);
                }
                sendMessage(data, sourceName) {
                    let message = {
                        sourceId: PDJS.Application.instance.instanceId,
                        sourceName: sourceName,
                        sourceData: data
                    };
                    this.channel.postMessage(message);
                }
            }
            Messaging.Broadcaster = Broadcaster;
        })(Messaging = Shared.Messaging || (Shared.Messaging = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfileBroadcaster extends PDJS.Shared.Messaging.Broadcaster {
            constructor() {
                super({ name: "profile-broadcaster" });
            }
            publishPreferencesChanged(args) {
                this.sendMessage(args, "preferencesChanged");
            }
            subscribePreferencesChanged(handler) {
                this.subscribe(handler, "preferencesChanged");
            }
        }
        Profiles.ProfileBroadcaster = ProfileBroadcaster;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfileIdentity extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get id() {
                return this.state.get("id");
            }
            get accountName() {
                return this.state.get("accountName", false);
            }
            get displayName() {
                return this.state.get("displayName", false);
            }
            get isAdmin() {
                return this.state.get("isAdmin", false);
            }
        }
        Profiles.ProfileIdentity = ProfileIdentity;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfilePreferences extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get explorerAncestorDisplayMode() {
                return this.state.get("explorerAncestorDisplayMode", 0);
            }
            set explorerAncestorDisplayMode(value) {
                this.state.set("explorerAncestorDisplayMode", value);
            }
            get onCreateBehavior() {
                return this.state.get("onCreateBehavior", 0);
            }
            set onCreateBehavior(value) {
                this.state.set("onCreateBehavior", value);
            }
            get onOpenBehavior() {
                return this.state.get("onOpenBehavior", 0);
            }
            set onOpenBehavior(value) {
                this.state.set("onOpenBehavior", value);
            }
            get openLastViewedExplorerFolder() {
                return this.state.get("openLastViewedExplorerFolder", false);
            }
            set openLastViewedExplorerFolder(value) {
                this.state.set("openLastViewedExplorerFolder", value);
            }
            get scrollBarSize() {
                return this.state.get("scrollBarSize", 14);
            }
            set scrollBarSize(value) {
                this.state.set("scrollBarSize", value);
            }
            update(state) {
                this.state.set(state);
            }
            initialize() {
                this.m_broadcaster = new Profiles.ProfileBroadcaster();
                this.m_broadcaster.subscribePreferencesChanged((e) => {
                    this.update({
                        explorerAncestorDisplayMode: e.explorerAncestorDisplayMode,
                        onCreateBehavior: e.onCreateBehavior,
                        onOpenBehavior: e.onOpenBehavior,
                        openLastViewedExplorerFolder: e.openLastViewedExplorerFolder,
                        scrollBarSize: e.scrollBarSize
                    });
                });
            }
            onStateChanged() {
                super.onStateChanged();
                Profiles.EventsHub.preferencesChangedPublish(this.state.toJSON());
                PDJS.System.Environment.setScrollBarSize();
            }
        }
        Profiles.ProfilePreferences = ProfilePreferences;
        PDJS.Application.onStart(() => {
            PDJS.System.Environment.current.profile.preferences.initialize();
        });
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfileRecent extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get entities() {
                return this.state.get("entities", []);
            }
            get views() {
                return this.state.get("views", []);
            }
        }
        Profiles.ProfileRecent = ProfileRecent;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfileSettings extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get newEntityMenuVisible() {
                return this.state.get("newEntityMenuVisible", 0);
            }
        }
        Profiles.ProfileSettings = ProfileSettings;
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Profiles;
    (function (Profiles) {
        class ProfileThemes extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get canvas() {
                return this.state.get("canvas");
            }
            set canvas(value) {
                this.state.set("canvas", value);
            }
            get hub() {
                return this.state.get("hub");
            }
            set hub(value) {
                this.state.set("hub", value);
            }
            get hubEditor() {
                return this.state.get("hubEditor");
            }
            set hubEditor(value) {
                this.state.set("hubEditor", value);
            }
            get isHubUsingDefault() {
                return this.hub === null;
            }
            get manage() {
                return this.state.get("manage");
            }
            set manage(value) {
                this.state.set("manage", value);
            }
            get manageEditor() {
                return this.state.get("manageEditor");
            }
            set manageEditor(value) {
                this.state.set("manageEditor", value);
            }
            get isManageUsingHub() {
                return this.manage === null;
            }
            get default() {
                return this.state.get("default");
            }
            get defaultEditor() {
                return this.manageEditor || this.hubEditor || this.defaultEditor;
            }
            get editor() {
                return this.getScopeSpecificEditor();
            }
            get editorThemeOverride() {
                return localStorage.getItem("code:editor:theme");
            }
            set editorThemeOverride(value) {
                localStorage.setItem("code:editor:theme", value);
            }
            initialize() {
                PDJS.Shared.Themes.EventsHub
                    .setThemeSubscribe(_.bind(this.onThemeChanged, this));
            }
            getScopeSpecificEditor() {
                if (PDJS.Application.instance.name == "hub") {
                    return this.hubEditor || this.defaultEditor;
                }
                if (PDJS.Application.instance.name == "manage") {
                    return this.editorThemeOverride || this.manageEditor || this.hubEditor || this.defaultEditor;
                }
            }
            onThemeChanged(e) {
                switch (e.themeScope) {
                    case PDJS.Services.Themes.ThemeScope.Canvas:
                        this.canvas = e.themeId;
                        break;
                    case PDJS.Services.Themes.ThemeScope.Hub:
                        this.hub = e.themeId;
                        this.hubEditor = e.themeEditor;
                        break;
                    case PDJS.Services.Themes.ThemeScope.Manage:
                        if (e.sourceScope == PDJS.Services.Themes.ThemeScope.Manage) {
                            this.manage = e.themeId;
                            this.manageEditor = e.themeEditor;
                        }
                        break;
                }
                Profiles.EventsHub.themeChangedPublish();
            }
        }
        Profiles.ProfileThemes = ProfileThemes;
        PDJS.Application.onStart(() => {
            PDJS.System.Environment.current.profile.themes.initialize();
        });
    })(Profiles = PDJS.Profiles || (PDJS.Profiles = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        Jade.Application.onStart(() => {
            let service = new Services.Views.ViewService();
            service.getViewStateIds();
        });
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class Error {
            constructor(options) {
                this.m_code = options.code;
                this.m_message = options.message;
            }
            get code() {
                return this.m_code;
            }
            get message() {
                return this.m_message;
            }
        }
        Services.Error = Error;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class GenericService {
            serviceMethod(data) {
                Services.ServicePipeline.createRequest({
                    url: "",
                    method: Jade.HttpVerb.GET,
                    data: data
                }).sendRequest();
            }
        }
        Services.GenericService = GenericService;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class HttpError extends Services.Error {
        }
        Services.HttpError = HttpError;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class Service {
        }
        Services.Service = Service;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class ServiceError extends Services.Error {
        }
        Services.ServiceError = ServiceError;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class ServicePipeline {
            constructor() {
                this.m_tasks = new Services.ServiceTaskCollection({
                    pipeline: this
                });
                this.m_stopped = false;
            }
            get tasks() {
                return this.m_tasks;
            }
            get request() {
                return this.m_request;
            }
            get response() {
                return this.m_response;
            }
            set response(value) {
                this.m_response = value;
            }
            get stopped() {
                return this.m_stopped;
            }
            set stopped(value) {
                this.m_stopped = value;
            }
            addBeforeSendTask(callback) {
                return this.addTask(Services.ServiceTaskType.OnBeforeSend, callback);
            }
            addErrorTask(callback) {
                return this.addTask(Services.ServiceTaskType.OnError, callback);
            }
            addSuccessTask(callback) {
                return this.addTask(Services.ServiceTaskType.OnSuccess, callback);
            }
            addCompleteTask(callback) {
                return this.addTask(Services.ServiceTaskType.OnComplete, callback);
            }
            createRequest(options) {
                this.m_request = new Services.ServiceRequestOf(options);
                return this;
            }
            sendRequest() {
                let ajaxSettings = _.extend({
                    contentType: this.request.contentType,
                    url: Jade.Path.resolve(this.request.url),
                    method: this.request.method,
                    data: this.request.getDataForAjaxRequest()
                }, {
                    beforeSend: _.bind(this.onBeforeSend, this),
                    error: _.bind(this.onError, this),
                    success: _.bind(this.onSuccess, this),
                    complete: _.bind(this.onComplete, this)
                });
                $.ajax(ajaxSettings);
            }
            abortRequestWithSuccess(timeout = 0) {
                this.request.xhr.abort();
                let success = () => {
                    this.onSuccess(this.response.data, "success", this.request.xhr);
                    this.onComplete(this.request.xhr, "complete");
                };
                if (timeout > 0) {
                    setTimeout(success, timeout);
                }
                else {
                    success();
                }
            }
            abortRequestWithError(timeout = 0) {
                this.request.xhr.abort();
                let error = () => {
                    this.onError(this.request.xhr, "error", "aborted by service");
                    this.onComplete(this.request.xhr, "complete");
                };
                if (timeout > 0) {
                    setTimeout(error, timeout);
                }
                else {
                    error();
                }
            }
            static bundleJsonData(bundleName, data) {
                let result = {};
                let bundle = {};
                for (let key in data) {
                    _.isFunction(data[key]) ?
                        result[key] = data[key] :
                        bundle[key] = data[key];
                }
                if (!_.isEmpty(bundle)) {
                    result[bundleName] = JSON.stringify(bundle);
                }
                return result;
            }
            onBeforeSend(xhr, textStatus) {
                this.request.xhr = xhr;
                this.response = new Services.ServiceResponse({
                    xhr: xhr
                });
                this.tasks.execute(Services.ServiceTaskType.OnBeforeSend);
                this.request.beforeSend(this.response);
            }
            onComplete(xhr, textStatus) {
                this.tasks.execute(Services.ServiceTaskType.OnComplete);
                this.request.complete(this.response);
            }
            onSuccess(data, textStatus, xhr) {
                this.response.data = data;
                this.response.statusText = textStatus;
                this.tasks.execute(Services.ServiceTaskType.OnSuccess);
                this.request.success(this.response);
            }
            onError(xhr, statueText, errorThrown) {
                this.response.error = new Services.HttpError({
                    code: xhr.status,
                    message: errorThrown
                });
                this.tasks.execute(Services.ServiceTaskType.OnError);
                this.request.error(this.response);
                if (!this.response.errorHandled) {
                    new PDJS.AjaxErrorHandler({
                        jqXHR: xhr
                    });
                }
            }
            addTask(type, callback) {
                this.tasks.add(new Services.ServiceTask({
                    type: type,
                    callback: callback
                }));
                return this;
            }
            static createRequest(options) {
                let result = new ServicePipeline();
                options.data = options.data == null ?
                    {} : options.data;
                result.createRequest(options);
                return result;
            }
        }
        Services.ServicePipeline = ServicePipeline;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        let ContentType;
        (function (ContentType) {
            ContentType["JSON"] = "application/json";
            ContentType["HTML"] = "html";
        })(ContentType = Services.ContentType || (Services.ContentType = {}));
        class ServiceRequest {
            constructor(options) {
                this.m_callbacks = {};
                this.registerCallbacks(options.data);
                this.m_options = new Jade.StateBag(options);
            }
            get accepts() {
                return this.options.get("accepts");
            }
            set accepts(value) {
                this.options.get("accepts", value);
            }
            get async() {
                return this.options.get("async");
            }
            set async(value) {
                this.options.get("async", value);
            }
            get beforeSend() {
                return this.getCallback("beforeSend");
            }
            set beforeSend(value) {
                this.setCallback("beforeSend", value);
            }
            get cache() {
                return this.options.get("cache", false);
            }
            set cache(value) {
                this.options.get("cache", value);
            }
            get complete() {
                return this.getCallback("complete");
            }
            set complete(value) {
                this.setCallback("complete", value);
            }
            get contentType() {
                return this.options.get("contentType", ContentType.JSON);
            }
            set contentType(value) {
                this.options.get("contentType", value);
            }
            get error() {
                return this.getCallback("error");
            }
            set error(value) {
                this.setCallback("error", value);
            }
            get data() {
                return this.options.get("data", null);
            }
            set data(value) {
                this.options.set("data", value);
            }
            get options() {
                return this.m_options;
            }
            get success() {
                return this.getCallback("success");
            }
            set success(value) {
                this.setCallback("success", value);
            }
            get method() {
                return this.options.get("method");
            }
            set method(value) {
                this.options.get("method", value);
            }
            get url() {
                return this.options.get("url");
            }
            set url(value) {
                this.options.set("url", value);
            }
            get xhr() {
                return this.m_xhr;
            }
            set xhr(value) {
                this.m_xhr = value;
            }
            getDataForAjaxRequest() {
                let result;
                let shouldStringify = this.contentType === ContentType.JSON &&
                    (this.method === Jade.HttpVerb.POST || this.method === Jade.HttpVerb.PUT || this.method === Jade.HttpVerb.DELETE);
                if (shouldStringify) {
                    result = JSON.stringify(this.data);
                }
                else {
                    result = this.data;
                }
                return result;
            }
            getCallback(name) {
                let result = () => { };
                if (this.m_callbacks[name] != null) {
                    result = this.m_callbacks[name];
                }
                return result;
            }
            setCallback(name, callback) {
                this.m_callbacks[name] = callback;
            }
            registerCallbacks(callbacks) {
                this.beforeSend = callbacks.beforeSend;
                this.complete = callbacks.complete;
                this.error = callbacks.error;
                this.success = callbacks.success;
                delete callbacks.beforeSend;
                delete callbacks.complete;
                delete callbacks.error;
                delete callbacks.success;
            }
            send(arg1) { }
        }
        Services.ServiceRequest = ServiceRequest;
        class ServiceRequestOf extends ServiceRequest {
            constructor(options) {
                super(options);
            }
            get data() {
                return this.options.get("data", null);
            }
            set data(value) {
                this.options.set("data", value);
            }
            get beforeSend() {
                return this.getCallback("beforeSend");
            }
            set beforeSend(value) {
                this.setCallback("beforeSend", value);
            }
            get complete() {
                return this.getCallback("complete");
            }
            set complete(value) {
                this.setCallback("complete", value);
            }
            get error() {
                return this.getCallback("error");
            }
            set error(value) {
                this.setCallback("error", value);
            }
            get success() {
                return this.getCallback("success");
            }
            set success(value) {
                this.setCallback("success", value);
            }
        }
        Services.ServiceRequestOf = ServiceRequestOf;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class ServiceResponse {
            constructor(options) {
                this.m_error = options.error;
                this.m_xhr = options.xhr;
                this.m_data = options.data;
            }
            get hasError() {
                return this.m_error != null;
                ;
            }
            get errorHandled() {
                return this.m_errorHandled;
            }
            set errorHandled(value) {
                this.m_errorHandled = value;
            }
            get error() {
                return this.m_error;
            }
            set error(value) {
                this.m_error = value;
            }
            get statusText() {
                return this.m_statusText;
            }
            set statusText(value) {
                this.m_statusText = value;
            }
            get data() {
                return this.m_data;
            }
            set data(value) {
                this.m_data = value;
            }
            get xhr() {
                return this.m_xhr;
            }
            set xhr(value) {
                this.m_xhr = value;
            }
        }
        Services.ServiceResponse = ServiceResponse;
        class ServiceResponseOf extends ServiceResponse {
            constructor(options) {
                super(options);
            }
            get data() {
                return this.m_data;
            }
            set data(value) {
                this.m_data = value;
            }
        }
        Services.ServiceResponseOf = ServiceResponseOf;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        let ServiceTaskType;
        (function (ServiceTaskType) {
            ServiceTaskType[ServiceTaskType["OnBeforeSend"] = 0] = "OnBeforeSend";
            ServiceTaskType[ServiceTaskType["OnError"] = 1] = "OnError";
            ServiceTaskType[ServiceTaskType["OnSuccess"] = 2] = "OnSuccess";
            ServiceTaskType[ServiceTaskType["OnComplete"] = 3] = "OnComplete";
        })(ServiceTaskType = Services.ServiceTaskType || (Services.ServiceTaskType = {}));
        class ServiceTask {
            constructor(options) {
                this.m_type = options.type;
                this.m_callback = options.callback;
            }
            get type() {
                return this.m_type;
            }
            execute(pipeline) {
                if (_.isFunction(this.m_callback)) {
                    _.bind(this.m_callback, this)(pipeline);
                }
            }
        }
        Services.ServiceTask = ServiceTask;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        class ServiceTaskCollection extends Jade.Collection {
            constructor(options) {
                super([]);
                this.m_pipeline = options.pipeline;
            }
            get pipeline() {
                return this.m_pipeline;
            }
            execute(type) {
                this.each((item) => {
                    if (this.pipeline.stopped == false && item.type === type) {
                        item.execute(this.pipeline);
                    }
                });
            }
        }
        Services.ServiceTaskCollection = ServiceTaskCollection;
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var ActiveDirectory;
        (function (ActiveDirectory) {
            class ActiveDirectoryService {
                deleteDomain(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/DeleteDomain",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                syncGroup(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/SyncGroup",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                syncGroups(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/SyncGroups",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                syncUser(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/SyncUser",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                syncUsers(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/SyncUsers",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            ActiveDirectory.ActiveDirectoryService = ActiveDirectoryService;
        })(ActiveDirectory = Services.ActiveDirectory || (Services.ActiveDirectory = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            class DocumentService {
                loadActualDocument(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Canvas/Document/Load",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadDesignDocument(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/Document/Load",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                saveDesignDocument(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/Document/Save",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                closeDesignDocument(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/Document/Close",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Canvas.DocumentService = DocumentService;
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            class ElementService {
                getCachedData(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Canvas/Element/GetCachedData",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                createDesignElements(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/Element/Create",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteDesignElements(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/Element/Delete",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Canvas.ElementService = ElementService;
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            class ListItemService {
                create(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Canvas/ListItem/Create",
                        method: Jade.HttpVerb.POST,
                        data: _.extend(data, {
                            document: data.document.toJSON()
                        })
                    }).sendRequest();
                }
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Canvas/ListItem/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                update(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Canvas/ListItem/Edit",
                        method: Jade.HttpVerb.POST,
                        data: _.extend(data, {
                            document: data.document.toJSON()
                        })
                    }).sendRequest();
                }
            }
            Canvas.ListItemService = ListItemService;
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            class ToolBoxService {
                load(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Canvas/ToolBox/Load",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Canvas.ToolBoxService = ToolBoxService;
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            var Files;
            (function (Files) {
                class FileService {
                    create(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Hub/Canvas/File/Create",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                    edit(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Hub/Canvas/File/Edit",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                    getCanvasDocument(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Hub/Canvas/File/GetCanvasDocument",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                }
                Files.FileService = FileService;
            })(Files = Canvas.Files || (Canvas.Files = {}));
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            var Forms;
            (function (Forms) {
                class FormFieldService {
                    entityFieldQuery(data) {
                        Services.ServicePipeline.createRequest({
                            url: Jade.Path.resolve("~/Hub/Canvas/FormField/EntityFieldQuery"),
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                    entityParentFieldQuery(data) {
                        Services.ServicePipeline.createRequest({
                            url: Jade.Path.resolve("~/Hub/Canvas/FormField/EntityParentFieldQuery"),
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                    userFieldQuery(data) {
                        Services.ServicePipeline.createRequest({
                            url: Jade.Path.resolve("~/Hub/Canvas/FormField/UserFieldQuery"),
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                }
                Forms.FormFieldService = FormFieldService;
            })(Forms = Canvas.Forms || (Canvas.Forms = {}));
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Canvas;
        (function (Canvas) {
            var Forms;
            (function (Forms) {
                class FormService {
                    submit(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Hub/Canvas/Form/Save",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                    validate(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Hub/Canvas/Form/Validate",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                }
                Forms.FormService = FormService;
            })(Forms = Canvas.Forms || (Canvas.Forms = {}));
        })(Canvas = Services.Canvas || (Services.Canvas = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DataLoad;
        (function (DataLoad) {
            class DataLoadService {
                createJob(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/dataload/createjob",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteAllJobs(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/dataload/deletealljobs",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                deleteJobs(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/dataload/deletejobs",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/dataload",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            DataLoad.DataLoadService = DataLoadService;
        })(DataLoad = Services.DataLoad || (Services.DataLoad = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DataModel;
        (function (DataModel) {
            class DataColumnService {
                deleteColumns(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/DataModel/DeleteExtensionColumn",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            DataModel.DataColumnService = DataColumnService;
        })(DataModel = Services.DataModel || (Services.DataModel = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DataModel;
        (function (DataModel) {
            class DataModelService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/datamodel",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            DataModel.DataModelService = DataModelService;
        })(DataModel = Services.DataModel || (Services.DataModel = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DataModel;
        (function (DataModel) {
            class DataTableService {
                deleteTable(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/datamodel/deleteextension",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            DataModel.DataTableService = DataTableService;
        })(DataModel = Services.DataModel || (Services.DataModel = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DataModel;
        (function (DataModel) {
            class SelectionListService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SelectionList",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                deleteList(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SelectionList/DeleteList",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                deleteListItems(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SelectionList/DeleteItem",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                moveListItems(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SelectionList/MoveItems",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            DataModel.SelectionListService = SelectionListService;
        })(DataModel = Services.DataModel || (Services.DataModel = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypeService {
                deleteDocumentType(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/DocumentTypes/DeleteDocumentType",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/DocumentTypes",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadDocumentType(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/DocumentType/Load",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadDocumentTypes(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/DocumentTypes/Load",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            DocumentTypes.DocumentTypeService = DocumentTypeService;
        })(DocumentTypes = Services.DocumentTypes || (Services.DocumentTypes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Entities;
        (function (Entities) {
            class EntitiesService {
                changeStatus(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityManagement/ChangeStatus",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                changeTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityManagement/ChangeTags",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getEntityTypes(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityManagement/GetEntityTypes",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                move(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/EntityManagement/Move",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                runScript(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityManagement/RunScript",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Entities.EntitiesService = EntitiesService;
        })(Entities = Services.Entities || (Services.Entities = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Entities;
        (function (Entities) {
            class EntityService {
                cascadePermissions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Security/CascadePermissions",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Entities.EntityService = EntityService;
        })(Entities = Services.Entities || (Services.Entities = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypeService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityType",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            EntityTypes.EntityTypeService = EntityTypeService;
        })(EntityTypes = Services.EntityTypes || (Services.EntityTypes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var EntityTypes;
        (function (EntityTypes) {
            class EntityTypesService {
                deleteEntityType(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypes/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypes",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypes/List",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                query(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypes/Query",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            EntityTypes.EntityTypesService = EntityTypesService;
        })(EntityTypes = Services.EntityTypes || (Services.EntityTypes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var EntityTypes;
        (function (EntityTypes) {
            class ExplorerModelService {
                loadFolders(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/ExplorerModel/GetFolders",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            EntityTypes.ExplorerModelService = ExplorerModelService;
        })(EntityTypes = Services.EntityTypes || (Services.EntityTypes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var EntityTypes;
        (function (EntityTypes) {
            class RelationshipsService {
                addRelationship(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypeRelationships/AddRelationship",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteRelationship(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypeRelationships/DeleteRelationship",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getRelationships(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypeRelationships/GetRelationships",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getRelationshipTree(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypeRelationships/GetRelationshipTree",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            EntityTypes.RelationshipsService = RelationshipsService;
        })(EntityTypes = Services.EntityTypes || (Services.EntityTypes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var EventLog;
        (function (EventLog) {
            class EventLogService {
                clearLog(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EventLog/Clear",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getApplicationLogUrl(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EventLog/GetApplicationLogUrl",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EventLog",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            EventLog.EventLogService = EventLogService;
        })(EventLog = Services.EventLog || (Services.EventLog = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Explorer;
        (function (Explorer) {
            class ExplorerService {
                getExplorer(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Explorer/GetExplorer",
                        contentType: Services.ContentType.JSON,
                        method: Jade.HttpVerb.POST,
                        data: Services.ServicePipeline.bundleJsonData("args", data),
                    }).sendRequest();
                }
                getExplorerNodes(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Explorer/GetExplorerNodes",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getContent(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Explorer/GetContent",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Explorer.ExplorerService = ExplorerService;
        })(Explorer = Services.Explorer || (Services.Explorer = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Files;
        (function (Files) {
            class FileService {
                downloadMultipleFiles(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/File/DownloadMultipleFiles",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                downloadMultipleFilesZip(data) {
                    Services.ServicePipeline.createRequest({
                        data: data
                    }).addBeforeSendTask((e) => {
                        e.abortRequestWithSuccess();
                        if (data.path == null) {
                            return;
                        }
                        PDJS.Shared.Downloader.downloadWithProgress({
                            url: "~/file/DownloadMultipleFilesZip",
                            params: {
                                path: data.path
                            }
                        });
                    }).sendRequest();
                }
                load(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/File/Load",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getFileInfo(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/File/GetFileInfo",
                        method: Jade.HttpVerb.GET,
                        data: _.extend(data, {
                            fileIds: JSON.stringify(data.fileIds)
                        })
                    }).sendRequest();
                }
                moveFiles(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/File/MoveFiles",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                replaceFile(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/File/ReplaceFile",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Files.FileService = FileService;
        })(Files = Services.Files || (Services.Files = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Jobs;
        (function (Jobs) {
            class JobsLogService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/JobsLog/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/JobsLog/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            Jobs.JobsLogService = JobsLogService;
        })(Jobs = Services.Jobs || (Services.Jobs = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Jobs;
        (function (Jobs) {
            class JobService {
                deleteJobs(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/DeleteJobs",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                executeJob(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/ExecuteJob",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getJobData(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/GetJobData",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadExpressions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/LoadExpressions",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                previewSchedule(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/PreviewSchedule",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                pauseJobs(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/PauseJobs",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                resumeJobs(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/ResumeJobs",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                saveExpressions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/SaveExpressions",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                validateExpression(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/ValidateExpression",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Jobs.JobService = JobService;
        })(Jobs = Services.Jobs || (Services.Jobs = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Licenses;
        (function (Licenses) {
            class LicensesService {
                applyLicenses(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licenses/Apply",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licenses",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                removeLicense(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licenses/Remove",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            Licenses.LicensesService = LicensesService;
        })(Licenses = Services.Licenses || (Services.Licenses = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Licenses;
        (function (Licenses) {
            class LicensingService {
                canReserve(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/CanReserve",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getGenerateUrl(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/GetGenerateUrl",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getLicenseKey(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/GetLicenseKey",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getRecentEvent(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/GetRecentEvent",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getReleaseURL(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/GetReleaseUrl",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getReserveURL(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/GetReserveURL",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                release(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/Release",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                reserve(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/Reserve",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                setLicenseKey(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/SetLicenseKey",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                updateLicenses(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Licensing/UpdateLicenses",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Licenses.LicensingService = LicensingService;
        })(Licenses = Services.Licenses || (Services.Licenses = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Mail;
        (function (Mail) {
            class MailService {
                deleteAll(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue/DeleteAll",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                deleteItem(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue/Delete/",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                resendAll(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue/RetryAll",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                resendItem(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue/Retry",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                testMailSettings(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/MailQueue/TestMailSettings",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Mail.MailService = MailService;
        })(Mail = Services.Mail || (Services.Mail = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceService {
                addUsers(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/AddUsers",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getMessage(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/GetMessage",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getStatus(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/GetStatus",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                removeUsers(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/RemoveUsers",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                schedule(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/Schedule",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                setMessage(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/SetMessage",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                start(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/Start",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                stop(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Maintenance/Stop",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Maintenance.MaintenanceService = MaintenanceService;
        })(Maintenance = Services.Maintenance || (Services.Maintenance = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Manage;
        (function (Manage) {
            class ModuleService {
                loadDefinitions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/modules/load",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Manage.ModuleService = ModuleService;
        })(Manage = Services.Manage || (Services.Manage = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Manage;
        (function (Manage) {
            var EntityTypes;
            (function (EntityTypes) {
                class ExplorerModelService {
                    getTree(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ExplorerModel/GetTree",
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                    deleteNode(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ExplorerModel/DeleteNode",
                            method: Jade.HttpVerb.DELETE,
                            data: data
                        }).sendRequest();
                    }
                    moveNode(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ExplorerModel/MoveNode",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                }
                EntityTypes.ExplorerModelService = ExplorerModelService;
            })(EntityTypes = Manage.EntityTypes || (Manage.EntityTypes = {}));
        })(Manage = Services.Manage || (Services.Manage = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Manage;
        (function (Manage) {
            var Process;
            (function (Process) {
                class ProcessNodeService {
                    addNode(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ProcessNode/Add",
                            method: Jade.HttpVerb.PUT,
                            data: data
                        }).sendRequest();
                    }
                    deleteNode(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ProcessNode/Delete",
                            method: Jade.HttpVerb.DELETE,
                            data: data
                        }).sendRequest();
                    }
                    moveNode(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/ProcessNode/Move",
                            method: Jade.HttpVerb.POST,
                            data: data
                        }).sendRequest();
                    }
                }
                Process.ProcessNodeService = ProcessNodeService;
            })(Process = Manage.Process || (Manage.Process = {}));
        })(Manage = Services.Manage || (Services.Manage = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Manage;
        (function (Manage) {
            var Process;
            (function (Process) {
                class ProcessService {
                    deleteProcess(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/Process/Delete",
                            method: Jade.HttpVerb.DELETE,
                            data: data
                        }).sendRequest();
                    }
                    getStageList(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/Process/GetStageList",
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                }
                Process.ProcessService = ProcessService;
            })(Process = Manage.Process || (Manage.Process = {}));
        })(Manage = Services.Manage || (Services.Manage = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Overview;
        (function (Overview) {
            class OverviewService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Overview",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Overview.OverviewService = OverviewService;
        })(Overview = Services.Overview || (Services.Overview = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Personalization;
        (function (Personalization) {
            class QuickAccessService {
                add(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/quickaccess/add",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/quickaccess/list",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                remove(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/quickaccess/remove",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            Personalization.QuickAccessService = QuickAccessService;
        })(Personalization = Services.Personalization || (Services.Personalization = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Personalization;
        (function (Personalization) {
            class RecentItemsService {
                add(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/recentitems/add",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/recentitems/list",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                remove(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/recentitems/remove",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            Personalization.RecentItemsService = RecentItemsService;
        })(Personalization = Services.Personalization || (Services.Personalization = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Plugins;
        (function (Plugins) {
            class PluginsService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Plugins",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Plugins.PluginsService = PluginsService;
        })(Plugins = Services.Plugins || (Services.Plugins = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Process;
        (function (Process) {
            class ProcessService {
                executeDecision(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Process/ExecuteDecision",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getKeys(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Process/GetKeys",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getProcesses(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Process/GetProcesses",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getStages(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Process/GetStages",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Process",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getStatusList(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Process/GetStatuses",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getTree(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Process/GetTree",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Process.ProcessService = ProcessService;
        })(Process = Services.Process || (Services.Process = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Process;
        (function (Process) {
            class ProcessStatusService {
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ProcessStatus/List",
                        contentType: Services.ContentType.JSON,
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Process.ProcessStatusService = ProcessStatusService;
        })(Process = Services.Process || (Services.Process = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Process;
        (function (Process) {
            class ProcessesService {
                deleteProcess(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Processes/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Processes",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Process.ProcessesService = ProcessesService;
        })(Process = Services.Process || (Services.Process = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Tags;
        (function (Tags) {
            class ProfileService {
                getRecentItems(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Profile/GetRecentItems",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getRecentViews(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Profile/GetRecentViews",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Tags.ProfileService = ProfileService;
        })(Tags = Services.Tags || (Services.Tags = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var RecycleBin;
        (function (RecycleBin) {
            class RecycleBinService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RecycleBin/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                empty(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RecycleBin/Empty",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RecycleBin",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                restore(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RecycleBin/Restore",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                sendTo(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/RecycleBin/Send",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            RecycleBin.RecycleBinService = RecycleBinService;
        })(RecycleBin = Services.RecycleBin || (Services.RecycleBin = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Reports;
        (function (Reports) {
            class ReportsService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Reports/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Reports",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Reports.ReportsService = ReportsService;
        })(Reports = Services.Reports || (Services.Reports = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Resources;
        (function (Resources) {
            let DuplicateFileMode;
            (function (DuplicateFileMode) {
                DuplicateFileMode[DuplicateFileMode["Fail"] = 0] = "Fail";
                DuplicateFileMode[DuplicateFileMode["Skip"] = 1] = "Skip";
                DuplicateFileMode[DuplicateFileMode["Replace"] = 2] = "Replace";
            })(DuplicateFileMode = Resources.DuplicateFileMode || (Resources.DuplicateFileMode = {}));
            class ResourcesService {
                addFiles(data) {
                    var _a, _b;
                    let addFilePromises = [];
                    data.files.forEach(file => {
                        addFilePromises.push(this.addFilePromise(data, data.folderId, file));
                    });
                    let onFileSaveSuccess = (_a = data.onFileSaveSuccess) !== null && _a !== void 0 ? _a : (() => { });
                    let onFileSaveFailure = (_b = data.onFileSaveFailure) !== null && _b !== void 0 ? _b : (() => { });
                    addFilePromises.forEach(promise => {
                        promise.then(e => onFileSaveSuccess(e.file), e => onFileSaveFailure(e.file));
                    });
                    Promise.allSettled(addFilePromises)
                        .then(this.addFileResultHandler(data));
                }
                addFile(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/AddFile",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                addPackage(data) {
                    data.folderId = Jade.Guid.isNullOrEmpty(data.folderId) ?
                        null : data.folderId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/AddPackage",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteResources(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/DeleteResources",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getFolderPath(data) {
                    data.folderId = Jade.Guid.isNullOrEmpty(data.folderId) ?
                        null : data.folderId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/GetFolderPath",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getIndex(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getTreeNodes(data) {
                    data.folderId = Jade.Guid.isNullOrEmpty(data.folderId) ?
                        null : data.folderId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/GetTreeNodes",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getPackage(data) {
                    data.folderId = Jade.Guid.isNullOrEmpty(data.folderId) ?
                        null : data.folderId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/GetPackage",
                        contentType: Services.ContentType.JSON,
                        method: Jade.HttpVerb.POST,
                        data: Services.ServicePipeline.bundleJsonData("args", data)
                    }).sendRequest();
                }
                loadTextFile(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/LoadTextFile",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                saveTextFile(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/SaveTextFile",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                moveResources(data) {
                    data.destinationId = Jade.Guid.isNullOrEmpty(data.destinationId) ?
                        null : data.destinationId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/MoveResources",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                addTextFile(data) {
                    data.folderId = Jade.Guid.isNullOrEmpty(data.folderId) ?
                        null : data.folderId;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Resources/AddTextFile",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                addFilePromise(data, folderId, file) {
                    return new Promise((resolve, reject) => {
                        var _a;
                        let uploadedFile = file;
                        this.addFile({
                            folderId: data.folderId,
                            uploadId: `${file.id}${file.extension}`,
                            fileMode: (_a = uploadedFile.fileMode) !== null && _a !== void 0 ? _a : 0,
                            file: file,
                            success: (e) => {
                                file.fileId = e.data.id;
                                resolve({
                                    file: file
                                });
                            },
                            error: (e) => {
                                var _a, _b;
                                var errors = e.xhr.responseJSON != null ?
                                    e.xhr.responseJSON : [];
                                var error = _.first(errors) || {};
                                e.errorHandled = true;
                                reject({
                                    code: (_a = error.code) !== null && _a !== void 0 ? _a : 0,
                                    message: (_b = error.message) !== null && _b !== void 0 ? _b : "Error",
                                    file: file
                                });
                            }
                        });
                    });
                }
                addFileResultHandler(data) {
                    return (results) => {
                        let fulfilled = results
                            .filter(result => result.status === "fulfilled")
                            .map(item => item.value.file);
                        let rejected = results
                            .filter(result => result.status === "rejected")
                            .map(item => item.reason);
                        let errors = rejected.filter(item => item.code !== 0);
                        let conflicts = rejected.filter(item => item.code === 0);
                        if (errors.length > 0 && data.onFileUploadErrors != null) {
                            data.onFileUploadErrors(errors);
                            return;
                        }
                        if (conflicts.length > 0 && data.onFileUploadConflicts != null) {
                            data.onFileUploadConflicts(conflicts);
                            return;
                        }
                        if (rejected.length > 0) {
                            data.error({
                                data: {
                                    conflicts: conflicts,
                                    errors: errors,
                                    succeeded: fulfilled
                                },
                                xhr: null
                            });
                            return;
                        }
                        data.success({
                            data: {
                                ids: fulfilled.map(item => item.fileId)
                            },
                            xhr: null
                        });
                    };
                }
            }
            Resources.ResourcesService = ResourcesService;
        })(Resources = Services.Resources || (Services.Resources = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Rules;
        (function (Rules) {
            class RuleService {
                getReferences(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rule/GetReferences",
                        method: Jade.HttpVerb.POST,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
                getAuditContent(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rule/GetAuditContent",
                        method: Jade.HttpVerb.GET,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
                getAuditHistory(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rule/GetAuditHistory",
                        method: Jade.HttpVerb.GET,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
            }
            Rules.RuleService = RuleService;
        })(Rules = Services.Rules || (Services.Rules = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Rules;
        (function (Rules) {
            class RulesService {
                addPackage(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/AddPackage",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteRuleScript(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/DeleteRuleScript",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                executeScriptById(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Rule/ExecuteByScriptId",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                executeScriptByName(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Rule/ExecuteByScriptName",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                formatRuleScript(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/FormatRuleScript",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getAutoCompleteFiles(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Rules/GetAutoCompleteFiles",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getPackage(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/GetPackage",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadRuleScript(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/GetRuleScriptInfo",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                saveRuleScript(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Rules/SaveRuleScript",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Rules.RulesService = RulesService;
        })(Rules = Services.Rules || (Services.Rules = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Rules;
        (function (Rules) {
            class RulesTagsService {
                addScriptTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/AddScriptTags",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                changeTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/ChangeTags",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/DeleteTags",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/GetTags",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                removeScriptTags(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/RemoveScriptTags",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                validateExpression(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/RulesTags/ValidateExpression",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Rules.RulesTagsService = RulesTagsService;
        })(Rules = Services.Rules || (Services.Rules = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Search;
        (function (Search) {
            class SearchService {
                query(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/Search/Query",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Search.SearchService = SearchService;
        })(Search = Services.Search || (Services.Search = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Security;
        (function (Security) {
            class ActiveDirectoryService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ActiveDirectory/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
            }
            Security.ActiveDirectoryService = ActiveDirectoryService;
        })(Security = Services.Security || (Services.Security = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Security;
        (function (Security) {
            class GroupService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Groups/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Groups",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Security.GroupService = GroupService;
        })(Security = Services.Security || (Services.Security = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Security;
        (function (Security) {
            class IdentityService {
                query(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Identity/Query",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Security.IdentityService = IdentityService;
        })(Security = Services.Security || (Services.Security = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Security;
        (function (Security) {
            class UserService {
                bulkEdit(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Users/BulkEdit",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Users/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getLoginData(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Users/GetLoginData",
                        method: Jade.HttpVerb.POST,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Users",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Security.UserService = UserService;
        })(Security = Services.Security || (Services.Security = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Settings;
        (function (Settings) {
            class SettingsService {
                clearCache(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/settings/clearcache",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                exportConfig(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/settings/exportconfig",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                importConfig(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/settings/importconfig",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/settings",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Settings.SettingsService = SettingsService;
        })(Settings = Services.Settings || (Services.Settings = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var System;
        (function (System) {
            class IconService {
                search(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/IconBrowser/Query",
                        data: _.extend({
                            take: 10,
                            skip: 0,
                            page: 1,
                            pageSize: 10
                        }, data)
                    }).sendRequest();
                }
            }
            System.IconService = IconService;
        })(System = Services.System || (Services.System = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariablesService {
                deleteVariables(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SystemVariables/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/SystemVariables",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            SystemVariables.SystemVariablesService = SystemVariablesService;
        })(SystemVariables = Services.SystemVariables || (Services.SystemVariables = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Tags;
        (function (Tags) {
            class ExpressionService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Expressions/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                getFolderExpressions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Expressions/GetFolderExpressions",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/expressions",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                setFolderExpressions(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Expressions/SetFolderExpressions",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Tags.ExpressionService = ExpressionService;
        })(Tags = Services.Tags || (Services.Tags = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Tags;
        (function (Tags) {
            class TagService {
                delete(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Tags/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/manage/tags",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Tags.TagService = TagService;
        })(Tags = Services.Tags || (Services.Tags = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Themes;
        (function (Themes) {
            let IThemeColorServiceError;
            (function (IThemeColorServiceError) {
                IThemeColorServiceError[IThemeColorServiceError["InvalidId"] = 0] = "InvalidId";
                IThemeColorServiceError[IThemeColorServiceError["InvalidName"] = 1] = "InvalidName";
                IThemeColorServiceError[IThemeColorServiceError["InvalidCategory"] = 2] = "InvalidCategory";
                IThemeColorServiceError[IThemeColorServiceError["InvalidDescription"] = 3] = "InvalidDescription";
                IThemeColorServiceError[IThemeColorServiceError["ColorNotFound"] = 4] = "ColorNotFound";
            })(IThemeColorServiceError = Themes.IThemeColorServiceError || (Themes.IThemeColorServiceError = {}));
            class ThemeColorService {
                addCustomColor(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/AddCustomColor",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).addSuccessTask((e) => {
                        PDJS.Shared.Themes.Theme.refreshColors();
                    }).sendRequest();
                }
                deleteCustomColor(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/DeleteCustomColor",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).addSuccessTask((e) => {
                        PDJS.Shared.Themes.Theme.refreshColors();
                    }).sendRequest();
                }
                importColors(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/ImportColors",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).addSuccessTask((e) => {
                        PDJS.Shared.Themes.Theme.refreshColors();
                    }).sendRequest();
                }
                listCustomColors(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/ListCustomColors",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                loadCustomColor(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/LoadCustomColor",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                saveCustomColor(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ThemeColor/SaveCustomColor",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).addSuccessTask((e) => {
                        PDJS.Shared.Themes.Theme.refreshColors();
                    }).sendRequest();
                }
            }
            Themes.ThemeColorService = ThemeColorService;
        })(Themes = Services.Themes || (Services.Themes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Themes;
        (function (Themes) {
            let IThemeServiceError;
            (function (IThemeServiceError) {
                IThemeServiceError[IThemeServiceError["InvalidName"] = 0] = "InvalidName";
            })(IThemeServiceError = Themes.IThemeServiceError || (Themes.IThemeServiceError = {}));
            let ThemeScope;
            (function (ThemeScope) {
                ThemeScope[ThemeScope["Hub"] = 0] = "Hub";
                ThemeScope[ThemeScope["Manage"] = 1] = "Manage";
                ThemeScope[ThemeScope["Canvas"] = 2] = "Canvas";
                ThemeScope[ThemeScope["Designer"] = 3] = "Designer";
            })(ThemeScope = Themes.ThemeScope || (Themes.ThemeScope = {}));
            class ThemeService {
                copyTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/CopyTheme",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                deleteTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/DeleteTheme",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                enableTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/EnableTheme",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getColors(data) {
                    let themeColorsKey = "theme-colors";
                    let themeColors = sessionStorage.getItem(themeColorsKey);
                    let themeColorsCached = themeColors != null;
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/GetColors",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).addBeforeSendTask((pipeline) => {
                        if (data.clearCache) {
                            return;
                        }
                        if (themeColorsCached) {
                            try {
                                pipeline.response.data = JSON.parse(themeColors);
                                pipeline.abortRequestWithSuccess();
                            }
                            catch (ex) {
                                pipeline.abortRequestWithError();
                            }
                        }
                    }).addSuccessTask((pipeline) => {
                        if (!themeColorsCached || data.clearCache === true) {
                            try {
                                sessionStorage.setItem(themeColorsKey, JSON.stringify(pipeline.response.data));
                            }
                            catch (ex) {
                                console.log(ex);
                            }
                        }
                    }).sendRequest();
                }
                getCurrentTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Theme/GetCurrentTheme",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                getThemeDesignerCss(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Theme/GetThemeDesignerCss",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                importTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/ImportTheme",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Theme/List",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                resetTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/ResetTheme",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                switchTheme(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Theme/SwitchTheme",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                updateColors(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Theme/UpdateColors",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Themes.ThemeService = ThemeService;
        })(Themes = Services.Themes || (Services.Themes = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Utilities;
        (function (Utilities) {
            let DuplicateFileMode;
            (function (DuplicateFileMode) {
                DuplicateFileMode[DuplicateFileMode["Fail"] = 0] = "Fail";
                DuplicateFileMode[DuplicateFileMode["Skip"] = 1] = "Skip";
                DuplicateFileMode[DuplicateFileMode["Replace"] = 2] = "Replace";
            })(DuplicateFileMode = Utilities.DuplicateFileMode || (Utilities.DuplicateFileMode = {}));
            class TaskService {
                taskPoll(data) {
                    let url = data.url;
                    delete data.url;
                    Services.ServicePipeline.createRequest({
                        url: url,
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                taskNotify(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/Task/Notify",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Utilities.TaskService = TaskService;
        })(Utilities = Services.Utilities || (Services.Utilities = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            class ViewFilterService {
                addInline(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/ViewFilter/AddInline",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                clearInline(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/ViewFilter/ClearInline",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                load(data) {
                    Services.ServicePipeline.createRequest({
                        url: `~/Hub/ViewFilter/Load?viewStateId=${data.viewStateId}`,
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                removeInline(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Hub/ViewFilter/RemoveInline",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                save(data) {
                    Services.ServicePipeline.createRequest({
                        url: `~/Hub/ViewFilter/Save?viewStateId=${data.viewStateId}`,
                        method: Jade.HttpVerb.POST,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
                validate(data) {
                    Services.ServicePipeline.createRequest({
                        url: `~/Hub/ViewFilter/Validate?viewStateId=${data.viewStateId}`,
                        method: Jade.HttpVerb.POST,
                        contentType: Services.ContentType.JSON,
                        data: data
                    }).sendRequest();
                }
            }
            Views.ViewFilterService = ViewFilterService;
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            class ViewPublisherService {
                deleteView(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ViewPublisher/Delete",
                        method: Jade.HttpVerb.DELETE,
                        data: data
                    }).sendRequest();
                }
                duplicateView(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ViewPublisher/Duplicate",
                        method: Jade.HttpVerb.PUT,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ViewPublisher/Index",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                reset(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ViewPublisher/Reset",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Views.ViewPublisherService = ViewPublisherService;
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            let BuiltInViews;
            (function (BuiltInViews) {
                BuiltInViews["APP_SETTINGS"] = "appSettings";
                BuiltInViews["BUILTIN_VIEWS"] = "builtInViews";
                BuiltInViews["DATA_LOADER_JOBS"] = "dataLoaderJobs";
                BuiltInViews["DOCUMENT_TYPES"] = "docTypes";
                BuiltInViews["DOCUMENT_TYPE_ASSIGNMENT"] = "docTypeAssignment";
                BuiltInViews["DOCUMENT_TYPE_SELECTION"] = "docTypeSelection";
                BuiltInViews["ENTITY_SECURITY"] = "entitySecurity";
                BuiltInViews["ENTITY_TYPE_SECURITY"] = "entTypeSecurity";
                BuiltInViews["ENTITY_TYPE_SELECTION"] = "entityTypeSelection";
                BuiltInViews["ENTITY_TYPES"] = "entityTypes";
                BuiltInViews["EVENT_LOG"] = "eventLog";
                BuiltInViews["EXPRESSION_SELECTION"] = "expressionSelection";
                BuiltInViews["EXPRESSIONS"] = "expressions";
                BuiltInViews["EXTENSION_COLUMNS"] = "extensionColumns";
                BuiltInViews["EXTENSIONS"] = "extensions";
                BuiltInViews["EXTENSIONS_ALL"] = "extensionsAll";
                BuiltInViews["FORM_FIELD_SELECTION"] = "rormFieldSelection";
                BuiltInViews["GLOBAL_SEARCH"] = "entitySearch";
                BuiltInViews["GROUP_MEMBERS"] = "groupMembers";
                BuiltInViews["GROUP_USERS"] = "groupUsers";
                BuiltInViews["GROUPS"] = "groups";
                BuiltInViews["IDENTITY_SELECTION"] = "identitySearch";
                BuiltInViews["LICENSES"] = "licenses";
                BuiltInViews["MAIL_QUEUE"] = "mailQueue";
                BuiltInViews["PARENT_SELECTION"] = "parentSelection";
                BuiltInViews["PLUGINS"] = "plugins";
                BuiltInViews["PROCESSES"] = "processes";
                BuiltInViews["RECYCLE_BIN"] = "recycleBin";
                BuiltInViews["REPORTS"] = "reports";
                BuiltInViews["RESOURCES"] = "resources";
                BuiltInViews["RULES"] = "ruleScripts";
                BuiltInViews["RULE_SELECTION"] = "ruleScriptSelection";
                BuiltInViews["RULE_SCRIPT_HISTORY"] = "ruleScriptHistory";
                BuiltInViews["RULE_SCRIPT_TAG_SELECTION"] = "ruleScriptTagSelection";
                BuiltInViews["RULE_SCRIPT_TAGS"] = "ruleScriptTags";
                BuiltInViews["SEARCH_GROUP_COLUMN_SELECTION"] = "searchColumnSelection";
                BuiltInViews["SEARCH_GROUP_ITEMS"] = "searchGroupItems";
                BuiltInViews["SEARCH_GROUPS"] = "searchGroups";
                BuiltInViews["SELECTION_LISTS"] = "selectionLists";
                BuiltInViews["SELECTION_LISTS_ALL"] = "selectionListsAll";
                BuiltInViews["SYSTEM_VARIABLES"] = "variables";
                BuiltInViews["SYSTEM_VARIABLE_SELECTION"] = "variableSelection";
                BuiltInViews["TAG_SELECTION"] = "tagSelection";
                BuiltInViews["TAGS"] = "tags";
                BuiltInViews["USER_GROUPS"] = "userGroups";
                BuiltInViews["USERS"] = "users";
                BuiltInViews["VIEW_PUBLISHER"] = "viewPublisher";
            })(BuiltInViews = Views.BuiltInViews || (Views.BuiltInViews = {}));
            class ViewService {
                commitView(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/View/Commit",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
                getViewStateId(data) {
                    this.getViewStateIds({
                        success: (e) => {
                            if (ViewService.cachedViewStateIds[data.viewCustomId] != null) {
                                data.success(new Services.ServiceResponseOf({
                                    xhr: e.xhr,
                                    data: {
                                        viewStateId: ViewService.cachedViewStateIds[data.viewCustomId]
                                    },
                                    statusText: e.statusText
                                }));
                            }
                            else {
                                if (_.isFunction(data.error)) {
                                    data.error(new Services.ServiceResponse({
                                        xhr: e.xhr,
                                        error: e.error,
                                        statusText: e.statusText
                                    }));
                                }
                            }
                        },
                        error: data.error
                    });
                }
                getViewStateIds(data = {}) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Shared/View/GetViewStateIds",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).addBeforeSendTask((pipeline) => {
                        let isCachedPopulated = ViewService.cachedViewStateIds != null;
                        if (isCachedPopulated) {
                            pipeline.response.data = ViewService.cachedViewStateIds;
                            pipeline.abortRequestWithSuccess();
                        }
                    }).addSuccessTask((pipeline) => {
                        let isCachedPopulated = ViewService.cachedViewStateIds != null;
                        if (!isCachedPopulated) {
                            ViewService.cachedViewStateIds = pipeline.response.data;
                        }
                    }).sendRequest();
                }
                getViewState(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/View/GetViewState",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                setViewState(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/View/SetViewState",
                        method: Jade.HttpVerb.POST,
                        data: data
                    }).sendRequest();
                }
            }
            Views.ViewService = ViewService;
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            class ViewerService {
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/ViewViewer",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
            }
            Views.ViewerService = ViewerService;
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            var BuiltIn;
            (function (BuiltIn) {
                class BuiltInService {
                    index(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/BuiltInViews",
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                }
                BuiltIn.BuiltInService = BuiltInService;
            })(BuiltIn = Views.BuiltIn || (Views.BuiltIn = {}));
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Services;
    (function (Services) {
        var Views;
        (function (Views) {
            var Insights;
            (function (Insights) {
                class InsightsService {
                    index(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/Insights",
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                }
                Insights.InsightsService = InsightsService;
            })(Insights = Views.Insights || (Views.Insights = {}));
        })(Views = Services.Views || (Services.Views = {}));
    })(Services = PDJS.Services || (PDJS.Services = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class BrandAndVersion extends Jade.UI.Control {
            constructor(options = {}) {
                super(options);
            }
            get imgNode() {
                return this.node.find("img");
            }
            template() {
                return `
                <div style="text-align:center;line-height:1.5;">
                    <img src="${PDJS.System.Environment.getProductLogoPath()}" style="width: 125px;"/><br/>
                    <span style="color: var(--visiv-theme-base-1-text-color);">version: ${PDJS.System.Settings.current.applicationVersion}</span>
                </div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.subscriptions.add(PDJS.Shared.Themes.EventsHub.setThemeSubscribe(() => {
                    this.updateLogo();
                }));
            }
            updateLogo() {
                this.imgNode.attr("src", PDJS.System.Environment.getProductLogoPath());
            }
        }
        Shared.BrandAndVersion = BrandAndVersion;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class DataTags {
            static containsTags(text) {
                return (/\[\[[^\[\]]+\]\]/g).test(text);
            }
            static format(text) {
                if (!_.isString(text)) {
                    return text;
                }
                let result = text.replace(/(\[\[)([^\[\]]+)(\]\])/gi, (match, $1, $2, $3) => {
                    return `<span><span style="color:red;">${$1}</span><span style="color:blue;">${$2}</span><span style="color:red;">${$3}</span>`;
                });
                result = result.split("\n").join("<br/>");
                result = result.split(" ").join("&nbsp;");
                return result;
            }
        }
        Shared.DataTags = DataTags;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class DateFormat {
            static isValid(value, format) {
                let result = true;
                let regex = this.getFormatRegEx(format);
                if (!Jade.String.isNullOrWhiteSpace(value)) {
                    result = regex.test(value);
                }
                return result;
            }
            static getFormatRegEx(format) {
                switch (format) {
                    case "MM/DD/YYYY":
                        return /^((0|1)?\d{1})\/((0|1|2|3)?\d{1})\/((19|20)\d{2})$/g;
                }
            }
        }
        Shared.DateFormat = DateFormat;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class Downloader {
            static downloadWithProgress(args) {
                let blob;
                let request = new XMLHttpRequest();
                let url = this.getUrl(args.url, args.params);
                let toastrNode = PDJS.Shared.MessageStack
                    .instance.info(`Preparing file for download... please wait.`, {
                    timeOut: 0
                });
                let toastIcon = toastrNode.find(".toast-icon");
                toastIcon.empty();
                toastIcon.html(PDJS.Shared.Spinner.toHtml({
                    size: 28
                }));
                request.open('GET', url, true);
                request.responseType = 'arraybuffer';
                request.onload = function (e) {
                    blob = new Blob([this.response]);
                };
                request.onprogress = function (e) {
                    let percent = (e.loaded / e.total) * 100;
                    percent = isFinite(percent) ? percent : 100;
                    toastrNode.find(".toast-message")
                        .html(`Downloading file ${Math.ceil(percent)}%...`);
                };
                request.onloadend = function (e) {
                    let element = document.createElement("a");
                    document.body.appendChild(element);
                    args.url = window.URL.createObjectURL(blob);
                    element.href = url;
                    element.download = args.name || "file";
                    element.click();
                    window.URL.revokeObjectURL(url);
                    toastr.clear(toastrNode);
                };
                request.send();
            }
            static download(args) {
                let frame = this.getFrame(args.iframeId);
                if (frame.length > 0) {
                    frame.prop("src", this.getUrl(args.url, _.extend(args.params, {
                        uid: Jade.Guid.new(),
                        "iframe-request": true
                    })));
                }
            }
            ;
            static getFrame(iframeId) {
                iframeId = iframeId || "-pd-downloads";
                var frame = `<iframe id="${iframeId}" style="display:none;"></iframe>`;
                var frameNode = $(`#${iframeId}`);
                if (frameNode.length === 0) {
                    frameNode = $(frame);
                    frameNode.appendTo("body");
                }
                ;
                return frameNode;
            }
            ;
            static getUrl(url, params) {
                return Jade.Path.resolve(url, params);
            }
        }
        Shared.Downloader = Downloader;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class IcoFont {
            static convertPathToFont(url) {
                url = url === null || url === void 0 ? void 0 : url.toLowerCase();
                let name = Jade.Path.getFileNameWithoutExtension(url);
                let size = Jade.Path.getFileExtension(name).replace(".", "");
                if (!Jade.String.isNullOrWhiteSpace(size)) {
                    name = Jade.Path.getFileNameWithoutExtension(name);
                    size = size;
                }
                else {
                    size = "12px";
                }
                return `<i class="icofont-${name}" style="font-size:${size};"></i>`;
            }
            static isFontPath(url) {
                var _a;
                return !Jade.String.isNullOrWhiteSpace(url)
                    && ((_a = Jade.Path.getFileExtension(url)) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == ".font";
            }
        }
        Shared.IcoFont = IcoFont;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class MessageStack {
            constructor() {
            }
            get defaults() {
                return {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-bottom-right",
                    "preventDuplicates": true,
                    "onclick": null,
                    "showDuration": 300,
                    "hideDuration": 1000,
                    "timeOut": 5000,
                    "extendedTimeOut": 1500,
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                };
            }
            static get instance() {
                if (this.m_instance == null) {
                    this.m_instance = new MessageStack();
                }
                return this.m_instance;
            }
            error(message, options) {
                return this.configureToastr(() => {
                    return toastr.error(message);
                }, options, "close-circled");
            }
            warning(message, options) {
                return this.configureToastr(() => {
                    return toastr.warning(message);
                }, options, "warning");
            }
            success(message, options) {
                return this.configureToastr(() => {
                    return toastr.success(message);
                }, options, "check-circled");
            }
            info(message, options) {
                return this.configureToastr(() => {
                    return toastr.info(message);
                }, options, "info-circle");
            }
            exception(message, options) {
                return this.error(message, options);
            }
            configureToastr(invokeFn, options, cssClass) {
                let result = null;
                toastr.options =
                    _.extend(this.defaults, options || {});
                result = invokeFn();
                this.addIcon(result, cssClass);
                toastr.options = this.defaults;
                return result;
            }
            addIcon(toastNode, cssClass) {
                if (toastNode == null) {
                    return;
                }
                let toastMessage = toastNode.find(".toast-message");
                toastNode.css({
                    backgroundImage: `none`,
                    display: "grid",
                    gridTemplateColumns: "max-content auto",
                    gridGap: "10px",
                    paddingLeft: "15px",
                    alignItems: "center"
                });
                $(`<div class="toast-icon" style="font-size:28px;"><i class="icofont-${cssClass}"></i></div>`)
                    .insertBefore(toastMessage);
            }
        }
        Shared.MessageStack = MessageStack;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class Numeric {
            static isInt32(value) {
                let integer = this.toBigInt(value);
                let min = this.toBigInt("-2147483648");
                let max = this.toBigInt("2147483647");
                return integer != null && integer >= min && integer <= max;
            }
            static isInt64(value) {
                let integer = this.toBigInt(value);
                let min = this.toBigInt("-9223372036854775808");
                let max = this.toBigInt("9223372036854775807");
                return integer != null && integer >= min && integer <= max;
            }
            static isDecimal(value) {
                let regex = /^-*(\d*\.)?\d+$/gim;
                return regex.test(value);
            }
            static toBigInt(value) {
                let result = null;
                try {
                    result = BigInt(value);
                }
                catch (ex) {
                    result = null;
                }
                return result;
            }
        }
        Shared.Numeric = Numeric;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class ScrollIntoView {
            static scroll(parent, child) {
                const parentBounding = parent.getBoundingClientRect();
                const clientBounding = child.getBoundingClientRect();
                const parentBottom = parentBounding.bottom;
                const parentTop = parentBounding.top;
                const clientBottom = clientBounding.bottom;
                const clientTop = clientBounding.top;
                if (parentTop >= clientTop) {
                    this.scrollTo(parent, -(parentTop - clientTop), 300);
                    return;
                }
                if (clientBottom > parentBottom) {
                    this.scrollTo(parent, clientBottom - parentBottom, 300);
                    return;
                }
            }
            static scrollTo(element, to, duration) {
                let start = element.scrollTop;
                let currentTime = 0;
                let increment = 20;
                let animateScroll = () => {
                    currentTime += increment;
                    let val = this.easeInOutQuad(currentTime, start, to, duration);
                    element.scrollTop = val;
                    if (currentTime < duration) {
                        setTimeout(animateScroll, increment);
                    }
                };
                animateScroll();
            }
            static easeInOutQuad(time, startPos, endPos, duration) {
                time /= duration / 2;
                if (time < 1)
                    return (endPos / 2) * time * time + startPos;
                time--;
                return (-endPos / 2) * (time * (time - 2) - 1) + startPos;
            }
        }
        Shared.ScrollIntoView = ScrollIntoView;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class Spinner {
            static toHtml(options = {}) {
                options = _.extend({
                    size: 16,
                    color: "inherit",
                    text: null,
                    strokeWidth: 5
                }, options);
                return `<div class="-pdjs-svg-spinner" style="color:${options.color};height:${options.size}px;">
						<div style="width:${options.size}px;">
							<svg viewBox="25 25 50 50" style="width:${options.size}px;">
								<circle cx="50"	cy="50" r="20" fill="none" stroke="currentColor" stroke-width="${options.strokeWidth}px" />
							</svg>
						</div>
						<div style="padding-left:${options.text == null ? 0 : 5}px;font-size:${options.size}px;">
							${options.text || ""}
						</div>
					</div>`;
            }
        }
        Shared.Spinner = Spinner;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class PopOver {
            static menu(handle, content, options) {
                return Tipped.create(handle, content, this.extendOptions({
                    skin: "themed",
                    detach: false,
                    fadeOut: 100,
                    hideAfter: 500,
                    hideDelay: 500,
                    hideOn: "click-outside",
                    hideOthers: true,
                    padding: false,
                    position: "bottomleft",
                    radius: false,
                    shadow: false,
                    stem: false,
                    showDelay: 0,
                    showOn: false
                }, options));
            }
            static tooltip(handle, content, options) {
                return Tipped.create(handle, content, this.extendOptions({
                    skin: "white",
                    hideOn: false,
                    padding: true
                }, options));
            }
            static tooltipMenu(handle, content, options) {
                return this.tooltip(handle, this.formatTooltipContent(content), this.extendOptions({
                    hideOn: false,
                    padding: true
                }, options));
            }
            static tooltipRibbon(handle, content, options) {
                return this.tooltip(handle, this.formatTooltipContent(content), this.extendOptions({
                    hideOn: false,
                    padding: true,
                    offset: { y: 5 },
                    position: "bottommiddle",
                    stem: false,
                    hideAfter: 10,
                    hideDelay: 10,
                    target: handle.closest(".-jadejs-ribbonbar-group").get(0)
                }, options));
            }
            static validation(handle, content, options) {
                return Tipped.create(handle, content, this.extendOptions({
                    skin: "validation-error",
                    padding: true
                }, options));
            }
            static findElement(handle) {
                return Tipped.findElement(handle);
            }
            static get(handle) {
                return Tipped.get(handle);
            }
            static hide(handle) {
                Tipped.hide(handle);
            }
            static refresh(handle) {
                return Tipped.refresh(handle);
            }
            static remove(handle) {
                Tipped.remove(handle);
            }
            static show(handle) {
                Tipped.show(handle);
            }
            static defaultOptions() {
                return {
                    cache: false,
                    hideAfter: 200,
                    hideDelay: 0,
                    hideOn: "mouseleave",
                    shadow: false,
                    showDelay: 750,
                    showOn: "mouseenter",
                    maxWidth: 300,
                    padding: false
                };
            }
            static extendOptions(item1, item2 = {}, item3 = {}) {
                return _.merge({}, this.defaultOptions(), item1, item2, item3);
            }
            static formatTooltipContent(content) {
                return `<div class="-pdjs-tooltip-content">
                        <div>${content.title}</div>
                        <div>${content.description}</div>
                    </div>`;
            }
        }
        Shared.PopOver = PopOver;
        PDJS.Application.onStart(() => {
            $.extend(Tipped.Skins, {
                "white": {
                    radius: false
                },
                maxWidth: "300",
                hideAfter: 500,
                hideDelay: 0,
                showDelay: 500
            });
            $.extend(Tipped.Skins, {
                "validation-error": {
                    radius: false,
                    position: {
                        target: "topleft",
                        tooltip: "bottomleft"
                    },
                    maxWidth: "300",
                    hideAfter: 500,
                    hideDelay: 0,
                    showDelay: 500
                }
            });
            $.extend(Tipped.Skins, {
                "themed": {
                    radius: false,
                    position: {
                        target: "topleft",
                        tooltip: "bottomleft"
                    },
                },
                maxWidth: "300",
                hideAfter: 500,
                hideDelay: 0,
                showDelay: 500
            });
        });
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class Error {
            constructor(error) {
                this.parse(error);
            }
            get code() {
                return this.m_code;
            }
            set code(value) {
                this.m_code = value;
            }
            get key() {
                return this.m_key;
            }
            set key(value) {
                this.m_key = value;
            }
            get message() {
                return this.m_message;
            }
            set message(value) {
                this.m_message = value;
            }
            get tags() {
                return this.m_tags;
            }
            set tags(value) {
                this.m_tags = value;
            }
            toJSON() {
                return {
                    code: this.code,
                    key: this.key,
                    message: this.message,
                    tags: this.tags
                };
            }
            parse(error) {
                if (this.isJSON(error)) {
                    error = this.convertJSON(error);
                }
                if (this.isObject(error)) {
                    this.convertObject(error);
                }
                if (this.isString(error)) {
                    this.convertString(error);
                }
            }
            convertJSON(error) {
                return this.parseJSON(error);
            }
            convertObject(error) {
                this.code = error.code || -1;
                this.message = error.message;
                this.key = error.key;
                this.tags = error.tags;
            }
            convertString(value) {
                this.code = -1;
                this.message = value;
            }
            isJSON(value) {
                return this.parseJSON(value) != null;
            }
            parseJSON(value) {
                let result = null;
                try {
                    result = JSON.parse(value);
                }
                catch (ex) { }
                return result;
            }
            isObject(value) {
                return _.isPlainObject(value);
            }
            isString(value) {
                return _.isString(value);
            }
        }
        Shared.Error = Error;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class ErrorFactory {
            constructor() {
            }
            static convert(error) {
                let result = [];
                if (this.isXHR(error)) {
                    error = this.convertXHR(error);
                }
                if (this.isArray(error)) {
                    result = this.convertArray(error);
                }
                if (this.isObject(error) || this.isString(error)) {
                    result = this.convertArray([error]);
                }
                return result || [new Shared.Error("Unhandled Error")];
            }
            static first(error) {
                return _.first(this.convert(error));
            }
            static convertArray(values) {
                let result = [];
                values.forEach(value => {
                    result.push(new Shared.Error(value));
                });
                return result;
            }
            static convertJSON(value) {
                let result = null;
                try {
                    result = JSON.parse(value);
                }
                catch (ex) { }
                return result;
            }
            static convertXHR(xhr) {
                let message = null;
                let header = xhr
                    .getResponseHeader("error-message");
                if (header != null) {
                    message = header;
                }
                if (message == null) {
                    message = xhr.responseText;
                }
                if (message == null) {
                    return;
                }
                return this.isJSON(message) ?
                    this.convertJSON(xhr.responseText) : message;
            }
            static isArray(value) {
                return _.isArray(value);
            }
            static isJSON(value) {
                return this.convertJSON(value) != null;
            }
            static isObject(value) {
                return _.isPlainObject(value);
            }
            static isString(value) {
                return _.isString(value);
            }
            static isXHR(value) {
                return _.isObjectLike(value) &&
                    _.isFunction(value.getAllResponseHeaders) &&
                    _.isFunction(value.getResponseHeader) &&
                    _.isString(value.responseText);
            }
        }
        Shared.ErrorFactory = ErrorFactory;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusDialog extends Jade.UI.Dialogs.Dialog {
            constructor(options) {
                super(options);
            }
            get alertMonitor() {
                return this.m_alertMonitor;
            }
            set alertMonitor(value) {
                this.m_alertMonitor = value;
            }
            get allowClose() {
                return this.state.get("allowClose", true);
            }
            get autoCloseOnSuccess() {
                return this.state.get("autoCloseOnSuccess", true);
            }
            get bar() {
                return this.m_bar;
            }
            set bar(value) {
                this.m_bar = value;
            }
            get cancelButtonNode() {
                return this.node.find("button[data-command=cancel]");
            }
            get closeButtonNode() {
                return this.node.find("button[data-command=close]");
            }
            get closeCallback() {
                return this.state.get("close", () => { });
            }
            get hasCloseCallback() {
                return this.state.get("close") != null;
            }
            get enableClose() {
                return this.state.get("enableClose", true);
            }
            get hasTaskCancelCallback() {
                return this.state.get("taskCancel") != null;
            }
            get hasTaskStartCallback() {
                return this.state.get("taskStart") != null;
            }
            get log() {
                return this.m_log;
            }
            set log(value) {
                this.m_log = value;
            }
            get marquee() {
                return this.m_marquee;
            }
            set marquee(value) {
                this.m_marquee = value;
            }
            get pollFrequency() {
                return this.state.get("pollFrequency", 1000);
            }
            get output() {
                return this.m_output;
            }
            set output(value) {
                this.m_output = value;
            }
            get statusMonitor() {
                return this.m_statusMonitor;
            }
            set statusMonitor(value) {
                this.m_statusMonitor = value;
            }
            get showDetail() {
                return this.state.get("showDetail", false);
            }
            get taskCompleteCallback() {
                return this.state.get("taskComplete", () => { });
            }
            get taskStartCallback() {
                return this.state.get("taskStart", () => { });
            }
            get taskSuccessCallback() {
                return this.state.get("taskSuccess", () => { });
            }
            get taskErrorCallback() {
                return this.state.get("taskError", () => { });
            }
            get toggle() {
                return this.m_copy;
            }
            set toggle(value) {
                this.m_copy = value;
            }
            complete(status, tags) {
                this.bar.update(100, status);
                this.marquee.updateStatus(status);
                this.taskCompleteCallback(this.createEventArgs());
                this.enableCloseButton(true);
            }
            enableCloseButton(enabled) {
                this.closeButtonNode.prop("disabled", !enabled);
                this.closeButtonNode.focus();
            }
            fatalError(message = null) {
                message = message || "Task was unexpectedly aborted.";
                this.bar.update(100, "error");
                this.marquee.update(message, "error");
                this.log.addMessage(Shared.ITaskStatusLevel.error, message);
                this.log.addMessage(Shared.ITaskStatusLevel.default, "Task aborted.");
                this.enableCloseButton(true);
            }
            template() {
                return super.template(`
                <div class="-pdjs-shared-task-status-dialog">
                    <div role="status-marquee"></div>
                    <div role="status-bar"></div>
                    <div role="status-log"></div>
                    <div role="deck">
                        <div role="deck-l">
                            <div></div>
                            <div></div>
                        </div>
                        <div role="deck-r">
                            <button 
                                class="-pdjs-dialog-button" 
                                data-command="close">
                                Close
                            </button>
                            <button 
                                class="-pdjs-dialog-button" 
                                data-command="cancel">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>`);
            }
            onActivate(e) {
                super.onActivate(e);
                this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.close();
                });
                this.closeButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.close();
                    this.closeCallback(this.createEventArgs());
                });
                this.enableCloseButton(this.enableClose);
                this.allowClose ?
                    this.closeButtonNode.show() :
                    this.closeButtonNode.hide();
                this.bar_init();
                this.log_init();
                this.marquee_init();
                this.deck_init();
                this.alertMonitor_init();
                this.statusMonitor_init();
            }
            onComplete(e) {
                super.onComplete(e);
                this.marquee.update("Starting task ...", "pending");
                this.log.addMessage(Shared.ITaskStatusLevel.default, "Starting task ...");
                this.allowClose ?
                    this.closeButtonNode.show() :
                    this.closeButtonNode.hide();
                this.showDetail ?
                    this.log.show() :
                    this.log.hide();
                this.hasTaskCancelCallback ?
                    this.cancelButtonNode.show() :
                    this.cancelButtonNode.hide();
                this.setDialogParameters();
                setTimeout(() => { this.start(); }, 1000);
            }
            alertMonitor_init() {
                this.alertMonitor = new Shared.TaskAlertMonitor();
            }
            bar_init() {
                this.bar = new Shared.TaskStatusBar({
                    insertAt: "div[role=status-bar]"
                });
                this.controls.add(this.bar);
            }
            createEventArgs() {
                return new Shared.TaskStatusDialogEventArgs({
                    alertMonitor: this.alertMonitor,
                    close: _.bind(this.close, this),
                    closeButton: this.closeButtonNode,
                    complete: _.bind(this.complete, this),
                    context: this.context,
                    fatalError: _.bind(this.fatalError, this),
                    log: this.log,
                    output: this.output,
                    statusMonitor: this.statusMonitor,
                    dialog: this
                });
            }
            deck_init() {
                let toggle = new Shared.TaskStatusLogToggle({
                    insertAt: "div[role=deck-l] > div:first-child",
                    toggled: this.showDetail,
                    toggle: (toggled) => {
                        toggled ?
                            this.log.show() :
                            this.log.hide();
                        this.setDialogParameters();
                    }
                });
                this.controls.add(toggle);
                let clipboard = new Shared.TaskStatusLogCopy({
                    insertAt: "div[role=deck-l] > div:last-child",
                    click: () => {
                        this.log.copyToClipboard();
                    }
                });
                this.controls.add(clipboard);
            }
            executeInParentContext(fn) {
                PDJS.Application.instance.contexts.revolveContext({
                    context: this.context.parent,
                    fn: () => {
                        fn();
                    }
                });
            }
            log_init() {
                this.log = new Shared.TaskStatusLog({
                    insertAt: "div[role=status-log]"
                });
                this.controls.add(this.log);
            }
            marquee_init() {
                this.marquee = new Shared.TaskStatusMarquee({
                    insertAt: "div[role=status-marquee]"
                });
                this.controls.add(this.marquee);
            }
            statusMonitor_init() {
                this.statusMonitor = new Shared.TaskStatusMonitor({
                    frequency: this.pollFrequency,
                    error: (e) => {
                        this.fatalError(e);
                        this.executeInParentContext(() => {
                            this.taskErrorCallback(this.createEventArgs());
                        });
                        this.complete("error", {});
                    },
                    success: (e) => {
                        let taskId = this.statusMonitor.taskId;
                        this.marquee.updateMessage(e.data.lastAction);
                        this.log.addMessages(e.data.messages);
                        this.bar.update(e.data.percentComplete);
                        this.output = e.data.tags;
                        if (e.data.alert != null) {
                            this.alertMonitor.handleAlert(taskId, e.data.alert);
                        }
                        if (e.data.complete && !e.data.failed) {
                            this.onTaskSuccess(e.data);
                        }
                        if (e.data.complete && e.data.failed) {
                            this.taskErrorCallback(this.createEventArgs());
                        }
                        if (e.data.complete) {
                            this.complete(e.data.failed ?
                                "error" : "success", e.data.tags);
                        }
                    }
                });
            }
            setDialogParameters() {
                let height = this.log.visible ?
                    250 : 104;
                let shouldRestore = !this.log.visible
                    && this.isMaximized;
                this.setWindowOptions({
                    height: height,
                    minHeight: height,
                    minWidth: 400,
                    resizable: this.log.visible,
                    width: this.contentNode.width(),
                });
                if (shouldRestore) {
                    this.restore();
                }
                this.center();
            }
            start() {
                if (!this.hasTaskStartCallback) {
                    this.fatalError("No task start was provided.");
                    return;
                }
                this.taskStartCallback(this.createEventArgs());
            }
            onTaskSuccess(e) {
                let eventArgs = this.createEventArgs();
                let hasErrorsOrWarnings = this.log.hasErrors() ||
                    this.log.hasWarnings();
                this.taskSuccessCallback(eventArgs);
                if (hasErrorsOrWarnings) {
                    if (!this.log.visible) {
                        this.log.show();
                        this.setDialogParameters();
                    }
                    return;
                }
                if (this.autoCloseOnSuccess && !this.log.visible) {
                    this.close();
                    this.closeCallback(eventArgs);
                }
            }
            static open(options) {
                return new TaskStatusDialog(options);
            }
        }
        Shared.TaskStatusDialog = TaskStatusDialog;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusDialogEventArgs extends PDJS.Core.Model {
            constructor(options) {
                super(options);
            }
            get alertMonitor() {
                return this.state.get("alertMonitor");
            }
            get closeButton() {
                return this.state.get("closeButton");
            }
            get closeCallback() {
                return this.state.get("close", () => { });
            }
            get completeCallback() {
                return this.state.get("complete", () => { });
            }
            get context() {
                return this.state.get("context");
            }
            get fatalErrorCallback() {
                return this.state.get("fatalError", () => { });
            }
            get hasErrors() {
                return this.log.hasErrors();
            }
            get hasWarnings() {
                return this.log.hasWarnings();
            }
            get log() {
                return this.state.get("log");
            }
            get output() {
                return this.state.get("output");
            }
            get statusMonitor() {
                return this.state.get("statusMonitor");
            }
            get window() {
                return this.state.get("window");
            }
            addDetailMessage(level, message, indent) {
                this.log.addMessage(level, message, indent);
            }
            abort(arg1 = null) {
                if (Jade.String.isNullOrWhiteSpace(arg1))
                    return;
                let message = arg1;
                if (arg1 instanceof PDJS.Services.ServiceResponse) {
                    message = arg1.xhr.responseJSON;
                    arg1.errorHandled = true;
                }
                let isArray = _.isArray(message);
                let isString = _.isString(message);
                let isObject = _.isObject(message);
                switch (true) {
                    case isArray:
                        _.each(message, (msg) => {
                            this.fatalErrorCallback(msg.message);
                        });
                        break;
                    case isString:
                        this.fatalErrorCallback(message);
                        break;
                    case isObject:
                        this.fatalErrorCallback(message.message);
                        break;
                    default:
                        this.fatalErrorCallback();
                        break;
                }
            }
            close(options) {
                this.closeCallback(options);
            }
            complete(message) {
                if (!Jade.String.isNullOrWhiteSpace(message)) {
                    this.log.addMessage(0, message);
                }
                this.completeCallback(message);
            }
            enableClose(enabled) {
                enabled ?
                    this.closeButton.removeAttr("disabled") :
                    this.closeButton.ttr("disabled", "disabled");
                this.closeButton.focus();
            }
            startPolling(e) {
                this.alertMonitor.registerAlertTypes(e.alerts);
                this.statusMonitor.poll(e.taskId, 0);
            }
        }
        Shared.TaskStatusDialogEventArgs = TaskStatusDialogEventArgs;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskAlertMonitor extends PDJS.Core.Model {
            constructor() {
                super({});
                this.m_register = {};
                this.m_taskService = new PDJS.Services.Utilities.TaskService();
            }
            get activeDialog() {
                return this.m_activeDialog;
            }
            set activeDialog(value) {
                this.m_activeDialog = value;
            }
            get register() {
                return this.m_register;
            }
            get taskService() {
                return this.m_taskService;
            }
            handleAlert(taskId, alert) {
                let isTaskAlerting = alert != null;
                let isDialogAlerting = this.activeDialog != null;
                if (!isTaskAlerting && isDialogAlerting) {
                    this.activeDialog.close();
                    this.activeDialog = null;
                }
                else if (isTaskAlerting && !isDialogAlerting) {
                    this.raiseAlert(taskId, alert);
                }
            }
            raiseAlert(taskId, alert) {
                let dialogType = this.register[alert.code];
                if (dialogType == null || this.activeDialog != null) {
                    return;
                }
                this.activeDialog = new dialogType({
                    alert: alert,
                    select: {
                        ok: (sender, e) => {
                            this.sendAlertResponse(taskId, e);
                            this.activeDialog = null;
                        }
                    }
                });
            }
            registerAlertTypes(alerts) {
                _.each(alerts, (value, key) => {
                    let type = Jade.Type.getType(value);
                    if (type != null) {
                        this.register[key] = type;
                    }
                });
            }
            sendAlertResponse(taskId, tags) {
                this.taskService.taskNotify({
                    reply: {
                        taskId: taskId,
                        tags: tags
                    }
                });
            }
        }
        Shared.TaskAlertMonitor = TaskAlertMonitor;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusBar extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get bar() {
                return this.m_bar;
            }
            set bar(value) {
                this.m_bar = value;
            }
            template() {
                return `<div role="bar"></div>`;
            }
            update(percent, status = "success") {
                this.bar.percent = percent < 1 ? 1 : percent;
                this.bar.backgroundColor =
                    status == "success" ? "var(--visiv-system-green-vibrant)" : "var(--visiv-system-red-vibrant)";
            }
            onActivate(e) {
                super.onActivate(e);
                this.progressBar_init();
            }
            progressBar_init() {
                this.bar = new PDJS.Shared.UI.Controls.ProgressBar({
                    backgroundColor: "#FFFFFF",
                    showMessage: true,
                    color: "var(--visiv-theme-base-1-back-color)",
                    height: "20px"
                });
                this.controls.add(this.bar);
            }
        }
        Shared.TaskStatusBar = TaskStatusBar;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        let ITaskStatusLevel;
        (function (ITaskStatusLevel) {
            ITaskStatusLevel[ITaskStatusLevel["default"] = 0] = "default";
            ITaskStatusLevel[ITaskStatusLevel["warning"] = 1] = "warning";
            ITaskStatusLevel[ITaskStatusLevel["error"] = 2] = "error";
        })(ITaskStatusLevel = Shared.ITaskStatusLevel || (Shared.ITaskStatusLevel = {}));
        class TaskStatusLog extends Jade.UI.Control {
            constructor(options) {
                super(options);
                this.m_messages = [];
                this.m_bulletPath = Jade.IconSet.get("pdjs").resolve("bullet.png", Jade.IconSetSizeSpecificDirectory.x16);
            }
            get visible() {
                return this.node.is(":visible");
            }
            get messages() {
                return this.m_messages;
            }
            addMessage(level, message, indent = 0) {
                let levels = { 0: "default", 1: "warning", 2: "error" };
                let content = $(`<div data-level="${levels[level] || "default"}">
                    <div><i class="icofont-simple-right"></i></div>
                    <div>${message != null ? message : ""}</div>
                </div>`);
                content.css({
                    margin: `0px 0px 0px ${indent == null ? 0 : indent}px`
                });
                this.node.append(content);
                this.node.get(0).scrollTop =
                    this.node.get(0).scrollHeight;
                this.messages.push({
                    level: level,
                    message: message
                });
            }
            addMessages(messages, indent = 0) {
                indent = indent == null ? 0 : indent;
                if (!_.isArray(messages) || messages.length <= 0) {
                    return;
                }
                messages.forEach(item => {
                    this.addMessage(item.level, item.message, indent);
                    _.isArray(item.subMessages) ?
                        this.addMessages(item.subMessages, indent + 15) : null;
                });
            }
            hide() {
                this.node.hide();
                this.node.parent().css({
                    paddingBottom: 0
                });
            }
            show() {
                this.node.show();
                this.node.parent().css({
                    paddingBottom: "10px"
                });
            }
            template() {
                return `<div role="log"></div>`;
            }
            copyToClipboard() {
                let text = this.getLogText();
                !navigator.clipboard ?
                    this.unsecuredCopyToClipboard(text) :
                    this.securedCopyToClipboard(text);
                PDJS.Shared.MessageStack.instance.info("Task log copied to the clipboard.");
            }
            hasWarnings() {
                return this.messages.filter((message) => {
                    return message.level == ITaskStatusLevel.warning;
                }).length > 0;
            }
            hasErrors() {
                return this.messages.filter((message) => {
                    return message.level == ITaskStatusLevel.error;
                }).length > 0;
            }
            getLogText() {
                let result = "";
                this.node.children("div").each((index, elem) => {
                    result += `${_.trim(elem.textContent)}\n`;
                });
                return result;
            }
            unsecuredCopyToClipboard(text) {
                let textArea = $("<textarea></textarea");
                textArea.val(text);
                this.node.append(textArea);
                textArea.focus();
                textArea.select();
                try {
                    document.execCommand('copy');
                }
                catch (err) {
                    console.error('Unable to copy to clipboard', err);
                }
                textArea.remove();
            }
            securedCopyToClipboard(text) {
                try {
                    navigator.clipboard.writeText(text);
                }
                catch (err) {
                    this.unsecuredCopyToClipboard(text);
                }
            }
        }
        Shared.TaskStatusLog = TaskStatusLog;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusLogCopy extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get clickCallback() {
                return this.state.get("click", () => { });
            }
            set clickCallback(value) {
                this.state.set("click", value);
            }
            get iconNode() {
                return this.node.children("i");
            }
            template() {
                return `<button role="clipboard">
                        <i class="icofont-copy"></i>
                    </button>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.clickCallback();
                });
                this.iconNode.attr("title", "Copy to Clipboard");
            }
        }
        Shared.TaskStatusLogCopy = TaskStatusLogCopy;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusLogToggle extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get toggled() {
                return this.state.get("toggled", false);
            }
            set toggled(value) {
                this.state.set("toggled", value);
            }
            get toggleCallback() {
                return this.state.get("toggle", () => { });
            }
            get iconNode() {
                return this.node.children("i");
            }
            template() {
                return `<button role="toggle" toggled="true">
                        <i class="icofont-down"></i>
                    </button>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.toggled = !this.toggled;
                    this.toggleIcon();
                    this.setToggledAttribute(this.toggled);
                    this.toggleCallback(this.toggled);
                });
            }
            onStateChanged() {
                super.onStateChanged();
                this.toggleIcon();
                this.setToggledAttribute(this.toggled);
            }
            toggleIcon() {
                this.iconNode.removeClass("icofont-simple-down");
                this.iconNode.removeClass("icofont-simple-up");
                this.toggled ?
                    this.iconNode.addClass("icofont-simple-up") :
                    this.iconNode.addClass("icofont-simple-down");
                let title = this.toggled ?
                    "Show less detail" :
                    "Show more detail";
                this.iconNode.attr("title", title);
            }
            setToggledAttribute(toggled) {
                toggled ?
                    this.node.attr("toggled", "true") :
                    this.node.attr("toggled", "false");
            }
        }
        Shared.TaskStatusLogToggle = TaskStatusLogToggle;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusMarquee extends Jade.UI.Control {
            constructor(options) {
                super(options);
            }
            get message() {
                return this.state.get("message", "");
            }
            set message(value) {
                this.state.get("message", value);
            }
            get messageNode() {
                return this.node.children("div:first-child");
            }
            get statusNode() {
                return this.node.children("div:last-child");
            }
            template() {
                return `<div role="marquee">
                        <div></div>
                        <div></div>
                    </div>`;
            }
            update(message, status) {
                this.updateMessage(message);
                this.updateStatus(status);
            }
            updateStatus(status) {
                let node = null;
                switch (status) {
                    case "error":
                        node = this.getIconTag("close-circled", "var(--visiv-system-red-vibrant)");
                        break;
                    case "pending":
                        node = PDJS.Shared.Spinner.toHtml({ size: 14 });
                        break;
                    case "success":
                        node = this.getIconTag("check-circled", "var(--visiv-system-green-vibrant)");
                        break;
                }
                this.statusNode.empty();
                if (node != null) {
                    this.statusNode.append(node);
                }
            }
            updateMessage(message) {
                this.messageNode.text(message);
                this.messageNode.attr("title", this.message);
            }
            getIconTag(name, color) {
                return `<i class="icofont-${name}" style="font-size:16px;color:${color};"><i/>`;
            }
        }
        Shared.TaskStatusMarquee = TaskStatusMarquee;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusMonitor extends PDJS.Core.Model {
            constructor(options) {
                super(options);
                this.m_taskService = new PDJS.Services.Utilities.TaskService();
            }
            get errorCallback() {
                return this.state.get("error", () => { });
            }
            get frequency() {
                return this.state.get("frequency", 0);
            }
            get pollUrl() {
                return this.state.get("pollUrl", "~/Shared/Task/Status");
            }
            get successCallback() {
                return this.state.get("success", () => { });
            }
            get taskId() {
                return this.state.get("taskId");
            }
            set taskId(value) {
                this.state.set("taskId", value);
            }
            get taskService() {
                return this.m_taskService;
            }
            poll(taskId, frequency = 0) {
                this.taskId = taskId;
                if (Jade.String.isNullOrWhiteSpace(this.pollUrl)) {
                    this.errorCallback("Unable to poll task.");
                    return;
                }
                setTimeout(() => {
                    this.taskService.taskPoll({
                        url: `${this.pollUrl}/${taskId}`,
                        success: _.bind(this.poll_onSuccess, this),
                        error: _.bind(this.poll_onError, this)
                    });
                }, frequency);
            }
            poll_onError(e) {
                let message = null;
                try {
                    message = e.xhr.responseJSON.message;
                }
                catch (ex) {
                    message = "Fatal error.";
                }
                this.errorCallback(message);
            }
            poll_onSuccess(e) {
                this.successCallback(e);
                if (!e.data.complete) {
                    this.poll(this.taskId, this.frequency);
                }
            }
        }
        Shared.TaskStatusMonitor = TaskStatusMonitor;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Ace;
        (function (Ace) {
            ;
            class AceEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", false);
                }
                get content() {
                    return this.state.get("content");
                }
                get ace() {
                    return this.m_editor;
                }
                get aceNode() {
                    return this.node.find("div[role=editor]");
                }
                get mode() {
                    return this.state.get("mode");
                }
                get readOnly() {
                    return this.state.get("readOnly", false);
                }
                set readOnly(value) {
                    this.state.set("readOnly", value);
                }
                get theme() {
                    return this.state.get("theme", "ace/theme/chrome");
                }
                get value() {
                    return this.ace.getValue();
                }
                set value(value) {
                    this.m_isSilentSet = true;
                    this.ace.setValue(value);
                    this.m_isSilentSet = false;
                }
                template() {
                    return `<div class="-pdjs-shared-ace-editor">
                        <div role="editor"></div>
                    </div>`;
                }
                resize() {
                    if (this.ace != null) {
                        this.ace.resize();
                    }
                }
                destroy() {
                    super.destroy();
                    if (this.ace != null) {
                        this.ace.destroy();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    if (this.content != null) {
                        this.ace.setValue(this.content, 0);
                    }
                }
                onStateChanged() {
                    super.onStateChanged();
                    if (this.ace != null) {
                        this.ace.setReadOnly(this.readOnly);
                    }
                }
                editor_init() {
                    ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                    this.m_editor = ace.edit(this.aceNode[0]);
                    this.ace.renderer.setShowPrintMargin(false);
                    this.ace.setShowFoldWidgets(true);
                    this.ace.getSession().setUseSoftTabs(false);
                    this.ace.setTheme(this.theme);
                    this.ace.session.setMode(`ace/mode/${this.mode}`);
                    this.ace.setFontSize("14px");
                    this.ace.setValue(this.value || "");
                    this.ace.setReadOnly(this.readOnly);
                    this.editor_focus();
                    this.ace.on("change", (e) => {
                        if (this.m_isSilentSet !== true) {
                            this.changeCallback({
                                value: this.ace.getValue()
                            });
                        }
                    });
                }
                editor_focus() {
                    let session = this.ace.getSession();
                    let lineCount = session.getLength();
                    this.ace.focus();
                    this.ace.gotoLine(lineCount, session.getLine(lineCount - 1).length);
                }
            }
            Ace.AceEditor = AceEditor;
        })(Ace = Shared.Ace || (Shared.Ace = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Actions;
        (function (Actions) {
            class ActionDefinition {
                constructor(options) {
                    this.m_parameters = [];
                    this.m_options = options;
                    this.m_pluginId = options.pluginId;
                    this.convertToParameters(options.parameters, (item) => {
                        return new Actions.ActionParameterDefinition(item);
                    });
                }
                get options() {
                    return this.m_options;
                }
                get id() {
                    return this.m_options.id;
                }
                get name() {
                    return this.m_options.name;
                }
                get description() {
                    return this.m_options.description;
                }
                get targetArbiter() {
                    return this.m_options.targetArbiter || "ProspectDirector.Web.Plugins.Actions.ActionArbiter";
                }
                get targetType() {
                    return this.m_options.targetType;
                }
                get parameters() {
                    return this.m_parameters;
                }
                set parameters(value) {
                    this.m_parameters = value;
                }
                get pluginId() {
                    return this.m_pluginId || null;
                }
                set pluginId(value) {
                    this.m_pluginId = value;
                }
                get plugin() {
                    this.ensurePlugin();
                    return this.m_plugin;
                }
                get executeCallback() {
                    return this.m_options.execute || (() => { });
                }
                execute(args) {
                    this.executeCallback(args);
                }
                getFullName() {
                    return `${this.plugin.name} : ${this.name}`;
                }
                toJSON(data) {
                    return _.extend({
                        id: this.id,
                        name: this.name,
                        pluginId: this.pluginId,
                        parameters: this.parameters.map(item => {
                            return item.toJSON();
                        }),
                        description: this.description,
                        targetArbiter: this.targetArbiter,
                        targetType: this.targetType
                    }, data || {});
                }
                toAction(params = []) {
                    let result = null;
                    let options = this.toJSON();
                    options.parameters = this.parameters.map((parameter, index) => {
                        let param = index <= params.length ? {} : params[index];
                        let options = parameter.toJSON({
                            label: param === null || param === void 0 ? void 0 : param.label,
                            value: param === null || param === void 0 ? void 0 : param.value,
                        });
                        return new Actions.ActionParameter(options);
                    });
                    options.execute = this.execute;
                    result = new Actions.Action(options);
                    return result;
                }
                convertToParameters(params, fn = null) {
                    fn = fn || ((item) => { return item; });
                    this.parameters = params.map(parameter => {
                        if (parameter.hasOwnProperty("name")) {
                            return fn(parameter);
                        }
                        else {
                            return parameter;
                        }
                    });
                }
                ensurePlugin() {
                    if (this.m_plugin == null) {
                        this.m_plugin = PDJS.Shared
                            .Plugins
                            .PluginManager
                            .instance
                            .getPlugin(this.pluginId);
                    }
                }
                static getDefinition(pluginId, actionId) {
                    let plugin = PDJS.Shared.Plugins.PluginManager.instance.getPlugin(pluginId);
                    let result;
                    if (plugin != null) {
                        result = plugin.actions.getActionDefinitionById(actionId);
                    }
                    return result;
                }
            }
            Actions.ActionDefinition = ActionDefinition;
        })(Actions = Shared.Actions || (Shared.Actions = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Actions;
        (function (Actions) {
            class Action extends Actions.ActionDefinition {
                get options() {
                    return super.options;
                }
                get definition() {
                    return Actions.ActionDefinition.getDefinition(this.pluginId, this.id);
                }
                constructor(options) {
                    super(options);
                    this.convertToParameters(this.parameters, (item) => {
                        return new Actions.ActionParameter(item);
                    });
                }
                static invoke(json) {
                    let action = new Action(json);
                    let params = {};
                    let result = null;
                    if (action.id == null || action.definition == null) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "Execute Action Error",
                            message: `The action "${json.pluginId}:${json.id}" cannot be executed.<br/><br/>Contact your system administrator.`
                        });
                        return;
                    }
                    json.parameters.forEach(o => {
                        params[o.name] = (o.value);
                    });
                    if (action.definition != null) {
                        result = action.definition.execute.apply(action.definition, [params]);
                    }
                    return result || (() => { });
                }
                static getAction(actionId, pluginId, params) {
                    var _a, _b, _c;
                    return (_c = (_b = (_a = PDJS.Shared.Plugins.PluginManager
                        .instance
                        .getPlugin(pluginId)) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.getActionDefinitionById(actionId)) === null || _c === void 0 ? void 0 : _c.toAction(params || []);
                }
            }
            Actions.Action = Action;
        })(Actions = Shared.Actions || (Shared.Actions = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Actions;
        (function (Actions) {
            class ActionManager {
                constructor(options) {
                    this.m_actions = {};
                    this.m_options = options;
                }
                get actions() {
                    return this.m_actions;
                }
                get hasActions() {
                    return _.keys(this.actions).length > 0;
                }
                get pluginId() {
                    var _a;
                    return (_a = this.m_options) === null || _a === void 0 ? void 0 : _a.pluginId;
                }
                getActionDefinitions() {
                    return _.clone(this.actions);
                }
                addActionDefinition(action) {
                    var actionId = action === null || action === void 0 ? void 0 : action.id;
                    if (!(actionId in this.actions)) {
                        this.actions[actionId] = action;
                        action.pluginId = this.pluginId;
                    }
                }
                removeActionDefinition(action) {
                    var actionId = null;
                    if (action instanceof Actions.ActionDefinition) {
                        actionId = action.id;
                    }
                    if (action instanceof String) {
                        actionId = action;
                    }
                    delete this.actions[actionId];
                }
                getActionDefinitionById(id) {
                    var result = null;
                    if (this.actions[id] != null) {
                        result = this.actions[id];
                    }
                    return result;
                }
            }
            Actions.ActionManager = ActionManager;
        })(Actions = Shared.Actions || (Shared.Actions = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Actions;
        (function (Actions) {
            class ActionParameterDefinition {
                constructor(options) {
                    this.m_options = options;
                }
                get options() {
                    return this.m_options;
                }
                get name() {
                    return this.options.name;
                }
                get type() {
                    return this.options.type;
                }
                toJSON(data) {
                    return _.extend({
                        name: this.name,
                        type: this.type
                    }, data || {});
                }
                toParameter(text, value) {
                    let options = this.toJSON({
                        text: text,
                        value: value
                    });
                    return new Actions.ActionParameter(options);
                }
            }
            Actions.ActionParameterDefinition = ActionParameterDefinition;
        })(Actions = Shared.Actions || (Shared.Actions = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Actions;
        (function (Actions) {
            class ActionParameter extends Actions.ActionParameterDefinition {
                constructor(options) {
                    super(options);
                }
                get options() {
                    return this.m_options;
                }
                get label() {
                    return this.options.label;
                }
                get value() {
                    return this.options.value;
                }
                toJSON() {
                    return super.toJSON({
                        label: this.label,
                        value: this.value
                    });
                }
            }
            Actions.ActionParameter = ActionParameter;
        })(Actions = Shared.Actions || (Shared.Actions = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_canMemoize = false;
                }
                get annotation() {
                    return this.m_annotation;
                }
                set annotation(value) {
                    this.m_annotation = value;
                }
                get autocomplete() {
                    return this.m_autocomplete;
                }
                set autocomplete(value) {
                    this.m_autocomplete = value;
                }
                get ace() {
                    return this.m_ace;
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get commands() {
                    return this.m_commands;
                }
                set commands(value) {
                    this.m_commands = value;
                }
                get content() {
                    return this.m_content;
                }
                set content(value) {
                    this.m_content = value;
                }
                get finder() {
                    return this.m_finder;
                }
                set finder(value) {
                    this.m_finder = value;
                }
                get focusCallback() {
                    return this.state.get("focus", () => { });
                }
                get marker() {
                    return this.m_marker;
                }
                set marker(value) {
                    this.m_marker = value;
                }
                get memos() {
                    return this.m_memos;
                }
                set memos(value) {
                    this.m_memos = value;
                }
                get memosCallback() {
                    return this.state.get("memos", () => { });
                }
                get readOnly() {
                    return this.ace.getReadOnly();
                }
                get selection() {
                    return this.m_selection;
                }
                set selection(value) {
                    this.m_selection = value;
                }
                get settings() {
                    return this.m_settings;
                }
                set settings(value) {
                    this.m_settings = value;
                }
                get visible() {
                    return this.node.css("display") != "none";
                }
                set visible(value) {
                    value ? this.node.show() : this.node.hide();
                }
                focus() {
                    this.ace.focus();
                    this.redraw();
                }
                load(value) {
                    this.content.setValue(value, {
                        silent: true,
                        cursorPosition: -1
                    });
                    setTimeout(() => {
                        this.visible = true;
                        this.focus();
                    }, 250);
                }
                setCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/shared/coding/editor": {
                            $editor: this
                        }
                    }, { force: true });
                }
                template() {
                    return `<div class="-pdjs-shared-ui-controls-code-editor"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.ace_init();
                    this.extensions_init();
                    this.node.hide();
                    this.ace.addEventListener("focus", () => {
                        this.focusCallback();
                    });
                }
                ace_init() {
                    ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                    ace.require("ace/ext/language_tools");
                    this.m_ace = ace.edit(this.node.get(0));
                    this.ace.setShowFoldWidgets(true);
                    this.ace.renderer.setShowPrintMargin(false);
                    this.ace.getSession().setUseSoftTabs(false);
                }
                extensions_init() {
                    this.annotation = new Coding.CodeEditorAnnotation({
                        editor: this
                    });
                    this.autocomplete = new Coding.AutoComplete.AutoCompleter({
                        editor: this
                    });
                    this.commands = new Coding.CodeEditorCommandKeys({
                        editor: this
                    });
                    this.content = new Coding.CodeEditorContent({
                        editor: this,
                        change: this.changeCallback
                    });
                    this.finder = new Coding.CodeEditorFinder({
                        editor: this
                    });
                    this.marker = new Coding.CodeEditorMarker({
                        editor: this
                    });
                    this.memos = new Coding.CodeEditorMemos({
                        editor: this
                    });
                    this.selection = new Coding.CodeEditorSelection({
                        editor: this
                    });
                    this.settings = new Coding.CodeEditorSettings({
                        editor: this
                    });
                }
                redraw() {
                    this.ace.resize(true);
                }
            }
            Coding.CodeEditor = CodeEditor;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorBroadcaster extends Shared.Messaging.Broadcaster {
                constructor() {
                    super({ name: "code-editor-broadcaster" });
                }
                publishEditorSettingsChanged() {
                    this.sendMessage({}, "editorSettingsChanged");
                }
                subscribeEditorSettingsChanged(handler) {
                    this.subscribe(handler, "editorSettingsChanged");
                }
            }
            Coding.CodeEditorBroadcaster = CodeEditorBroadcaster;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CommentToggleCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/comment-toggle",
                        label: "Comment / Uncomment",
                        tooltip: "Comment or uncomment the selected lines of code.",
                        icon: "code_red.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    this.editor.selection.toggleCommentLines();
                    this.editor.focus();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.editor != null && !this.editor.readOnly;
                }
            }
            Coding.CommentToggleCommand = CommentToggleCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class FontSizeCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/font-size",
                        label: "Font Size",
                        tooltip: "Select the font size to use within the editor.",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdv2"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.editor != null;
                }
                execute(e) {
                    this.editor.settings.fontSize = `${e.selection}px`;
                }
                onInitialLoad() {
                    super.onInitialLoad();
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.value = parseInt(this.editorSettings.fontSize);
                    });
                    this.value = parseInt(this.editorSettings.fontSize);
                }
            }
            Coding.FontSizeCommand = FontSizeCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class FormatCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "file/format",
                        label: "Format",
                        tooltip: "Normalize the indentation and spacing of the code.",
                        icon: "code.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.format();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.editor != null && !this.editor.readOnly;
                }
                format() {
                    let service = new PDJS.Services.Rules.RulesService();
                    service.formatRuleScript({
                        content: this.editor.content.getValue(),
                        success: (e) => {
                            var pos = this.editor.ace.getCursorPosition();
                            this.editor.content.setValue(e.data.content);
                            this.editor.ace.moveCursorToPosition(pos);
                            this.editor.focus();
                            PDJS.Shared.MessageStack
                                .instance
                                .success("Rule script formatted successuflly.");
                        },
                        error: (e) => {
                            var errors = e.xhr.responseJSON;
                            if (errors != null) {
                                e.errorHandled = true;
                                this.addErrorMarkers(errors);
                                this.showFormatErrorsDialog(errors);
                            }
                        }
                    });
                }
                addErrorMarkers(errors) {
                    errors.forEach(error => {
                        if (error.tags != null && ("ScriptLine" in error.tags)) {
                            this.editor.memos.addErrorMemo({
                                row: error.tags["ScriptLine"] - 1,
                                text: error.message
                            });
                        }
                    });
                }
                showFormatErrorsDialog(errors) {
                    Jade.UI.Dialogs.TaggedMessageDialog.open({
                        title: "Rule Format Error",
                        message: "The following errors were found when formatting:",
                        errors: errors,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        select: (e) => {
                            e.close();
                            this.editor.focus();
                        }
                    });
                }
            }
            Coding.FormatCommand = FormatCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class SetThemeCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/theme",
                        label: "Theme",
                        tooltip: "Select the theme to use within the editor.",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.settings.theme = e.selection;
                }
                onInitialLoad() {
                    super.onInitialLoad();
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.value = this.editorSettings.theme;
                    });
                    PDJS.Profiles.EventsHub.themeChangedSubscribe(() => {
                        this.editor.settings.theme = PDJS.Profiles.Profile.current.themes.editor;
                        this.value = PDJS.Profiles.Profile.current.themes.editor;
                    });
                    this.value = PDJS.Profiles.Profile.current.themes.editor;
                }
            }
            Coding.SetThemeCommand = SetThemeCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class SplitHorizontalCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/split/horizontal",
                        label: "Split Vertically",
                        tooltip: "Arrange the code editor panes vertically.",
                        icon: "window_split_hor.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    this.workspace.settings.orientation = "horizontal";
                    this.editor.focus();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.workspace != null && this.workspace.pane2.visible;
                }
            }
            Coding.SplitHorizontalCommand = SplitHorizontalCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class SplitVerticalCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/split/vertical",
                        label: "Split Horizontally",
                        tooltip: "Arrange the code editor panes horizontally.",
                        icon: "window_split_ver.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    this.workspace.settings.orientation = "vertical";
                    this.editor.focus();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.workspace != null && this.workspace.pane2.visible;
                }
            }
            Coding.SplitVerticalCommand = SplitVerticalCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleAutoCompleteCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/auto-complete",
                        label: "Toggle Auto Complete",
                        tooltip: "Toggle auto complete to assist in writing rules.",
                        icon: "text_field.png",
                        enabled: true,
                        checked: true,
                        display: "icon",
                        iconSetId: "pdjs"
                    };
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.workspace.pane1.editor.autocomplete.enabled = this.checked;
                    this.workspace.pane2.editor.autocomplete.enabled = this.checked;
                    this.editor.focus();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.workspace != null;
                }
            }
            Coding.ToggleAutoCompleteCommand = ToggleAutoCompleteCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleCodeSplitCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/code-split",
                        label: "Code Mirror",
                        tooltip: "Toggle mirror mode where you can edit the code between two panes.",
                        icon: "search_replace.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    !this.workspace.settings.inMirrorMode ?
                        this.workspace.settings.enterMirrorMode() :
                        this.workspace.settings.enterSingleMode();
                    this.editor.focus();
                }
                setState(state) {
                    super.setState(state);
                    this.visible = this.workspace != null;
                    this.enabled = this.workspace != null;
                }
            }
            Coding.ToggleCodeSplitCommand = ToggleCodeSplitCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleFindCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/find",
                        label: "Find",
                        tooltip: "Find occurences of a text pattern.",
                        icon: "binocular.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.finder.showFind();
                }
                setState(state) {
                    super.setState(state);
                    this.enabled = this.editor != null;
                }
            }
            Coding.ToggleFindCommand = ToggleFindCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleIndentsCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-indents",
                        label: "Toggle Indents",
                        tooltip: "Toggle the visibility of indentation markers.",
                        icon: "code.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showIndents;
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.checked = this.editorSettings.showIndents;
                    });
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showIndents = this.checked;
                    this.editor.focus();
                }
            }
            Coding.ToggleIndentsCommand = ToggleIndentsCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleInvisiblesCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-invisibles",
                        label: "Toggle Invisibles",
                        tooltip: "Toggle the visibility of white space characters.",
                        icon: "symbol_paragraph.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showInvisibles;
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.checked = this.editorSettings.showInvisibles;
                    });
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showInvisibles = this.checked;
                    this.editor.focus();
                }
            }
            Coding.ToggleInvisiblesCommand = ToggleInvisiblesCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleLineNumbersCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/toggle-line-numbers",
                        label: "Toggle Line Numbers",
                        tooltip: "Toggle the visibility of line numbers.",
                        icon: "list_style_numbered.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pdv2"
                    };
                }
                onInitialLoad() {
                    this.checked = this.editor.settings.showLineNumbers;
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.checked = this.editorSettings.showLineNumbers;
                    });
                }
                execute(e) {
                    this.checked = !this.checked;
                    this.editor.settings.showLineNumbers = this.checked;
                    this.editor.focus();
                }
            }
            Coding.ToggleLineNumbersCommand = ToggleLineNumbersCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ToggleReplaceCommand extends Coding.CodeEditorCommand {
                getDefaultValuesForProps() {
                    return {
                        id: "editor/replace",
                        label: "Replace",
                        tooltip: "Find and replace occurences of a text pattern.",
                        icon: "search_replace.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    this.editor.finder.showReplace();
                }
                setState(state) {
                    super.setState(state);
                    this.enabled = this.editor != null && !this.editor.readOnly;
                }
            }
            Coding.ToggleReplaceCommand = ToggleReplaceCommand;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/shared/coding/editor");
                }
                registerCommands(e) {
                    e.commands.add(new Coding.CommentToggleCommand());
                    e.commands.add(new Coding.FontSizeCommand());
                    e.commands.add(new Coding.FormatCommand());
                    e.commands.add(new Coding.SetThemeCommand());
                    e.commands.add(new Coding.SplitHorizontalCommand());
                    e.commands.add(new Coding.SplitVerticalCommand());
                    e.commands.add(new Coding.ToggleAutoCompleteCommand());
                    e.commands.add(new Coding.ToggleCodeSplitCommand());
                    e.commands.add(new Coding.ToggleFindCommand());
                    e.commands.add(new Coding.ToggleIndentsCommand());
                    e.commands.add(new Coding.ToggleInvisiblesCommand());
                    e.commands.add(new Coding.ToggleLineNumbersCommand());
                    e.commands.add(new Coding.ToggleReplaceCommand());
                }
            }
            Coding.CodeEditorCommands = CodeEditorCommands;
            Jade.CommandGroups.add(CodeEditorCommands);
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get codeContent() {
                    return this.state.get("codeContent");
                }
                get mimeType() {
                    return this.state.get("mimeType", "text");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`<div class="-pdjs-shared-coding-code-editor-dialog">
                                        <div role="toolbar"></div>
                                        <div role="editor"></div>
                                        <div role="buttons">
                                            <button class="-pdjs-dialog-button" data-id="ok" disabled>OK</button>
                                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                                        </div>
                                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                codeContent: this.m_editor.content.editor1.content.getValue(),
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.editor_init();
                    this.toolbar_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    let mode = Coding.CodeEditorEnvironment.getMode(this.mimeType);
                    this.m_editor.content.editor1.ace.session.setMode(mode);
                    this.m_editor.content.editor2.ace.session.setMode(mode);
                    this.m_editor.content.editor1.autocomplete.enabled = false;
                    this.m_editor.content.editor2.autocomplete.enabled = false;
                    this.m_editor.content.editor1.load(this.codeContent);
                    this.m_editor.content.pane1.headerText = "Current";
                    this.m_editor.content.pane1.focus();
                }
                getDefaultOptions() {
                    return {
                        title: "Edit | Code",
                        height: "80%",
                        width: "80%",
                        maximized: false,
                        resizable: false
                    };
                }
                editor_init() {
                    this.m_editor = new Coding.CodeWorkspace({
                        insertAt: "div[role=editor]",
                        change: () => {
                            this.okButtonNode.prop("disabled", false);
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new PDJS.Shared.Coding.CodeEditorToolbar({ target: "code" })]
                    });
                    this.controls.add(this.m_toolbar);
                }
                static open(options = {}) {
                    return new CodeEditorDialog(options);
                }
            }
            Coding.CodeEditorDialog = CodeEditorDialog;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorEnvironment {
                constructor() {
                    this.m_broadcaster = new Coding.CodeEditorBroadcaster();
                    this.broadcaster.subscribeEditorSettingsChanged(() => {
                        Coding.EventsHub.settingsChangedPublish({
                            sourceId: "broadcaster"
                        });
                    });
                    Coding.EventsHub.settingsChangedSubscribe((e) => {
                        if (e.sourceId !== "broadcaster") {
                            this.broadcaster.publishEditorSettingsChanged();
                        }
                    });
                }
                get fontSize() {
                    return localStorage.getItem("code:editor:font-size");
                }
                set fontSize(value) {
                    localStorage.setItem("code:editor:font-size", value);
                }
                get showIndents() {
                    return this.getLocalStorageBoolean("code:editor:show-indents");
                }
                set showIndents(value) {
                    this.setLocalStorageBoolean("code:editor:show-indents", value);
                }
                get showInvisibles() {
                    return this.getLocalStorageBoolean("code:editor:show-invisibles");
                }
                set showInvisibles(value) {
                    this.setLocalStorageBoolean("code:editor:show-invisibles", value);
                }
                get showLineNumbers() {
                    return this.getLocalStorageBoolean("code:editor:show-line-numbers");
                }
                set showLineNumbers(value) {
                    this.setLocalStorageBoolean("code:editor:show-line-numbers", value);
                }
                get theme() {
                    return this.profile.themes.editor;
                }
                set theme(value) {
                    this.profile.themes.editorThemeOverride = value;
                }
                get autoComplete() {
                    return localStorage.getItem("code:editor:auto-complete");
                }
                set autoComplete(value) {
                    localStorage.setItem("code:editor:auto-complete", value);
                }
                static get current() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                get broadcaster() {
                    return this.m_broadcaster;
                }
                get profile() {
                    return PDJS.System.Environment.current.profile;
                }
                static getTheme(mimeType) {
                    let themes = {
                        "text/html": "ace/theme/chrome",
                        "text/javascript": "ace/theme/chrome",
                        "text/plain": "ace/theme/chrome",
                        "text/css": "ace/theme/tomorrow",
                        "text/xml": "ace/theme/sqlserver",
                        "text/json": "ace/theme/eclipse"
                    };
                    return themes[mimeType] || themes["text/plain"];
                }
                static getMode(mimeType) {
                    let modes = {
                        "text/html": "ace/mode/html",
                        "text/javascript": "ace/mode/javascript",
                        "text/plain": "ace/mode/text",
                        "text/css": "ace/mode/css",
                        "text/xml": "ace/mode/xml",
                        "text/json": "ace/mode/json5"
                    };
                    return modes[mimeType] || modes["ace/mode/text"];
                }
                getLocalStorageBoolean(id) {
                    return localStorage.getItem(id) == "true";
                }
                setLocalStorageBoolean(id, value) {
                    localStorage.setItem(id, value.toString());
                }
                static ensureInstance() {
                    if (this.m_instance == null) {
                        this.m_instance = new CodeEditorEnvironment();
                    }
                }
            }
            Coding.CodeEditorEnvironment = CodeEditorEnvironment;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorExtension {
                constructor(options) {
                    this.m_silentChanges = false;
                    this.m_editor = options.editor;
                    this.ace.renderer.once("afterRender", () => { this.onRendered(); });
                }
                get ace() {
                    return this.editor.ace;
                }
                get editor() {
                    return this.m_editor;
                }
                get environment() {
                    return Coding.CodeEditorEnvironment.current;
                }
                get silentChanges() {
                    return this.m_silentChanges;
                }
                set silentChanges(value) {
                    this.m_silentChanges = value;
                }
                onRendered() {
                }
                onAnnotated() {
                }
            }
            Coding.CodeEditorExtension = CodeEditorExtension;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                constructor(options) {
                    super();
                    this.m_target = options.target;
                }
                onAddItems(e) {
                    let prefix = "pdjs/shared/coding/editor";
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/toggle-indents`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/toggle-invisibles`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/toggle-line-numbers`
                    }));
                    e.registerItem(new PDJS.Manage.Editor.FontSizeItem({
                        commandId: `${prefix}:editor/font-size`
                    }));
                    if (this.m_target == "rules") {
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:file/format`
                        }));
                    }
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/comment-toggle`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/find`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/replace`
                    }));
                    e.registerItem(new Coding.ThemesItem({
                        commandId: `${prefix}:editor/theme`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/code-split`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/split/vertical`
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: `${prefix}:editor/split/horizontal`
                    }));
                    if (this.m_target == "rules") {
                        e.addSeparator();
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:editor/auto-complete`
                        }));
                    }
                }
            }
            Coding.CodeEditorToolbar = CodeEditorToolbar;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            let Events;
            (function (Events) {
                Events["SettingsChanged"] = "CodeEditor:SettingsChanged";
                Events["PaneToggled"] = "CodeWorkspace:PaneToggled";
                Events["PaneFocused"] = "CodeWorkspace:PaneFocused";
            })(Events = Coding.Events || (Coding.Events = {}));
            class EventsHub extends Shared.EventsHubBase {
                static settingsChangedPublish(e = {}) {
                    this.global.publish(Events.SettingsChanged, e);
                }
                static paneToggledPublish(e) {
                    this.current.publish(Events.PaneToggled, e);
                }
                static paneFocusedPublish(e) {
                    this.current.publish(Events.PaneFocused, e);
                }
                static settingsChangedSubscribe(handler) {
                    return this.global.subscribe(Events.SettingsChanged, handler);
                }
                static paneToggledSubscribe(handler) {
                    return this.current.subscribe(Events.PaneToggled, handler);
                }
                static paneFocusedSubscribe(handler) {
                    return this.current.subscribe(Events.PaneFocused, handler);
                }
            }
            Coding.EventsHub = EventsHub;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorAnnotation extends Coding.CodeEditorExtension {
                constructor() {
                    super(...arguments);
                    this.m_annotations = [];
                    this.m_render = _.debounce((annotations) => {
                        setTimeout((e) => {
                            this.renderAnnotations(e);
                        }, 250, annotations.slice(0));
                    }, 200, { trailing: true });
                }
                get annotations() {
                    return this.m_annotations;
                }
                set annotations(value) {
                    this.m_annotations = value;
                }
                add(args) {
                    if (!(args instanceof Array)) {
                        args = [args];
                    }
                    if (args instanceof Array) {
                        args.forEach(annotation => {
                            if (annotation != null) {
                                this.annotations.push(annotation);
                            }
                        });
                    }
                }
                clear(className = null) {
                    this.annotations = this.annotations.filter(annotation => {
                        return (className == null && annotation.clazz == null)
                            || (className != null && annotation.clazz !== className);
                    });
                }
                render() {
                    if (!this.editor.readOnly && this.editor.visible) {
                        this.m_render(this.annotations);
                    }
                }
                sync(source) {
                    if (source === this.editor) {
                        return;
                    }
                    this.clear();
                    if (this.editor.readOnly || !this.editor.visible) {
                        return;
                    }
                    this.add(source.annotation.annotations);
                    this.render();
                }
                renderAnnotations(inputs) {
                    if (inputs.length === 0) {
                        return;
                    }
                    let annotations = this.ace.session.getAnnotations();
                    annotations = annotations.filter(annotation => {
                        return annotation.clazz == null;
                    });
                    inputs.forEach(annotation => {
                        annotations.push(annotation);
                    });
                    this.ace.session.setAnnotations(annotations);
                }
            }
            Coding.CodeEditorAnnotation = CodeEditorAnnotation;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorCommandKeys extends Coding.CodeEditorExtension {
                addCommand(shortcut, exec) {
                    this.ace.commands.addCommand({
                        name: shortcut,
                        bindKey: { win: "Ctrl-S" },
                        exec: () => {
                            if (_.isFunction(exec)) {
                                exec(this.ace);
                            }
                        }
                    });
                }
            }
            Coding.CodeEditorCommandKeys = CodeEditorCommandKeys;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorContent extends Coding.CodeEditorExtension {
                constructor(options) {
                    super(options);
                    this.m_change = options.change;
                }
                get cursorIndex() {
                    return this.ace.session.doc.positionToIndex(this.ace.getCursorPosition(), 0);
                }
                get changeCallback() {
                    return this.m_change || (() => { });
                }
                get changed() {
                    return this.m_changed;
                }
                set changed(value) {
                    this.m_changed = value;
                }
                getValue() {
                    return this.ace.getValue();
                }
                moveCursorToStart() {
                    this.editor.ace.moveCursorTo(0, 0);
                    this.editor.ace.selection.clearSelection();
                }
                resetChangedState() {
                    this.m_changed = false;
                }
                setValue(value, options = {}) {
                    let silentChanges = this.silentChanges;
                    let currentPosition = this.editor.ace.getCursorPosition();
                    this.silentChanges = options.silent;
                    this.ace.setValue(value || "", options.cursorPosition ? options.cursorPosition : -1);
                    if (options.cursorPosition == null) {
                        this.editor.ace.moveCursorToPosition(currentPosition);
                    }
                    if (options.changed != null) {
                        this.changed = options.changed;
                    }
                    this.silentChanges = silentChanges;
                }
                sync(source) {
                    if (source === this.editor) {
                        return;
                    }
                    this.editor.content.setValue(source.content.getValue(), { silent: true });
                }
                toggleCommentLines() {
                    this.ace.toggleCommentLines();
                }
                getTextLeftOfCursor() {
                    return this.getValue().slice(0, this.cursorIndex);
                }
                onRendered() {
                    super.onRendered();
                    this.ace.getSession().on("change", () => {
                        if (!this.silentChanges) {
                            this.changed = true;
                            this.changeCallback();
                        }
                    });
                }
            }
            Coding.CodeEditorContent = CodeEditorContent;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorFinder extends Coding.CodeEditorExtension {
                showFind(value, isReplace = false) {
                    this.ace.searchBox.show(value, isReplace);
                }
                hideFind() {
                    this.ace.searchBox.hide();
                }
                showReplace() {
                    this.ace.execCommand("replace");
                }
                find(text) {
                    this.ace.gotoLine(0);
                    this.ace.find(text);
                }
                onRendered() {
                    this.loadSearchBoxModule();
                }
                loadSearchBoxModule() {
                    ace.config.loadModule("ace/ext/searchbox", (m) => {
                        m.Search(this.ace);
                        this.hideFind();
                    });
                }
            }
            Coding.CodeEditorFinder = CodeEditorFinder;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorMarker extends Coding.CodeEditorExtension {
                constructor() {
                    super(...arguments);
                    this.m_markers = [];
                }
                get markers() {
                    return this.m_markers;
                }
                set markers(value) {
                    this.m_markers = value;
                }
                add(args) {
                    let isAddArgs = args
                        .hasOwnProperty("startOnLine");
                    let marker = isAddArgs ?
                        this.convertArgsToMarker(args) : args;
                    this.markers.push(marker);
                }
                clear(className = null) {
                    let keep = [];
                    let kill = [];
                    this.markers.forEach(marker => {
                        let keeper = (className == null) ||
                            (className != null && marker.clazz !== className);
                        keeper ? keep.push(marker) : kill.push(marker);
                    });
                    kill.forEach(marker => {
                        this.ace.session.removeMarker(marker.id);
                    });
                    this.markers = keep;
                }
                render() {
                    let markers = this.editor.ace.session.getMarkers(false);
                    for (let key in markers) {
                        let marker = markers[key];
                        if (marker.clazz != null && marker.clazz.startsWith("-pdjs")) {
                            this.editor.ace.session.removeMarker(marker.id);
                        }
                    }
                    ;
                    if (!this.editor.readOnly && this.editor.visible) {
                        this.markers.forEach(marker => {
                            marker.id =
                                this.ace.session.addMarker(marker.range, marker.clazz, marker.type, marker.inFront);
                        });
                    }
                }
                sync(source) {
                    if (source === this.editor) {
                        return;
                    }
                    this.clear();
                    if (this.editor.readOnly || !this.editor.visible) {
                        return;
                    }
                    source.marker.markers.forEach(marker => {
                        this.add(marker);
                    });
                    this.render();
                }
                createRange(startOnLine, endOnLine) {
                    let AceRange = ace.require('ace/range').Range;
                    return new AceRange(startOnLine, 0, endOnLine, 1);
                }
                getMarkers() {
                    let result = [];
                    let markers = this.ace.session.getMarkers(false);
                    for (let key in markers) {
                        let marker = markers[key];
                        if (marker.clazz.startsWith("-pdjs")) {
                            result.push(marker);
                        }
                    }
                    return result;
                }
                convertArgsToMarker(args) {
                    return {
                        clazz: args.clazz,
                        id: args.id,
                        inFront: args.inFront,
                        range: this.createRange(args.startOnLine, args.endOnLine || args.startOnLine),
                        renderer: args.renderer,
                        type: args.type
                    };
                }
            }
            Coding.CodeEditorMarker = CodeEditorMarker;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            let AnnotationType;
            (function (AnnotationType) {
                AnnotationType["error"] = "error";
                AnnotationType["info"] = "info";
                AnnotationType["ref"] = "ref";
                AnnotationType["warn"] = "warn";
            })(AnnotationType = Coding.AnnotationType || (Coding.AnnotationType = {}));
            let MarkerType;
            (function (MarkerType) {
                MarkerType["error"] = "-pdjs-code-editor-memo-error";
                MarkerType["info"] = "-pdjs-code-editor-memo-info";
                MarkerType["ref"] = "-pdjs-code-editor-memo-ref";
                MarkerType["warn"] = "-pdjs-code-editor-memo-warn";
            })(MarkerType = Coding.MarkerType || (Coding.MarkerType = {}));
            class CodeEditorMemos extends Coding.CodeEditorExtension {
                get canMemoize() {
                    return !this.editor.readOnly && this.editor.visible;
                }
                addErrorMemo(reference) {
                    if (!this.canMemoize) {
                        return;
                    }
                    this.editor.annotation.add({
                        column: 0,
                        row: reference.row,
                        text: reference.text,
                        type: "error",
                        clazz: AnnotationType.error
                    });
                    this.editor.marker.add({
                        clazz: MarkerType.error,
                        inFront: false,
                        startOnLine: reference.row,
                        type: "fullLine"
                    });
                }
                addInfoMemo(reference) {
                    if (!this.canMemoize) {
                        return;
                    }
                    this.editor.annotation.add({
                        column: 0,
                        row: reference.row,
                        text: reference.text,
                        type: "info",
                        clazz: AnnotationType.info
                    });
                    this.editor.marker.add({
                        clazz: MarkerType.info,
                        inFront: false,
                        startOnLine: reference.row,
                        type: "fullLine"
                    });
                }
                addReferenceMemo(reference) {
                    if (!this.canMemoize) {
                        return;
                    }
                    this.editor.annotation.add({
                        column: 0,
                        row: reference.row,
                        text: `Reference: ${reference.text}`,
                        type: "ref",
                        clazz: AnnotationType.ref
                    });
                    this.editor.marker.add({
                        clazz: MarkerType.ref,
                        inFront: false,
                        startOnLine: reference.row,
                        type: "fullLine"
                    });
                }
                addWarningMemo(reference) {
                    if (!this.canMemoize) {
                        return;
                    }
                    this.editor.annotation.add({
                        column: 0,
                        row: reference.row,
                        text: reference.text,
                        type: "warning",
                        clazz: AnnotationType.warn
                    });
                    this.editor.marker.add({
                        clazz: MarkerType.warn,
                        inFront: false,
                        startOnLine: reference.row,
                        type: "fullLine"
                    });
                }
                clear() {
                    this.clearErrors();
                    this.clearInfos();
                    this.clearRefs();
                    this.clearWarns();
                }
                clearErrors() {
                    this.editor.annotation.clear(AnnotationType.error);
                    this.editor.marker.clear(MarkerType.error);
                }
                clearInfos() {
                    this.editor.annotation.clear(AnnotationType.info);
                    this.editor.marker.clear(MarkerType.info);
                }
                clearRefs() {
                    this.editor.annotation.clear(AnnotationType.ref);
                    this.editor.marker.clear(MarkerType.ref);
                }
                clearWarns() {
                    this.editor.annotation.clear(AnnotationType.warn);
                    this.editor.marker.clear(MarkerType.warn);
                }
                render() {
                    this.editor.marker.render();
                    this.editor.annotation.render();
                }
                sync(source) {
                    if (source === this.editor) {
                        return;
                    }
                    this.editor.annotation.sync(source);
                    this.editor.marker.sync(source);
                }
            }
            Coding.CodeEditorMemos = CodeEditorMemos;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorSelection extends Coding.CodeEditorExtension {
                toggleCommentLines() {
                    this.ace.toggleCommentLines();
                }
            }
            Coding.CodeEditorSelection = CodeEditorSelection;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeEditorSettings extends Coding.CodeEditorExtension {
                get fontSize() {
                    return this.ace.getFontSize();
                }
                set fontSize(value) {
                    this.ace.setFontSize(value);
                    this.publishSettingsChanged();
                }
                get showInvisibles() {
                    return this.ace.getShowInvisibles();
                }
                set showInvisibles(value) {
                    this.ace.setShowInvisibles(value);
                    this.publishSettingsChanged();
                }
                get showIndents() {
                    return this.ace.getDisplayIndentGuides();
                }
                set showIndents(value) {
                    this.ace.setDisplayIndentGuides(value);
                    this.publishSettingsChanged();
                }
                get showLineNumbers() {
                    return this.ace.renderer.getShowGutter();
                }
                set showLineNumbers(value) {
                    this.ace.renderer.setShowGutter(value);
                    this.publishSettingsChanged();
                }
                get theme() {
                    return this.ace.getTheme();
                }
                set theme(value) {
                    this.setEditorTheme(value);
                    this.publishSettingsChanged();
                }
                reset() {
                    this.applyEnvironmentSettings();
                }
                setStyle(mimeType) {
                    let mode = Coding.CodeEditorEnvironment.getMode(mimeType);
                    let theme = this.environment.theme ||
                        Coding.CodeEditorEnvironment.getTheme(mimeType);
                    this.setEditorTheme(theme);
                    this.ace.session.setMode(mode);
                }
                onRendered() {
                    this.applyEnvironmentSettings();
                    Coding.EventsHub.settingsChangedSubscribe(() => {
                        this.applyEnvironmentSettings();
                    });
                    PDJS.Profiles.EventsHub.themeChangedSubscribe(() => {
                        this.theme = PDJS.Profiles.Profile.current.themes.editor;
                        this.publishSettingsChanged();
                    });
                }
                applyEnvironmentSettings() {
                    this.silentChanges = true;
                    this.showIndents = this.environment.showIndents;
                    this.showInvisibles = this.environment.showInvisibles;
                    this.showLineNumbers = this.environment.showLineNumbers;
                    this.fontSize = this.environment.fontSize;
                    this.theme = this.environment.theme;
                    this.silentChanges = false;
                }
                publishSettingsChanged() {
                    if (this.silentChanges) {
                        return;
                    }
                    this.environment.fontSize = this.fontSize;
                    this.environment.showIndents = this.showIndents;
                    this.environment.showInvisibles = this.showInvisibles;
                    this.environment.showLineNumbers = this.showLineNumbers;
                    Coding.EventsHub.settingsChangedPublish();
                }
                setEditorTheme(value) {
                    this.environment.theme = value;
                    value = value == "sys/theme/current"
                        ? PDJS.Profiles.Profile.current.themes.defaultEditor : value;
                    this.ace.setTheme(value);
                }
            }
            Coding.CodeEditorSettings = CodeEditorSettings;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class FontSizeItem extends PDJS.Shared.UI.Controls.ToolbarCommandList {
                constructor(options) {
                    super(options);
                }
                onInit(e) {
                    super.onInit(e);
                    this.items = [];
                    [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 32, 36].forEach(item => {
                        this.items.push({ label: `${item} px`, value: item });
                    });
                }
                onPropertiesChanged() {
                    super.onPropertiesChanged();
                    if (this.commander.value != null) {
                        this.inputNode.val(this.commander.value);
                    }
                }
            }
            Coding.FontSizeItem = FontSizeItem;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class ThemesItem extends PDJS.Shared.UI.Controls.ToolbarCommandList {
                constructor(options) {
                    super(options);
                    this.m_themes = [
                        { name: "- Current Manage Theme - ", value: "sys/theme/current" },
                        { name: "Chrome", value: "ace/theme/chrome" },
                        { name: "Clouds", value: "ace/theme/clouds" },
                        { name: "Crimson Editor", value: "ace/theme/crimson_editor" },
                        { name: "Dawn", value: "ace/theme/dawn" },
                        { name: "Dreamweaver", value: "ace/theme/dreamweaver" },
                        { name: "Eclipse", value: "ace/theme/eclipse" },
                        { name: "GitHub", value: "ace/theme/github" },
                        { name: "IPlastic", value: "ace/theme/iplastic" },
                        { name: "KatzenMilch", value: "ace/theme/katzenmilch" },
                        { name: "Kuroir", value: "ace/theme/kuroir" },
                        { name: "Solarized Light", value: "ace/theme/solarized_light" },
                        { name: "SQL Server", value: "ace/theme/sqlserver" },
                        { name: "TextMate", value: "ace/theme/textmate" },
                        { name: "Tomorrow", value: "ace/theme/tomorrow" },
                        { name: "Xcode", value: "ace/theme/xcode" },
                        { name: "Ambiance", value: "ace/theme/ambiance" },
                        { name: "Chaos", value: "ace/theme/chaos" },
                        { name: "Clouds Midnight", value: "ace/theme/clouds_midnight" },
                        { name: "Cobalt", value: "ace/theme/cobalt" },
                        { name: "Dracula", value: "ace/theme/dracula" },
                        { name: "Green on Black", value: "ace/theme/gob" },
                        { name: "Gruvbox", value: "ace/theme/gruvbox" },
                        { name: "Idle Fingers", value: "ace/theme/idle_fingers" },
                        { name: "krTheme", value: "ace/theme/kr_theme" },
                        { name: "Merbivore", value: "ace/theme/merbivore" },
                        { name: "Merbivore Soft", value: "ace/theme/merbivore_soft" },
                        { name: "Mono Industrial", value: "ace/theme/mono_industrial" },
                        { name: "Monokai", value: "ace/theme/monokai" },
                        { name: "Nord Dark", value: "ace/theme/nord_dark" },
                        { name: "Pastel on Dark", value: "ace/theme/pastel_on_dark" },
                        { name: "Solarized Dark", value: "ace/theme/solarized_dark" },
                        { name: "Terminal", value: "ace/theme/terminal" },
                        { name: "Tomorrow Night", value: "ace/theme/tomorrow_night" },
                        { name: "Tomorrow Night Blue", value: "ace/theme/tomorrow_night_blue" },
                        { name: "Tomorrow Night Bright", value: "ace/theme/tomorrow_night_bright" },
                        { name: "Tomorrow Night Eighties", value: "ace/theme/tomorrow_night_eighties" },
                        { name: "Twilight", value: "ace/theme/twilight" },
                        { name: "Vibrant Ink", value: "ace/theme/vibrant_ink" }
                    ];
                }
                onInit(e) {
                    super.onInit(e);
                    this.items = [];
                    this.m_themes.forEach(theme => {
                        this.items.push({ label: theme.name, value: theme.value });
                    });
                }
                onPropertiesChanged() {
                    super.onPropertiesChanged();
                    if (this.commander.value != null) {
                        this.inputNode.val(this.commander.value);
                    }
                }
            }
            Coding.ThemesItem = ThemesItem;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspace extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get content() {
                    this.ensureContent();
                    return this.m_content;
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get focusCallback() {
                    return this.state.get("focus", () => { });
                }
                get focusedPane() {
                    return this.getFocusedPane();
                }
                get memos() {
                    this.ensureMemos();
                    return this.m_memos;
                }
                get operations() {
                    this.ensureOperations();
                    return this.m_operations;
                }
                get pane1() {
                    return this.m_pane1;
                }
                get pane2() {
                    return this.m_pane2;
                }
                get splitterNode() {
                    return this.node.children("div[role=splitter]");
                }
                get splitter() {
                    return this.m_splitter;
                }
                set splitter(value) {
                    this.m_splitter = value;
                }
                get settings() {
                    this.ensureSettings();
                    return this.m_settings;
                }
                focus() {
                    this.resize();
                }
                resize() {
                    if (this.splitter != null) {
                        if (this.pane2.visible) {
                            this.splitter.size(".k-pane:first", "50%");
                            this.splitter.size(".k-pane:last", "50%");
                        }
                        this.splitter.resize();
                    }
                }
                setCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/shared/coding/editor": {
                            $workspace: this
                        }
                    }, { force: true });
                }
                showPanes(pane1 = true, pane2 = false, init = false) {
                    let showPane1 = pane1 === true || (pane1 == false && pane2 == false);
                    let showPane2 = pane2 === true;
                    let showPane1And2 = showPane1 && showPane2;
                    let panes = [];
                    this.splitter_destroy();
                    if (showPane1) {
                        panes.push({
                            resizable: true,
                            scrollable: false,
                            size: showPane1And2 ? (init ? "100%" : "50%") : "100%"
                        });
                        this.splitterNode.append(this.pane1.node);
                    }
                    if (showPane2) {
                        panes.push({
                            resizable: true,
                            scrollable: false,
                            size: showPane1And2 ? (init ? "0%" : "50%") : "100%"
                        });
                        this.splitterNode.append(this.pane2.node);
                    }
                    this.splitter_init(panes);
                    this.pane1.visible = showPane1;
                    this.pane2.visible = showPane2;
                    this.setCommandState();
                }
                syncPanes(source = null, destination = null) {
                    if (source == null && destination == null) {
                        source = this.pane1.focused ? this.pane1 : this.pane2;
                        destination = this.pane1.focused ? this.pane2 : this.pane1;
                    }
                    if (source == null && destination != null) {
                        source = destination === this.pane1 ? this.pane2 : this.pane1;
                    }
                    if (source != null && destination == null) {
                        destination = source === this.pane1 ? this.pane2 : this.pane1;
                    }
                    destination.sync(source);
                }
                template() {
                    return `<div class="-pdjs-shared-coding-workspace">
                        <div role="splitter"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.pane1_init();
                    this.pane2_init();
                    this.showPanes(true, true, true);
                }
                onComplete(e) {
                    super.onComplete(e);
                    setTimeout(() => {
                        this.showPanes(true, false);
                    }, 10);
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter != null) {
                        this.splitter.destroy();
                    }
                }
                ensureContent() {
                    if (this.m_content == null) {
                        this.m_content = new Coding.CodeWorkspaceContent({
                            workspace: this
                        });
                    }
                }
                ensureMemos() {
                    if (this.m_memos == null) {
                        this.m_memos = new Coding.CodeWorkspaceMemos({
                            workspace: this
                        });
                    }
                }
                ensureOperations() {
                    if (this.m_operations == null) {
                        this.m_operations = new Coding.CodeWorkspaceOperations({
                            workspace: this
                        });
                    }
                }
                ensureSettings() {
                    if (this.m_settings == null) {
                        this.m_settings = new Coding.CodeWorkspaceSettings({
                            workspace: this
                        });
                    }
                }
                getFocusedPane() {
                    if (this.pane1.focused) {
                        return this.pane1;
                    }
                    if (this.pane2.focused) {
                        return this.pane2;
                    }
                    return null;
                }
                pane1_init() {
                    this.m_pane1 = new Coding.CodeWorkspacePane({
                        allowClose: false,
                        insertAt: "div[role=splitter]",
                        pane: "left",
                        change: () => {
                            this.onContentChange(this.pane1);
                        },
                        close: (sender) => {
                            this.showPanes(true, true);
                        },
                        focus: (sender) => {
                            this.setCommandState();
                            this.focusCallback(this.pane1);
                        }
                    });
                    this.controls.add(this.pane1);
                }
                pane2_init() {
                    this.m_pane2 = new Coding.CodeWorkspacePane({
                        allowClose: true,
                        insertAt: "div[role=splitter]",
                        pane: "right",
                        change: () => {
                            this.onContentChange(this.pane2);
                        },
                        close: (sender) => {
                            this.settings.enterSingleMode();
                            this.showPanes(true, false);
                        },
                        focus: (sender) => {
                            this.setCommandState();
                            this.focusCallback(this.pane2);
                        }
                    });
                    this.controls.add(this.pane2);
                }
                redraw() {
                    if (this.pane1.visible && this.pane1.ready) {
                        this.pane1.editor.ace.resize();
                    }
                    if (this.pane2.visible && this.pane2.ready) {
                        this.pane2.editor.ace.resize();
                    }
                }
                splitter_destroy() {
                    this.pane1.node.detach();
                    this.pane2.node.detach();
                    if (this.splitter) {
                        this.splitter.destroy();
                        this.splitterNode.empty();
                    }
                }
                splitter_init(panes) {
                    this.splitter = this.splitterNode.kendoSplitter({
                        panes: panes,
                        orientation: this.settings.orientation,
                        resize: () => {
                            this.redraw();
                        }
                    }).data("kendoSplitter");
                }
                onContentChange(sender) {
                    this.memos.clearErrors();
                    if (this.settings.inMirrorMode) {
                        let content = sender.editor.content.getValue();
                        if (sender === this.pane1) {
                            this.pane2.editor.content.setValue(content, { silent: true, changed: true });
                        }
                        if (sender === this.pane2) {
                            this.pane1.editor.content.setValue(content, { silent: true, changed: true });
                        }
                    }
                    if (sender == this.pane1 || this.settings.inMirrorMode) {
                        this.changeCallback();
                    }
                    this.operations.highlightReferences();
                }
            }
            Coding.CodeWorkspace = CodeWorkspace;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceExtension {
                constructor(options) {
                    this.m_changeCallback = options.change;
                    delete options.change;
                    this.m_workspace = options.workspace;
                    delete options.workspace;
                    this.m_state = new Jade.StateBag(options);
                    this.m_state.on("change", () => {
                        this.onStateChanged();
                    });
                }
                get changeCallback() {
                    return this.m_changeCallback || (() => { });
                }
                get editor1() {
                    return this.workspace.pane1.editor;
                }
                get editor2() {
                    return this.workspace.pane2.editor;
                }
                get focusedEditor() {
                    return this.getFocusedEditor();
                }
                get blurredEditor() {
                    return this.getBlurredEditor();
                }
                get pane1() {
                    return this.workspace.pane1;
                }
                get pane2() {
                    return this.workspace.pane2;
                }
                get state() {
                    return this.m_state;
                }
                get workspace() {
                    return this.m_workspace;
                }
                onStateChanged() {
                    this.changeCallback();
                }
                getFocusedEditor() {
                    return this.workspace.pane1.focused ?
                        this.editor1 : this.editor2;
                }
                getBlurredEditor() {
                    return this.workspace.pane1.focused ?
                        this.editor2 : this.editor1;
                }
            }
            Coding.CodeWorkspaceExtension = CodeWorkspaceExtension;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceOperation {
                constructor(options) {
                    this.m_workspace = options.workspace;
                    delete options.workspace;
                }
                get workspace() {
                    return this.m_workspace;
                }
                set workspace(value) {
                    this.m_workspace = value;
                }
                execute(args) {
                }
            }
            Coding.CodeWorkspaceOperation = CodeWorkspaceOperation;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspacePane extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get allowClose() {
                    return this.state.get("allowClose", false);
                }
                set allowClose(value) {
                    this.state.set("allowClose", value);
                }
                get bodyNode() {
                    return this.node.find(".-pdjs-shared-coding-workspace-pane-body");
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get closeCallback() {
                    return this.state.get("close", () => { });
                }
                get editor() {
                    return this.m_editor;
                }
                get editorNode() {
                    return this.node.find(".-pdjs-shared-coding-workspace-pane-editor");
                }
                get focusCallback() {
                    return this.state.get("focus", () => { });
                }
                get focused() {
                    return this.bodyNode.hasClass("-pdjs-focused");
                }
                get headerNode() {
                    return this.node.find(".-pdjs-shared-coding-workspace-pane-header");
                }
                get headerTextNode() {
                    return this.headerNode.children("div").first();
                }
                get closeNode() {
                    return this.headerNode.find("div:last-child > i");
                }
                get headerText() {
                    return this.state.get("headerText", "");
                }
                set headerText(value) {
                    this.state.set("headerText", value);
                }
                get pane() {
                    return this.state.get("pane");
                }
                get readOnly() {
                    return this.state.get("readOnly", false);
                }
                set readOnly(value) {
                    this.state.set("readOnly", value);
                }
                get visible() {
                    return this.state.get("visible", true);
                }
                set visible(value) {
                    this.state.set("visible", value);
                }
                get ready() {
                    return this.editor != null
                        && this.editor.ace != null;
                }
                clean() {
                    this.node.css({
                        top: "",
                        left: "",
                        right: "",
                        bottom: "",
                    });
                }
                focus() {
                    if (!this.focused) {
                        this.editor.focus();
                        this.setFocused(true);
                    }
                }
                sync(source) {
                    if (source === this) {
                        return;
                    }
                    this.editor.content.sync(source.editor);
                    this.editor.memos.sync(source.editor);
                }
                template() {
                    return `<div class="-pdjs-shared-coding-workspace-pane">
                        <div class="-pdjs-shared-coding-workspace-pane-body">
                            <div class="-pdjs-shared-coding-workspace-pane-header">
                                <div></div>
                                <div>
                                    <i class="icofont-close" title="Close Pane"></i>
                                </div>
                            </div>
                            <div class="-pdjs-shared-coding-workspace-pane-editor"></div>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                    this.closeNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        this.closeCallback(this);
                    });
                    Coding.EventsHub.paneFocusedSubscribe((e) => {
                        if (e.pane != this.pane) {
                            this.setFocused(false);
                        }
                    });
                    this.node.on(Jade.BrowserEvent.CLICK, () => {
                        this.focus();
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    if (this.state.hasChanged("readOnly")) {
                        this.editor.ace.setReadOnly(this.readOnly);
                    }
                    this.headerTextNode.text(this.headerText);
                    this.closeNode.css({
                        display: this.allowClose ? "" : "none"
                    });
                }
                editor_init() {
                    this.m_editor = new Coding.CodeEditor({
                        insertAt: ".-pdjs-shared-coding-workspace-pane-editor",
                        change: () => { this.changeCallback(); }
                    });
                    this.controls.add(this.m_editor);
                }
                setFocused(focused) {
                    focused ?
                        this.bodyNode.addClass("-pdjs-focused") :
                        this.bodyNode.removeClass("-pdjs-focused");
                    if (focused) {
                        Coding.EventsHub.paneFocusedPublish({
                            pane: this.pane,
                        });
                        this.focusCallback(this);
                    }
                }
            }
            Coding.CodeWorkspacePane = CodeWorkspacePane;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class HighlightReferencesOperation extends Coding.CodeWorkspaceOperation {
                get editor1() {
                    return this.workspace.pane1.editor;
                }
                get editor2() {
                    return this.workspace.pane2.editor;
                }
                execute(e) {
                    var _a;
                    this.workspace.memos.clearRefs();
                    if (((_a = e.terms) === null || _a === void 0 ? void 0 : _a.length) === 0) {
                        return;
                    }
                    this.workspace.settings.references = e.terms;
                    if (!this.containsMatches(this.editor1, e.terms)) {
                        return;
                    }
                    let matches = this.findMatches(this.editor1, e.terms);
                    matches.forEach(match => {
                        this.workspace.memos.addReferenceMemo({
                            row: match.number,
                            text: match.terms.join(",")
                        });
                    });
                    this.workspace.memos.render();
                }
                findMatches(editor, terms) {
                    let results = [];
                    let matches = {};
                    let content = editor.content.getValue().toLowerCase();
                    content.split("\n").forEach((line, index) => {
                        terms.forEach(term => {
                            if (line.indexOf(`name="${term.toLowerCase()}"`) > -1) {
                                if (matches[index] == undefined) {
                                    matches[index] = { number: index, terms: [] };
                                }
                                matches[index].terms.push(term);
                            }
                        });
                    });
                    for (let name in matches) {
                        results.push(matches[name]);
                    }
                    return results;
                }
                containsMatches(editor, terms) {
                    let content = editor.content.getValue().toLowerCase();
                    return terms.find(term => content.indexOf(term.toLowerCase()) > 0) != null;
                }
            }
            Coding.HighlightReferencesOperation = HighlightReferencesOperation;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceContent extends Coding.CodeWorkspaceExtension {
                setValue(content, options = {}) {
                    this.editor1.content.setValue(content, options);
                    if (this.workspace.settings.inMirrorMode) {
                        this.editor2.content.setValue(content, options);
                    }
                }
            }
            Coding.CodeWorkspaceContent = CodeWorkspaceContent;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceMemos extends Coding.CodeWorkspaceExtension {
                addErrorMemo(error) {
                    this.editor1.memos.addErrorMemo(error);
                    if (this.editor2.memos.canMemoize) {
                        this.editor2.memos.addErrorMemo(error);
                    }
                }
                addInfoMemo(info) {
                    this.editor1.memos.addInfoMemo(info);
                    if (this.editor2.memos.canMemoize) {
                        this.editor2.memos.addInfoMemo(info);
                    }
                }
                addReferenceMemo(reference) {
                    this.editor1.memos.addReferenceMemo(reference);
                    if (this.editor2.memos.canMemoize) {
                        this.editor2.memos.addReferenceMemo(reference);
                    }
                }
                addWarningMemo(warning) {
                    this.editor1.memos.addWarningMemo(warning);
                    if (this.editor2.memos.canMemoize) {
                        this.editor2.memos.addWarningMemo(warning);
                    }
                }
                clear() {
                    this.editor1.memos.clear();
                    this.editor2.memos.clear();
                }
                clearErrors() {
                    this.editor1.memos.clearErrors();
                    this.editor2.memos.clearErrors();
                }
                clearInfos() {
                    this.editor1.memos.clearInfos();
                    this.editor2.memos.clearInfos();
                }
                clearRefs() {
                    this.editor1.memos.clearRefs();
                    this.editor2.memos.clearRefs();
                }
                clearWarns() {
                    this.editor1.memos.clearWarns();
                    this.editor2.memos.clearWarns();
                }
                render() {
                    this.editor1.memos.render();
                    this.editor2.memos.render();
                }
                sync() {
                    this.editor2.memos.sync(this.editor1);
                }
            }
            Coding.CodeWorkspaceMemos = CodeWorkspaceMemos;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceOperations extends Coding.CodeWorkspaceExtension {
                get operations() {
                    this.ensureOperations();
                    return this.m_operations;
                }
                highlightReferences(terms = null) {
                    let operation = this.getByType(Coding.HighlightReferencesOperation);
                    if (operation == null) {
                        operation = new Coding.HighlightReferencesOperation({
                            workspace: this.workspace
                        });
                        this.operations.push(operation);
                    }
                    if (terms == null) {
                        terms = this.workspace.settings.references;
                    }
                    operation.execute({
                        terms: terms
                    });
                }
                getByType(type) {
                    return this.operations.find(operation => {
                        return operation instanceof type;
                    });
                }
                ensureOperations() {
                    if (this.m_operations == null) {
                        this.m_operations = [];
                    }
                }
            }
            Coding.CodeWorkspaceOperations = CodeWorkspaceOperations;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            class CodeWorkspaceSettings extends Coding.CodeWorkspaceExtension {
                get orientation() {
                    return this.state.get("orientation", "horizontal");
                }
                set orientation(value) {
                    this.state.set("orientation", value);
                }
                get showErrors() {
                    return this.state.get("showErrors", true);
                }
                set showErrors(value) {
                    this.state.set("showErrors", value);
                }
                get references() {
                    return this.state.get("references", []);
                }
                set references(value) {
                    this.state.set("references", value);
                }
                get showReferences() {
                    return this.state.get("showReferences", true);
                }
                set showReferences(value) {
                    this.state.set("showReferences", value);
                }
                get splitMode() {
                    return this.state.get("splitMode", "single");
                }
                set splitMode(value) {
                    this.state.set("splitMode", value);
                }
                get inMirrorMode() {
                    return this.splitMode === "mirror";
                }
                get inHistoryMode() {
                    return this.splitMode === "history";
                }
                get inSingleMode() {
                    return this.splitMode === "single";
                }
                enterHistoryMode(content, title = "history") {
                    this.splitMode = "history";
                    this.pane2.headerText = title;
                    this.editor2.content.setValue(content, { changed: false });
                    this.editor2.memos.clear();
                    this.editor2.memos.render();
                    this.editor2.content.moveCursorToStart();
                    this.editor2.visible = true;
                    this.pane2.readOnly = true;
                    this.pane2.focus();
                    this.workspace.setCommandState();
                }
                enterMirrorMode() {
                    this.splitMode = "mirror";
                    this.pane2.headerText = "Current";
                    this.editor2.visible = true;
                    this.pane2.readOnly = false;
                    this.pane2.sync(this.workspace.pane1);
                    this.editor2.content.moveCursorToStart();
                    this.pane2.focus();
                    this.workspace.setCommandState();
                }
                enterSingleMode() {
                    this.splitMode = "single";
                    this.pane1.focus();
                    this.workspace.setCommandState();
                }
                hasChanged(property) {
                    return this.state.hasChanged(property);
                }
                onStateChanged() {
                    super.onStateChanged();
                    if (this.hasChanged("orientation")) {
                        this.onOrientationChange();
                    }
                    if (this.hasChanged("splitMode")) {
                        this.onSplitModeChange();
                    }
                }
                onSplitModeChange() {
                    this.workspace.pane2.headerText =
                        !this.inHistoryMode ? "Current" : "History";
                    this.workspace.showPanes(true, !this.inSingleMode);
                }
                onOrientationChange() {
                    this.workspace.pane1.clean();
                    this.workspace.pane2.clean();
                    this.workspace.showPanes(true, true);
                    this.workspace.resize();
                }
            }
            Coding.CodeWorkspaceSettings = CodeWorkspaceSettings;
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class AutoCompleter {
                    constructor(options) {
                        this.m_editor = options.editor;
                        this.state = new Jade.StateBag();
                        this.state.on("change", _.bind(this.onStateChanged, this));
                        this.init();
                    }
                    get ace() {
                        return this.editor.ace;
                    }
                    get content() {
                        return this.editor.content.getValue();
                    }
                    get cursorIndex() {
                        return this.editor.content.cursorIndex;
                    }
                    get editor() {
                        return this.m_editor;
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get state() {
                        return this.m_state;
                    }
                    set state(value) {
                        this.m_state = value;
                    }
                    get trigger() {
                        return this.state.get("trigger");
                    }
                    set trigger(value) {
                        this.state.set("trigger", value);
                    }
                    enableAutoCompletion(enabled) {
                        this.ace.setOptions({
                            enableBasicAutocompletion: enabled,
                            enableLiveAutocompletion: false
                        });
                        enabled ?
                            this.ace.completers = [this.getCompleter()] :
                            this.ace.completers = [];
                        this.init_command(enabled);
                    }
                    getCompleter() {
                        let completer = {
                            getCompletions: (editor, session, pos, prefix, callback) => {
                                new AutoComplete.Resolver().resolve((data) => {
                                    data.forEach(item => {
                                        item.completer = completer;
                                    });
                                    callback(null, data);
                                }, editor.getValue(), this.editor.content.cursorIndex, this.trigger);
                            },
                            insertMatch: (editor, data) => {
                                let isAttributeValueTrigger = this.trigger == "value->advance" ||
                                    this.trigger == "=" ||
                                    this.trigger == `"`;
                                if (isAttributeValueTrigger) {
                                    this.insertAttributeValue(data);
                                    return;
                                }
                                let isAttributeTrigger = this.trigger == " ";
                                if (isAttributeTrigger) {
                                    this.insertAttribute(data);
                                    return;
                                }
                                if (this.trigger == "<") {
                                    this.insertElement(data);
                                    return;
                                }
                                this.insertMatch({ value: data.value });
                            },
                            filter: (e) => {
                                e.filtered = e.filtered.filter(item => {
                                    return item.value.toLowerCase().indexOf(e.filterText.toLowerCase()) > -1;
                                });
                            }
                        };
                        return completer;
                    }
                    init() {
                        ace.require("ace/ext/language_tools");
                        this.enableAutoCompletion(true);
                    }
                    onStateChanged() {
                        if (this.state.hasChanged("enabled")) {
                            this.enableAutoCompletion(this.enabled);
                        }
                    }
                    init_command(enabled) {
                        if (this.m_commandHandler == null) {
                            this.m_commandHandler = (e) => {
                                if (e.command.name !== "insertstring") {
                                    return;
                                }
                                let triggered = e.args === "<" ||
                                    e.args === " " ||
                                    e.args === "=" ||
                                    e.args === `"`;
                                if (!triggered || !AutoComplete.Inspect.isWithinElement(this.content, this.cursorIndex)) {
                                    return;
                                }
                                this.trigger = e.args;
                                this.ace.execCommand("startAutocomplete", e.args);
                            };
                        }
                        enabled ?
                            this.ace.commands.on("afterExec", this.m_commandHandler) :
                            this.ace.commands.off("afterExec", this.m_commandHandler);
                    }
                    insertAttributeValue(data) {
                        if (this.trigger == "value->advance") {
                            this.insertMatch({ value: data.value }, 1);
                            return;
                        }
                        if (this.trigger == `"`) {
                            this.insertMatch({ value: `${data.value}` }, 1);
                            return;
                        }
                        if (this.trigger == "=") {
                            this.insertMatch({ value: `"${data.value}"` });
                            return;
                        }
                    }
                    insertAttribute(data) {
                        if (this.trigger == " ") {
                            this.insertMatch({ value: `${data.value}=""` }, -1);
                            this.trigger = "value->advance";
                            this.ace.execCommand("startAutocomplete", this.trigger);
                            return;
                        }
                    }
                    insertElement(data) {
                        if (data.terminates) {
                            this.insertMatch({ value: `${data.value}/>` });
                            return;
                        }
                        this.insertMatch({
                            value: data.value
                        });
                    }
                    insertMatch(match, cursorPosition = null) {
                        let ace = this.ace;
                        if (ace.completer.completions == null) {
                            ace.completer.completions = [];
                        }
                        ace.completer.insertMatch(match);
                        this.trigger = null;
                        if (cursorPosition) {
                            let position = this.ace.getCursorPosition();
                            position.column += cursorPosition;
                            this.ace.moveCursorToPosition(position);
                        }
                    }
                }
                AutoComplete.AutoCompleter = AutoCompleter;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Completer {
                    getCompletions(editor, session, position, prefix, callback) {
                    }
                    insertMatch(editor, data) {
                    }
                }
                AutoComplete.Completer = Completer;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Extractor {
                    get cursorPlacholder() {
                        return `�|�`;
                    }
                    insertCursorPlacholder(content, index) {
                        return `${content.slice(0, index)}${this.cursorPlacholder}${content.slice(index)}`;
                    }
                    removeCursorPlacholder(content) {
                        return content.replace(this.cursorPlacholder, "");
                    }
                }
                AutoComplete.Extractor = Extractor;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class AttributeExtractor extends AutoComplete.Extractor {
                    extract(options) {
                        let result = this.getTextLeftOfCursor(options.content, options.index);
                        let beginIndex = result.lastIndexOf(` `);
                        result = result.slice(beginIndex);
                        let closeIndex = result.lastIndexOf(`="`);
                        result = result.slice(0, closeIndex);
                        return Jade.String.isNullOrWhiteSpace(result) ? null : result.trim();
                    }
                    getTextLeftOfCursor(content, index) {
                        let targetText = content.slice(0, index);
                        let elementStartIndex = targetText.indexOf("<");
                        return elementStartIndex > -1 ?
                            targetText.slice(elementStartIndex) : targetText;
                    }
                    getTextRightOfCursor(content, index) {
                        let targetText = content.slice(0, index);
                        let elementEndIndex = targetText.indexOf(">");
                        return elementEndIndex > -1 ?
                            targetText.slice(0, elementEndIndex) : targetText;
                    }
                }
                AutoComplete.AttributeExtractor = AttributeExtractor;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class AttributesExtractor extends AutoComplete.Extractor {
                    get endChar() {
                        return this.m_endChar || ">";
                    }
                    set endChar(value) {
                        this.m_endChar = value;
                    }
                    get endMax() {
                        return this.m_endMax || 500;
                    }
                    set endMax(value) {
                        this.m_endMax = value;
                    }
                    get startChar() {
                        return this.m_startChar || "<";
                    }
                    set startChar(value) {
                        this.m_startChar = value;
                    }
                    get startMax() {
                        return this.m_startMax || 500;
                    }
                    set startMax(value) {
                        this.m_startMax = value;
                    }
                    extract(options) {
                        this.setParameters(options);
                        let startPart = this.getStartPart(options.content, options.index);
                        let endPart = this.getEndPart(options.content, options.index);
                        return this.getAttributes(`${startPart}${endPart}`);
                    }
                    getStartPart(content, index) {
                        let maxExceedsContent = index - this.startMax < 0;
                        let result = maxExceedsContent ?
                            content.slice(0, index) :
                            content.slice(index - this.startMax, index);
                        let startCharIndex = result.lastIndexOf(this.startChar);
                        let endCharIndex = result.lastIndexOf(this.endChar);
                        let charIndex = startCharIndex > endCharIndex ?
                            startCharIndex : endCharIndex;
                        return charIndex > -1 ?
                            result.slice(charIndex) : result;
                    }
                    getEndPart(content, index) {
                        let maxExceedsContent = index + this.endMax > content.length;
                        let result = maxExceedsContent ?
                            content.slice(index, content.length) :
                            content.slice(index, index + this.endMax);
                        let startCharIndex = result.indexOf(this.startChar);
                        let endCharIndex = result.indexOf(this.endChar);
                        let charIndex = startCharIndex < endCharIndex ?
                            startCharIndex : endCharIndex;
                        return charIndex > -1 ?
                            result.slice(0, charIndex) : result;
                    }
                    setParameters(options) {
                        this.endChar = options.endChar || ">";
                        this.endMax = options.endMax || 500;
                        this.startChar = options.startChar || "<";
                        this.startMax = options.startMax || 500;
                    }
                    ;
                    getAttributes(content) {
                        let result = {};
                        let regexp = new RegExp(/\s+(([\w\-]+)=+"{1}([^"]*)"{1})/gi);
                        let item = undefined;
                        while ((item = regexp.exec(content)) !== null) {
                            result[item[2]] = item[3];
                        }
                        return result;
                    }
                }
                AutoComplete.AttributesExtractor = AttributesExtractor;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class ElementExtractor extends AutoComplete.Extractor {
                    get content() {
                        return this.m_content;
                    }
                    set content(value) {
                        this.m_content = value;
                    }
                    get position() {
                        return this.m_position;
                    }
                    set position(value) {
                        this.m_position = value;
                    }
                    extract(options) {
                        this.setParameters(options);
                        let openTagPosition = this.content.lastIndexOf("<");
                        let closeTagPosition = this.content.lastIndexOf(">");
                        if (openTagPosition < closeTagPosition) {
                            return null;
                        }
                        let sample = this.content.substring(openTagPosition + 1, this.content.length);
                        let name = sample.substring(0, sample.indexOf(" "));
                        return !Jade.String.isNullOrWhiteSpace(name) ? name : null;
                    }
                    setParameters(options) {
                        this.position = options.position;
                        this.content = options.content.slice(0, options.position);
                        this.content = this.content
                            .replace(/\n/g, " ")
                            .replace(/\t/g, " ")
                            .replace(/\s/g, " ");
                    }
                }
                AutoComplete.ElementExtractor = ElementExtractor;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class ElementsExtractor extends AutoComplete.Extractor {
                    get content() {
                        return this.m_content;
                    }
                    set content(value) {
                        this.m_content = value;
                    }
                    get position() {
                        return this.m_position;
                    }
                    set position(value) {
                        this.m_position = value;
                    }
                    extract(options) {
                        this.setParameters(options);
                        return this.getElementTagPath() || [];
                    }
                    setParameters(options) {
                        this.position = options.position;
                        this.content = options.content.slice(0, options.position);
                        this.content = this.content
                            .replace(/\n/g, " ")
                            .replace(/\t/g, " ")
                            .replace(/\s/g, " ");
                    }
                    getElementTagPath() {
                        let results = [];
                        let extracted = this.content.slice(0, this.content.lastIndexOf(" "));
                        extracted = this.reduceWhiteSpace(extracted);
                        extracted = this.removeAttributes(extracted);
                        extracted = AutoComplete.Sanitizer.removeCDATA(extracted);
                        extracted = AutoComplete.Sanitizer.removeComments(extracted);
                        extracted = this.removeMissedAttributes(extracted);
                        extracted = extracted.trim();
                        extracted = extracted.startsWith("<") ?
                            extracted.slice(1) : extracted;
                        extracted = extracted.endsWith(">") ?
                            extracted.slice(0, extracted.lastIndexOf(">")) : extracted;
                        extracted = this.reduceWhiteSpace(extracted);
                        extracted = this.removeElementBeginAndEnd(extracted);
                        extracted = this.fixOrphanedForwardSlashes(extracted);
                        let lastClosingTagIndex = extracted.lastIndexOf(">");
                        if (lastClosingTagIndex > -1) {
                            extracted = extracted.slice(0, lastClosingTagIndex);
                        }
                        extracted = this.reduceWhiteSpace(extracted);
                        extracted = this.removeSelfTerminatingElements(extracted);
                        extracted = extracted.trim();
                        if (Jade.String.isNullOrWhiteSpace(extracted)) {
                            return [];
                        }
                        let elements = extracted.split(" ").reverse();
                        let minDepth = 0;
                        let curDepth = 0;
                        elements.forEach((element, index) => {
                            let closing = element.startsWith("/");
                            let newDepth = curDepth + (closing ? 1 : -1);
                            if (newDepth < minDepth && !closing) {
                                results.push(element);
                                minDepth = newDepth;
                            }
                            ;
                            curDepth = newDepth;
                        });
                        return results.reverse();
                    }
                    fixOrphanedForwardSlashes(value) {
                        return value.replace(/\s{1}\/{1}(\s{1}|$)/g, "/ ");
                    }
                    removeAttributes(value) {
                        return value.replace(/[\S]+="([^"]*)"/gim, "");
                    }
                    removeMissedAttributes(value) {
                        value = value.replace(/".*(?!=")"/gim, "");
                        value = value.replace(/\w*\s*=/gim, "");
                        return value;
                    }
                    removeElementBeginAndEnd(value) {
                        return value.replace(/>([\s\S]*?)</gim, " ");
                    }
                    reduceWhiteSpace(value) {
                        return value.replace(/\s+/gim, " ");
                    }
                    removeSelfTerminatingElements(value) {
                        return value.replace(/([\w\d_-]*)(\/{1})(\W{1}|$)/gim, "");
                    }
                    removeRemainingElementBeginAndEnd(value) {
                        return value.replace(/(<|>)/gim, "");
                    }
                }
                AutoComplete.ElementsExtractor = ElementsExtractor;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class File {
                    constructor(file) {
                        this.file = JSON.parse(file);
                    }
                    get file() {
                        return this.m_file;
                    }
                    set file(value) {
                        this.m_file = value;
                    }
                    get templates() {
                        return this.m_templates;
                    }
                    set templates(value) {
                        this.m_templates = value;
                    }
                    parse() {
                        this.templates =
                            new AutoComplete.FileTemplates(this.file);
                        this.templates.parse();
                        let elements = new AutoComplete.FileElements(this.file);
                        elements.parse();
                        delete this.file.templates;
                        return this.file;
                    }
                }
                AutoComplete.File = File;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class FileElements {
                    constructor(file) {
                        this.file = file;
                    }
                    get file() {
                        return this.m_file;
                    }
                    set file(value) {
                        this.m_file = value;
                    }
                    get elements() {
                        var _a;
                        return ((_a = this.m_file) === null || _a === void 0 ? void 0 : _a.elements) || [];
                    }
                    get templates() {
                        var _a;
                        return ((_a = this.m_file) === null || _a === void 0 ? void 0 : _a.templates) || {};
                    }
                    parse() {
                        this.checkForDuplicateNames();
                        this.elements.forEach(element => {
                            this.resolveElement(element);
                        });
                    }
                    checkForDuplicateNames() {
                        let names = [];
                        this.elements.forEach(element => {
                            if (names.indexOf(element.name) > -1) {
                                throw `Duplicate element name "${element.name}".`;
                            }
                            names.push(element.name);
                        });
                    }
                    resolveElement(element) {
                        if (!element) {
                            return;
                        }
                        this.resolveElementImports(element);
                        this.resolveAttributesImports(element);
                        this.inheritMetaAndLink(element, element.attributes);
                        element.attributes = element.attributes || [];
                        element.attributes.forEach(attribute => {
                            this.resolveAttribute(attribute);
                        });
                        this.inheritMetaAndLink(element, element.elements);
                        element.elements = element.elements || [];
                        element.elements.forEach(childElement => {
                            this.resolveElement(childElement);
                        });
                    }
                    resolveElementImport(element, importId) {
                        let imported = this.templates.elements[importId];
                        if (imported) {
                            let found = false;
                            imported = _.merge({}, imported);
                            imported.link = imported.link || element.link;
                            imported.meta = imported.meta || element.meta;
                            element.elements = element.elements || [];
                            element.elements.forEach((item, index) => {
                                if (item.name == imported.name && !found) {
                                    element.elements[index] = _.merge({}, imported, item);
                                    found = true;
                                }
                            });
                            if (!found) {
                                element.elements.push(imported);
                            }
                        }
                    }
                    resolveElementImports(element) {
                        element.imports = element.imports || [];
                        let resolved = [];
                        element.imports.forEach(importId => {
                            if (importId.startsWith("$")) {
                                this.resolveElementImport(element, importId.replace("$", ""));
                                resolved.push(importId);
                            }
                        });
                        element.imports = element.imports.filter(importId => {
                            return !importId.startsWith("$");
                        });
                    }
                    resolveAttribute(attribute) {
                        if (!attribute) {
                            return;
                        }
                        this.resolveAttributeValueImports(attribute);
                        this.inheritMetaAndLink(attribute, attribute.values);
                    }
                    resolveAttributesImport(element, importId) {
                        let imported = this.templates.attributes[importId];
                        if (!imported) {
                            return;
                        }
                        let found = false;
                        imported = _.merge({}, imported);
                        element.attributes = element.attributes || [];
                        element.attributes.forEach((item, index) => {
                            if (item.name == imported.name) {
                                element.attributes[index] = _.merge({}, imported, item);
                                found = true;
                            }
                        });
                        if (!found) {
                            element.attributes.push(imported);
                        }
                    }
                    resolveAttributesImports(element) {
                        element.imports = element.imports || [];
                        element.imports.forEach(importId => {
                            if (importId.startsWith("@")) {
                                this.resolveAttributesImport(element, importId.replace("@", ""));
                            }
                        });
                        element.imports = element.imports.filter(item => {
                            return !item.startsWith("@");
                        });
                    }
                    resolveAttributeValueImport(attribute, importId) {
                        let imported = this.templates.values[importId];
                        if (!imported) {
                            return;
                        }
                        let found = false;
                        imported = _.merge({}, imported);
                        attribute.values = attribute.values || [];
                        attribute.values.forEach((item, index) => {
                            if (item.name == imported.name) {
                                attribute.values[index] = _.merge({}, imported, item);
                                found = true;
                            }
                        });
                        if (!found) {
                            attribute.values.push(imported);
                        }
                    }
                    resolveAttributeValueImports(attribute) {
                        attribute.imports = attribute.imports || [];
                        attribute.imports.forEach(importId => {
                            this.resolveAttributeValueImport(attribute, importId);
                        });
                    }
                    inheritMetaAndLink(src, items) {
                        (items || []).forEach(dst => {
                            dst.link = dst.link || src.link;
                            dst.meta = dst.meta || src.meta;
                        });
                    }
                }
                AutoComplete.FileElements = FileElements;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class FileTemplates {
                    constructor(file) {
                        this.file = file;
                        this.m_dependencies = new AutoComplete.FileTemplatesDependencies(this.file);
                    }
                    get file() {
                        return this.m_file;
                    }
                    set file(value) {
                        this.m_file = value;
                    }
                    get templates() {
                        var _a;
                        return ((_a = this.file) === null || _a === void 0 ? void 0 : _a.templates) || {};
                    }
                    get attributes() {
                        var _a;
                        return ((_a = this.templates) === null || _a === void 0 ? void 0 : _a.attributes) || {};
                    }
                    get elements() {
                        var _a;
                        return ((_a = this.templates) === null || _a === void 0 ? void 0 : _a.elements) || {};
                    }
                    get values() {
                        var _a;
                        return ((_a = this.templates) === null || _a === void 0 ? void 0 : _a.values) || {};
                    }
                    get dependencies() {
                        return this.m_dependencies;
                    }
                    parse() {
                        for (let key in this.attributes) {
                            this.resolveAttributeValueTemplates(this.attributes[key]);
                        }
                        for (let key in this.elements) {
                            this.resolveAttributeTemplates(this.elements[key]);
                        }
                        this.dependencies.parse((keys) => {
                            keys.forEach(key => {
                                this.resolveElementTemplates(this.elements[key]);
                            });
                        });
                    }
                    resolveElementTemplate(element, importId, path = []) {
                        if (path.indexOf(importId) > -1) {
                            return;
                        }
                        let imported = this.elements[importId];
                        if (imported) {
                            let found = false;
                            imported = _.merge({}, imported);
                            element.elements = element.elements || [];
                            element.elements.forEach((item, index) => {
                                if (item.name == imported.name && !found) {
                                    element.elements[index] = _.merge({}, imported, item);
                                    found = true;
                                }
                            });
                            this.inheritMetaAndLink(element, element.attributes);
                            element.attributes.forEach(attribute => {
                                this.inheritMetaAndLink(attribute, attribute.values);
                            });
                            element.elements.push(imported);
                        }
                    }
                    resolveElementTemplates(target, path = []) {
                        let element = _.isString(target) ?
                            this.elements[target] : target;
                        if (_.isString(target)) {
                            if (path.indexOf(target) > -1) {
                                return;
                            }
                        }
                        if (element.imports) {
                            let resolved = [];
                            element.imports.forEach(importId => {
                                if (importId.startsWith("$")) {
                                    this.resolveElementTemplate(element, importId.replace("$", ""));
                                    resolved.push(importId);
                                }
                            });
                            element.imports = element.imports.filter(importId => {
                                return importId.startsWith("#") ||
                                    resolved.indexOf(importId.replace("$", "")) > 0;
                            });
                        }
                        if (element.elements) {
                            element.elements.forEach(childElement => {
                                this.resolveElementTemplates(childElement, path);
                            });
                        }
                    }
                    resolveAttributeTemplate(element, importId) {
                        let imported = this.attributes[importId];
                        if (imported) {
                            let found = false;
                            imported = _.merge({}, imported);
                            element.attributes = element.attributes || [];
                            element.attributes.forEach((item, index) => {
                                if (item.name == imported.name) {
                                    element.attributes[index] = _.merge({}, imported, item);
                                    found = true;
                                }
                            });
                            if (!found) {
                                element.attributes.push(imported);
                            }
                        }
                    }
                    resolveAttributeTemplates(element) {
                        if (element.imports) {
                            element.imports.forEach(importId => {
                                if (importId.startsWith("@")) {
                                    this.resolveAttributeTemplate(element, importId.replace("@", ""));
                                }
                            });
                            element.imports = element.imports.filter(item => {
                                return !item.startsWith("@");
                            });
                        }
                        if (element.elements) {
                            element.elements.forEach(childElement => {
                                this.resolveAttributeTemplates(childElement);
                            });
                        }
                    }
                    resolveAttributeValueTemplate(attribute, importId) {
                        let imported = this.values[importId];
                        if (imported) {
                            let found = false;
                            imported = _.merge({}, imported);
                            attribute.values = attribute.values || [];
                            attribute.values.forEach((item, index) => {
                                if (item.name == imported.name) {
                                    attribute.values[index] = _.merge({}, imported, item);
                                    found = true;
                                }
                            });
                            if (!found) {
                                attribute.values.push(imported);
                            }
                        }
                    }
                    resolveAttributeValueTemplates(attribute) {
                        if (attribute.imports) {
                            attribute.imports.forEach(importId => {
                                this.resolveAttributeValueTemplate(attribute, importId);
                            });
                            delete attribute.imports;
                        }
                    }
                    inheritMetaAndLink(src, items) {
                        (items || []).forEach(dst => {
                            dst.link = dst.link || src.link;
                            dst.meta = dst.meta || src.meta;
                        });
                    }
                }
                AutoComplete.FileTemplates = FileTemplates;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class FileTemplatesDependencies {
                    constructor(file) {
                        this.m_unresolved = {};
                        this.m_resolved = [];
                        this.file = file;
                    }
                    get elements() {
                        var _a;
                        return ((_a = this.templates) === null || _a === void 0 ? void 0 : _a.elements) || {};
                    }
                    get file() {
                        return this.m_file;
                    }
                    set file(value) {
                        this.m_file = value;
                    }
                    get resolved() {
                        return this.m_resolved;
                    }
                    get templates() {
                        var _a;
                        return ((_a = this.file) === null || _a === void 0 ? void 0 : _a.templates) || {};
                    }
                    get unresolved() {
                        return this.m_unresolved;
                    }
                    get hasUnresolvedDependencies() {
                        return Object.keys(this.unresolved).length > 0;
                    }
                    parse(resolver) {
                        this.createDependenciesList();
                        do {
                            resolver(this.resolveDependencies());
                        } while (this.hasUnresolvedDependencies);
                        return this.resolved;
                    }
                    createDependenciesList() {
                        let options = {
                            dependencies: []
                        };
                        for (let key in this.templates.elements) {
                            this.getElementDependencies(key, options);
                            this.unresolved[key] = Array.from(new Set(options.dependencies));
                            options = { dependencies: [] };
                        }
                    }
                    resolveDependencies() {
                        let targets = [];
                        for (let key in this.unresolved) {
                            if (this.unresolved[key].length == 0) {
                                targets.push(key);
                            }
                        }
                        targets.forEach(importId => {
                            this.resolved.push(importId);
                            delete this.unresolved[importId];
                        });
                        for (let key in this.unresolved) {
                            let entries = this.unresolved[key];
                            this.unresolved[key] = entries.filter(entry => targets.indexOf(entry) == -1);
                        }
                        return targets;
                    }
                    getElementDependencies(key, e = {}) {
                        var _a, _b;
                        this.getElementCircularDependencies(key, e);
                        let element = this.elements[key];
                        if (element == null) {
                            throw `Reference to element template "${key}" could not be resolved.`;
                        }
                        if (((_a = element.imports) === null || _a === void 0 ? void 0 : _a.length) == 0 && ((_b = element.elements) === null || _b === void 0 ? void 0 : _b.length) == 0) {
                            return;
                        }
                        this.getElementImports(element, e);
                        if (element.elements) {
                            element.elements.forEach(childElement => {
                                this.getElementImports(childElement, e);
                            });
                        }
                    }
                    getElementImports(element, e = {}) {
                        let entryPath = e.path.slice(0);
                        if (element.imports) {
                            element.imports.forEach(importId => {
                                if (importId.startsWith("$")) {
                                    importId = importId.replace("$", "");
                                    this.getElementDependencies(importId, e);
                                    e.path = entryPath.slice(0);
                                }
                            });
                        }
                    }
                    getElementCircularDependencies(key, e = {}) {
                        if (e.source === key) {
                            throw `Circular dependency detected: ${e.path.join(" > ")} > ${key}.`;
                        }
                        e.source = e.source || key;
                        e.path = e.path || [];
                        e.path.push(key);
                    }
                }
                AutoComplete.FileTemplatesDependencies = FileTemplatesDependencies;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Manager {
                    static get files() {
                        this.ensureFiles();
                        return this.m_files;
                    }
                    static set files(value) {
                        this.m_files = value;
                    }
                    static get filesCache() {
                        return localStorage.getItem("code:editor:auto-complete");
                    }
                    static set filesCache(value) {
                        localStorage.setItem("code:editor:auto-complete", value);
                    }
                    static load(force = false) {
                        if (this.files != null && this.files.length > 0 && !force) {
                            return;
                        }
                        let service = new PDJS.Services.Rules.RulesService();
                        service.getAutoCompleteFiles({
                            success: (e) => {
                                e.data.forEach(file => {
                                    let parse1 = new AutoComplete.File(file).parse();
                                    let parse2 = new AutoComplete.Parser().parse(JSON.stringify(parse1));
                                    this.files = [];
                                    this.files.push(parse2);
                                    AutoComplete.Store.instance.load(parse2);
                                });
                                this.commitFiles();
                            }
                        });
                    }
                    static commitFiles() {
                        this.filesCache = JSON.stringify(this.files);
                    }
                    static ensureFiles() {
                        if (this.m_files != null) {
                            return;
                        }
                        if (this.filesCache != null) {
                            try {
                                this.m_files = JSON.parse(this.filesCache);
                                this.m_files.forEach(file => {
                                    AutoComplete.Store.instance.load(file);
                                });
                            }
                            catch (ex) {
                                this.m_files = [];
                            }
                        }
                    }
                }
                AutoComplete.Manager = Manager;
                PDJS.Application.onStart(() => {
                    PDJS.ApplicationEventsHub.versionChangedSubscribe(() => {
                        Manager.load(true);
                    });
                    Manager.load();
                });
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Parser {
                    constructor() {
                        this.m_parsed = {};
                        this.m_tags = {};
                    }
                    get file() {
                        return this.m_file;
                    }
                    set file(value) {
                        this.m_file = value;
                    }
                    get parsed() {
                        return this.m_parsed;
                    }
                    get tags() {
                        return this.m_tags;
                    }
                    parse(content) {
                        this.file = JSON.parse(content);
                        let transitioned = {};
                        this.file.elements.forEach(element => {
                            this.transitionElement(transitioned, element);
                        });
                        _.forEach(transitioned, (element) => {
                            this.finalizeElement(element);
                        });
                        return this.parsed;
                    }
                    transitionElement(store, target, path = []) {
                        path = path.slice(0);
                        path.push(target);
                        let parsed;
                        parsed = {
                            name: target.name.toLowerCase(),
                            meta: target.meta,
                            link: target.link,
                            tags: (target.tags || []).map(tag => tag.toLowerCase()),
                            path: path.map(parent => parent.name).join("/").toLowerCase(),
                            html: this.elementToHtml(target),
                            attributes: this.parseAttributes(target),
                            imports: target.imports || [],
                            importsOnly: path.length > 1
                        };
                        store[parsed.path] = parsed;
                        this.addToTagsDictionary(parsed);
                        if (target.elements) {
                            target.elements.forEach(element => {
                                parsed.imports.push(`${parsed.path}/${element.name}`);
                                this.transitionElement(store, element, path);
                            });
                        }
                        return parsed;
                    }
                    finalizeElement(source) {
                        let target = {
                            name: source.name,
                            path: source.path,
                            html: source.html,
                            tags: source.tags,
                            meta: source.meta,
                            attributes: source.attributes,
                            imports: source.imports || []
                        };
                        this.parsed[target.path] = target;
                        this.parseElementImports(source, target);
                        return target;
                    }
                    parseElementImports(source, target) {
                        let sourceImports = source.imports.slice(0);
                        let targetImports = new Set([]);
                        sourceImports.forEach(importId => {
                            if (importId.startsWith("#")) {
                                importId = importId.replace("#", "");
                                let tags = this.tags[importId];
                                if (tags != null) {
                                    tags.forEach(path => {
                                        targetImports.add(path);
                                    });
                                }
                            }
                            else {
                                targetImports.add(importId);
                            }
                        });
                        target.imports = Array.from(targetImports);
                        return true;
                    }
                    parseAttribute(target) {
                        return {
                            required: target.required,
                            name: target.name,
                            html: this.attributeToHtml(target),
                            meta: target.required ? "required" : null,
                            values: this.parseAttributeValues(target)
                        };
                    }
                    parseAttributes(target) {
                        let result = [];
                        if (target.attributes) {
                            target.attributes.forEach(attribute => {
                                result.push(this.parseAttribute(attribute));
                            });
                        }
                        return result;
                    }
                    parseAttributeValue(target) {
                        return {
                            name: target.name,
                            html: this.attributeValueToHtml(target),
                            meta: target.default ? "default" : null
                        };
                    }
                    parseAttributeValues(target) {
                        let result = [];
                        if (target.values) {
                            target.values.forEach(attribute => {
                                result.push(this.parseAttributeValue(attribute));
                            });
                        }
                        return result;
                    }
                    elementToHtml(target) {
                        if (!this.hasDocumentation(target, target.attributes)) {
                            return null;
                        }
                        let sorted = target.attributes.sort((a, b) => {
                            let aName = `${a.required ? "_" : ""}${a.name}`;
                            let bName = `${b.required ? "_" : ""}${b.name}`;
                            if (aName < bName) {
                                return -1;
                            }
                            if (aName > bName) {
                                return 1;
                            }
                            return 0;
                        });
                        return this.renderHTML(target, sorted, (item) => {
                            return `<div role="attr">
                            <div role="name" ${item.required ? `style="color:darkred;"` : ""}>@${item.name} ${item.required ? "<i>(required)</i>" : ""}</div>
                            <div role="desc">${item.desc || ""}</div>
                        </div>`;
                        });
                    }
                    attributeToHtml(target) {
                        if (!this.hasDocumentation(target, target.values)) {
                            return null;
                        }
                        return this.renderHTML(target, target.values, (item) => {
                            return `<div role="value">
                            <div role="name">${item.name}</div>
                            <div role="desc">${item.desc || ""}</div>
                        </div>`;
                        });
                    }
                    attributeValueToHtml(target) {
                        return this.renderHTML(target);
                    }
                    renderHTML(target, items = [], fn = () => { return null; }) {
                        let hasAttr = items != null && items.length > 0;
                        let hasDesc = !Jade.String.isNullOrWhiteSpace(target.desc);
                        let hasLink = !Jade.String.isNullOrWhiteSpace(target.link);
                        let rows = ["max-content"];
                        hasDesc ? rows.push("auto") : null;
                        hasAttr ? rows.push("max-content") : null;
                        hasLink ? rows.push("max-content") : null;
                        let html = [`<div role="name">${target.name}</div>`];
                        hasDesc ? html.push(`<div role="desc">${target.desc}</div>`) : null;
                        hasAttr ? html.push(`<div role="items">${items.map(item => fn(item)).join("")}</div>`) : null;
                        hasLink ? html.push(`<div role="link"><a href="${this.file.baseUrl}${target.link}" target="_blank">More...</a></div>`) : null;
                        return `<div class="-pdjs-shared-ui-controls-code-editor-auto-complete" style="grid-template-rows: ${rows.join(" ")}">
                        ${html.join("")}
                    </div>`;
                    }
                    hasDocumentation(target, items = []) {
                        return (items != null && items.length > 0)
                            || !Jade.String.isNullOrWhiteSpace(target.desc)
                            || !Jade.String.isNullOrWhiteSpace(target.link);
                    }
                    addToTagsDictionary(element) {
                        element.tags.forEach(tag => {
                            let entry = this.tags[tag];
                            if (entry === undefined) {
                                entry = this.tags[tag] = [];
                            }
                            entry.push(element.path);
                        });
                    }
                }
                AutoComplete.Parser = Parser;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class AttributesResolver {
                    resolve(content, position, success) {
                        let elementName = this.getElementName(content, position);
                        if (elementName) {
                            success(this.resolveAttributes(elementName, content, position));
                        }
                    }
                    getElementName(content, position) {
                        let path = new AutoComplete.ElementsExtractor().extract({
                            content: content,
                            position: position
                        });
                        let element = AutoComplete.Store.instance.getElementByPath(path);
                        return element === null || element === void 0 ? void 0 : element.path;
                    }
                    resolveAttributes(tagName, content, position) {
                        let attributes = AutoComplete.Store.instance.findAttributes(tagName);
                        if (attributes.length == 0) {
                            return [];
                        }
                        let extracted = new AutoComplete.AttributesExtractor().extract({
                            content: content,
                            index: position
                        });
                        let existingAttributes = attributes
                            .filter(item => {
                            return extracted[item.name] === undefined;
                        })
                            .map(item => {
                            return {
                                meta: item.meta,
                                docHTML: item.html,
                                score: 1,
                                value: item.name
                            };
                        });
                        return existingAttributes;
                    }
                }
                AutoComplete.AttributesResolver = AttributesResolver;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class AttributesValuesResolver {
                    resolve(content, position, success) {
                        let elementName = this.getElementName(content, position);
                        if (!elementName) {
                            return;
                        }
                        let attributeName = this.getAttributeName(elementName, content, position);
                        if (attributeName) {
                            success(this.resolveAttributeValues(elementName, attributeName));
                        }
                    }
                    getAttributeName(elementName, content, position) {
                        if (elementName == null) {
                            return null;
                        }
                        return new AutoComplete.AttributeExtractor().extract({
                            content: content,
                            index: position
                        });
                    }
                    getElementName(content, position) {
                        let path = new AutoComplete.ElementsExtractor().extract({
                            content: content,
                            position: position
                        });
                        let element = AutoComplete.Store.instance.getElementByPath(path);
                        return element === null || element === void 0 ? void 0 : element.path;
                    }
                    resolveAttributeValues(elementName, attributeName) {
                        return AutoComplete.Store.instance.findAttributeValues(elementName, attributeName).map(item => {
                            return {
                                value: item.name,
                                score: 1,
                                meta: item.meta,
                                docHTML: item.html
                            };
                        });
                    }
                }
                AutoComplete.AttributesValuesResolver = AttributesValuesResolver;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class ElementsResolver {
                    resolve(content, position, success) {
                        let path = new AutoComplete.ElementsExtractor().extract({
                            content: content,
                            position: position
                        });
                        if (path.length == 0) {
                            success([{
                                    score: 1,
                                    value: "rules"
                                }]);
                            return;
                        }
                        let result = AutoComplete.Store.instance.findElementsByPath(path)
                            .map(item => {
                            return {
                                meta: item.meta,
                                terminates: item.terminates,
                                score: 1 + item.path.split("/").length,
                                docHTML: item.html,
                                value: item.name
                            };
                        });
                        success(result);
                    }
                }
                AutoComplete.ElementsResolver = ElementsResolver;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Resolver {
                    resolve(success, content, position, trigger) {
                        if (trigger === "<") {
                            new AutoComplete.ElementsResolver().resolve(content, position, (items) => {
                                success(items);
                            });
                            return;
                        }
                        if (trigger === " ") {
                            new AutoComplete.AttributesResolver().resolve(content, position, (items) => {
                                success(items);
                            });
                            return;
                        }
                        if (trigger === `"` || trigger === "value->advance") {
                            new AutoComplete.AttributesValuesResolver().resolve(content, position, (items) => {
                                success(items);
                            });
                            return;
                        }
                        let allElements = AutoComplete.Store.instance.list.map(item => {
                            return {
                                meta: item.meta,
                                terminates: item.terminates,
                                score: 1,
                                docHTML: item.html,
                                value: item.name
                            };
                        });
                        success([]);
                    }
                }
                AutoComplete.Resolver = Resolver;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Store {
                    constructor() {
                        this.m_data = {};
                        this.m_list = [];
                    }
                    get data() {
                        return this.m_data;
                    }
                    set data(value) {
                        this.m_data = value;
                    }
                    static get instance() {
                        this.ensureInstance();
                        return this.m_instance;
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    load(data) {
                        for (let key in data) {
                            this.data[key] = data[key];
                            this.list.push(data[key]);
                        }
                    }
                    getElementByPath(path) {
                        let result = null;
                        path = path.slice(0);
                        _.times(path.length, (index) => {
                            if (!result) {
                                result = this.data[path.join("/")];
                            }
                            path.shift();
                        });
                        return result;
                    }
                    findElementsByPath(path) {
                        let element = this.getElementByPath(path);
                        if (!element) {
                            return this.list.filter(item => item.path.indexOf("/") == -1);
                        }
                        let imports = this.getImportedElementsByPath(element, path);
                        return imports;
                    }
                    findAttributes(elementPath) {
                        var _a;
                        let element = this.data[elementPath];
                        return ((_a = element === null || element === void 0 ? void 0 : element.attributes) === null || _a === void 0 ? void 0 : _a.length) > 0 ?
                            element.attributes : [];
                    }
                    findAttribute(elementPath, attributeName) {
                        var _a;
                        let element = this.data[elementPath];
                        if (element == null) {
                            return null;
                        }
                        return (_a = element === null || element === void 0 ? void 0 : element.attributes) === null || _a === void 0 ? void 0 : _a.find(attr => attr.name === attributeName);
                    }
                    findAttributeValues(elementPath, attributeName) {
                        var _a;
                        let attribute = this.findAttribute(elementPath, attributeName);
                        return ((_a = attribute === null || attribute === void 0 ? void 0 : attribute.values) === null || _a === void 0 ? void 0 : _a.length) > 0 ? attribute.values : [];
                    }
                    static ensureInstance() {
                        if (!this.m_instance) {
                            this.m_instance = new Store();
                        }
                    }
                    getImportedElementsByPath(element, path) {
                        let result = [];
                        if (!element) {
                            return result;
                        }
                        element.imports.forEach(path => {
                            let imported = this.data[path];
                            if (imported) {
                                result.push(imported);
                            }
                        });
                        return result;
                    }
                }
                AutoComplete.Store = Store;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Inspect {
                    static isWithinElement(content, index) {
                        content = content.slice(0, index);
                        return this.isWithinCode(content, index) &&
                            content.lastIndexOf("<") > content.lastIndexOf("</") &&
                            content.lastIndexOf("<") > content.lastIndexOf(">");
                    }
                    static isWithinComments(content, index) {
                        content = this.textLeftOfCursor(content, index);
                        return content.lastIndexOf("<!--") >
                            content.lastIndexOf("-->");
                    }
                    static isWithinCdata(content, index) {
                        content = this.textLeftOfCursor(content, index).toLowerCase();
                        return content.lastIndexOf("<![cdata[") >
                            content.lastIndexOf("]]>");
                    }
                    static isWithinCode(content, index) {
                        return !this.isWithinComments(content, index)
                            && !this.isWithinCdata(content, index);
                    }
                    static textLeftOfCursor(content, index) {
                        return content.slice(0, index);
                    }
                }
                AutoComplete.Inspect = Inspect;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Coding;
        (function (Coding) {
            var AutoComplete;
            (function (AutoComplete) {
                class Sanitizer {
                    static removeCDATA(value) {
                        return this.replaceBetween(value, "<![CDATA[", "]]>", "");
                    }
                    static removeComments(value) {
                        return this.replaceBetween(value, "<!--", "-->", "");
                    }
                    static replaceBetween(source, start, end, replacement) {
                        do {
                            let srcCased = source.toLowerCase();
                            let sIndex = srcCased.indexOf(start.toLowerCase());
                            let eIndex = srcCased.indexOf(end.toLowerCase());
                            eIndex > -1 ?
                                source = `${source.substring(0, sIndex)}${replacement}${source.substring(eIndex + end.length)}` :
                                source = source.substring(0, source.startIndex);
                        } while (source.indexOf(start) > -1);
                        return source;
                    }
                }
                AutoComplete.Sanitizer = Sanitizer;
            })(AutoComplete = Coding.AutoComplete || (Coding.AutoComplete = {}));
        })(Coding = Shared.Coding || (Shared.Coding = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Colors;
        (function (Colors) {
            class Color {
                static cssVarToColor(cssVariableName) {
                    return getComputedStyle(document.documentElement)
                        .getPropertyValue(cssVariableName.replace("var(", "").replace(")", ""));
                }
                static isThemeColor(color) {
                    return this.isValidColor(color) && Jade.String.startsWith(color, "var", true);
                }
                static isHexColor(value, allowTransparency = false) {
                    let regex = allowTransparency ?
                        new RegExp("^#[a-fA-F0-9]{3,8}|transparent$", "gi") :
                        new RegExp("^#[a-fA-F0-9]{3,8}$", "gi");
                    return (allowTransparency && Jade.String.isNullOrWhiteSpace(value)) || regex.test(value || "");
                }
                static isValidColor(color) {
                    return !Jade.String.isNullOrWhiteSpace(color);
                }
                static getThemeColorByVarRef(varRef) {
                    return _.first(PDJS.Shared.Themes.Theme.colors.filter((color) => {
                        return color.varRef.toLowerCase() === varRef.toLowerCase();
                    }));
                }
            }
            Colors.Color = Color;
        })(Colors = Shared.Colors || (Shared.Colors = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Colors;
        (function (Colors) {
            class ColorPalette extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get colors() {
                    return this.state.get("colors", []);
                }
                set colors(value) {
                    this.state.set("colors", value);
                }
                get columns() {
                    return this.state.get("columns", 10);
                }
                get itemColorNodes() {
                    return this.node.find(".-pdjs-shared-colors-palette-item-color");
                }
                get select() {
                    return this.state.get("select", () => { });
                }
                get targetTheme() {
                    return this.state.get("targetTheme", null);
                }
                template() {
                    return `<div class="-pdjs-shared-colors-palette"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.css({
                        gridTemplateColumns: `repeat(${this.columns}, max-content)`
                    });
                    this.node.on(Jade.BrowserEvent.CLICK, ".-pdjs-shared-colors-palette-item", _.bind(this.item_click, this));
                    this.renderColors();
                    this.applyTargetTheme();
                    this.subscriptions.add(PDJS.Shared.Themes.EventsHub.setThemeSubscribe((e) => {
                        if (e.sourceScope === PDJS.Services.Themes.ThemeScope.Canvas) {
                            this.node.empty();
                            this.renderColors();
                            this.applyTargetTheme();
                        }
                    }));
                }
                renderColors() {
                    this.colors.forEach(color => {
                        this.node.append(`<div  class="-pdjs-shared-colors-palette-item" data-value="${color}">
                                    <div class="-pdjs-shared-colors-palette-item-color" style="background-color:${color};"></div>
                                </div>`);
                    });
                }
                item_click(e) {
                    this.select({
                        color: $(e.currentTarget).data("value")
                    });
                }
                applyTargetTheme() {
                    let themeCss = null;
                    switch (this.targetTheme) {
                        case PDJS.Services.Themes.ThemeScope.Canvas:
                            themeCss = "-theme-canvas";
                            break;
                        case PDJS.Services.Themes.ThemeScope.Designer:
                            themeCss = "-theme-designer";
                            break;
                        case PDJS.Services.Themes.ThemeScope.Hub:
                            themeCss = "-theme-hub";
                            break;
                        case PDJS.Services.Themes.ThemeScope.Manage:
                            themeCss = "-theme-manage";
                            break;
                    }
                    if (themeCss) {
                        this.itemColorNodes.addClass(`${themeCss}`);
                    }
                }
            }
            Colors.ColorPalette = ColorPalette;
        })(Colors = Shared.Colors || (Shared.Colors = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Colors;
        (function (Colors) {
            class ColorPalettes {
                static get standardColors() {
                    return [
                        "var(--visiv-system-black)",
                        "var(--visiv-system-grey)",
                        "var(--visiv-system-white)",
                        "var(--visiv-system-red)",
                        "var(--visiv-system-orange)",
                        "var(--visiv-system-yellow)",
                        "var(--visiv-system-green)",
                        "var(--visiv-system-blue)",
                        "var(--visiv-system-purple)",
                        "var(--visiv-system-violet)"
                    ];
                }
                static get themeColors() {
                    return [];
                }
            }
            Colors.ColorPalettes = ColorPalettes;
        })(Colors = Shared.Colors || (Shared.Colors = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Dialogs;
        (function (Dialogs) {
            class ErrorDialogLauncher {
                static open(options = {}) {
                    if (this.m_dialog != null) {
                        return this.m_dialog;
                    }
                    let errors = PDJS.Shared.ErrorFactory.convert(options.errors);
                    options.errors = errors;
                    let hasTags = errors.find(item => {
                        return !_.isEmpty(item.tags);
                    }) != null;
                    switch (true) {
                        case errors.length === 0:
                            this.m_dialog = this.showCatchAllErrorDialog();
                            break;
                        case errors.length === 1 && !hasTags:
                            this.m_dialog = this.showMessageDialog(options);
                            break;
                        case errors.length > 0 && hasTags:
                            this.m_dialog = this.showTaggedMessageDialog(options);
                            break;
                        case errors.length > 1 && !hasTags:
                            this.m_dialog = this.showMultiMessageDialog(errors);
                            break;
                    }
                    return this.m_dialog;
                }
                static showCatchAllErrorDialog() {
                    return this.showMessageDialog({
                        title: "Application | Errors",
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        errors: [new Shared.Error(`The system is unable to complete your request due to an unspecified error.<br/><br/>
                          Please try the operation again and contact your system administrator if the problem persists.`)]
                    });
                }
                static showMessageDialog(options) {
                    let defaults = {
                        title: "Application | Errors",
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        message: _.first(options.errors).message
                    };
                    let combined = _.extend(defaults, options, {
                        select: _.bind(this.handleDialogSelect, this)
                    });
                    return Jade.UI.Dialogs.MessageDialog.open(combined);
                }
                static showMultiMessageDialog(options) {
                    let defaults = {
                        title: "Application | Errors",
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        messages: options.errors.map(error => error.message),
                        select: (sender) => {
                            this.m_dialog = null;
                            sender.close();
                        }
                    };
                    let combined = _.extend(defaults, options, {
                        select: _.bind(this.handleDialogSelect, this)
                    });
                    return Jade.UI.Dialogs.MultiMessageDialog.open(combined);
                }
                static showTaggedMessageDialog(options) {
                    let defaults = {
                        title: "Application | Errors",
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        messages: options.errors
                    };
                    let combined = _.extend(defaults, options, {
                        select: _.bind(this.handleDialogSelect, this)
                    });
                    return Jade.UI.Dialogs.TaggedMessageDialog.open(combined);
                }
                static handleDialogSelect(sender, e) {
                    this.m_dialog = null;
                    sender.close();
                }
            }
            Dialogs.ErrorDialogLauncher = ErrorDialogLauncher;
        })(Dialogs = Shared.Dialogs || (Shared.Dialogs = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Dialogs;
        (function (Dialogs) {
            class IconBrowserDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get value() {
                    return this.getSelectedValue();
                }
                get grid() {
                    return this.m_grid;
                }
                get gridNode() {
                    return this.node.find("div[role=grid]");
                }
                get headNode() {
                    return this.node.find("div[role=head]");
                }
                get search() {
                    return this.m_search;
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=button-ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=button-cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-shared-icon-browser-dialog">
                    <div role="head"></div>
                    <div>
                        <div role="grid"></div>
                    </div>
                    <div>
                        <button 
                            data-id="button-ok"  
                            class="-jadeui-dialog-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-jadeui-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.search_init();
                    this.grid_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.closeAndReturn();
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.search.focus();
                }
                getDefaultOptions() {
                    return {
                        title: "Icon Selection",
                        height: 500,
                        width: 450,
                        minHeight: 250,
                        minWidth: 250
                    };
                }
                search_init() {
                    this.m_search = new PDJS.Shared.UI.Controls.SearchBox({
                        insertAt: "div[role=head]",
                        onSearch: (e) => {
                            this.grid.dataSource.page(0);
                            this.grid.dataSource.read();
                        }
                    });
                    this.controls.add(this.search);
                }
                grid_init() {
                    this.m_grid = this.gridNode.kendoGrid({
                        height: "100%",
                        sortable: {
                            allowUnsort: false
                        },
                        selectable: "row",
                        dataSource: {
                            serverPaging: true,
                            serverSorting: true,
                            pageSize: 100,
                            transport: {
                                read: {
                                    url: Jade.Path.resolve("~/Shared/Icon/Query"),
                                    data: () => {
                                        return {
                                            term: this.search.textValue
                                        };
                                    }
                                }
                            },
                            schema: {
                                data: "data",
                                total: "totalCount"
                            },
                            sort: {
                                field: "icon",
                                dir: "asc"
                            }
                        },
                        scrollable: {
                            virtual: true
                        },
                        columns: [
                            {
                                field: "icon",
                                title: "Icon",
                                template: (e) => {
                                    let icon = Jade.IconSet.get("pd").resolve(e.icon, Jade.IconSetSizeSpecificDirectory.x16);
                                    return `<div class="-pdjs-shared-icon-browser-dialog-grid-cell" style="background-image:url(${icon});">
                                        ${e.name}
                                    </div>`;
                                },
                                attributes: {
                                    style: "height:24px;position:relative;padding:0;"
                                }
                            }
                        ]
                    }).data("kendoGrid");
                    this.m_grid.content.on(Jade.BrowserEvent.DOUBLECLICK, "TR[role=row]", () => {
                        if (this.value != null) {
                            this.closeAndReturn();
                        }
                    });
                }
                getSelectedValue() {
                    let data = null;
                    let row = this.grid.select();
                    if (row.length > 0) {
                        data = this.grid.dataItem(row);
                    }
                    return data ? data.get("icon") : null;
                }
                closeAndReturn() {
                    this.close({
                        name: "ok",
                        data: {
                            value: this.value
                        }
                    });
                }
                static open(options) {
                    return new IconBrowserDialog(options);
                }
            }
            Dialogs.IconBrowserDialog = IconBrowserDialog;
        })(Dialogs = Shared.Dialogs || (Shared.Dialogs = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Dialogs;
        (function (Dialogs) {
            class UnsavedChangesDialog extends Jade.UI.Dialogs.MultiChoiceDialog {
                static open(e) {
                    return new UnsavedChangesDialog({
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        title: "Unsaved Changes Detected",
                        header: "There are unsaved changes.\n\nHow would you like to proceed?",
                        items: [{
                                title: "Attempt to automatically save the changes and proceed.",
                                message: `The application will attempt to automatically save the changes you have made,
                              if the changes cannot be saved you will be prompted to attempt the save operation manually.`,
                                value: "save",
                                selected: true
                            }, {
                                title: "Discard the changes and proceed.",
                                message: `Any changes you have made will be discarded and the application will continue to execute your request.`,
                                value: "discard"
                            }]
                    });
                }
            }
            Dialogs.UnsavedChangesDialog = UnsavedChangesDialog;
        })(Dialogs = Shared.Dialogs || (Shared.Dialogs = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypeBrowserDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(_.extend(options));
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get filters() {
                    return this.state.get("filters", []);
                }
                get grid() {
                    return this.m_grid;
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get selectionMode() {
                    return this.state.get("selectionMode", PD.Web.UI.Controls.GridSelectionMode.multiple);
                }
                get selections() {
                    return _.map(this.grid.getSelections().toArray(), "id");
                }
                get viewCustomId() {
                    return this.state.get("viewCustomId", PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPES);
                }
                get viewStateId() {
                    return Jade.Application
                        .instance
                        .contexts
                        .global
                        .store
                        .get("DocumentTypeSelectionDialog.viewStateId");
                }
                set viewStateId(value) {
                    Jade.Application
                        .instance
                        .contexts
                        .global
                        .store
                        .set("DocumentTypeSelectionDialog.viewStateId", value);
                }
                template() {
                    return super.template(`<div style="position:absolute;inset:0;box-sizing:border-box;">
                                        <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;"></div>
                                        <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                                            <button data-command="ok" class="-pdjs-dialog-button">OK</button>
                                            <button data-command="cancel" class="-pdjs-dialog-button">Cancel</button>
                                        </div>
                                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.startUp();
                    this.grid_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                }
                getDefaultOptions() {
                    return {
                        title: "Document Type Browser",
                        height: 400,
                        width: 600,
                        maximized: false
                    };
                }
                static open(options) {
                    return new DocumentTypeBrowserDialog(options);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role=grid]"),
                        selectionMode: this.selectionMode,
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId
                                    };
                                });
                            }
                        },
                        dblclick: (e) => {
                            this.closeAndReturn();
                        },
                        needContext: (e) => {
                            _.each(this.filters, (item) => {
                                e.filters[e.filters.length] = item.toJSON();
                            });
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.selections.length > -1) {
                        let documentTypeService = new PDJS.Services.DocumentTypes.DocumentTypeService();
                        documentTypeService.loadDocumentTypes({
                            ids: this.selections,
                            success: (e) => {
                                this.close({
                                    name: "ok",
                                    data: e.data
                                });
                            },
                            error: (e) => {
                                this.close();
                            }
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No document type has been selected. Select a document type and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    if (this.viewStateId == null) {
                        service.getViewStateId({
                            viewCustomId: this.viewCustomId,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                            }
                        });
                    }
                }
            }
            DocumentTypes.DocumentTypeBrowserDialog = DocumentTypeBrowserDialog;
        })(DocumentTypes = Shared.DocumentTypes || (Shared.DocumentTypes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Entities;
    (function (Entities) {
        class EntityCreateResponse extends PDJS.Shared.Rules.ScriptResponseOf {
            handle(e) {
                this.arguments = e;
                if (this.handleScriptErrors()) {
                    return true;
                }
                if (this.handleScriptAlerts()) {
                    return true;
                }
                this.handleDefaultBehavior();
                return true;
            }
            handleScriptAction(action) {
                switch (true) {
                    case action instanceof PDJS.Shared.Rules.ScriptRedirect:
                        this.handleRedirect(action);
                        break;
                    case action instanceof PDJS.Shared.Rules.ScriptPrompt:
                        this.handlePrompt(action);
                        break;
                }
            }
            acknowledgedScriptAlerts(e) {
                e.close();
                this.handleDefaultBehavior();
            }
            acknowledgedScriptErrors(e) {
                e.close();
                this.handleDefaultBehavior();
            }
            promptToExplore() {
                let entityTypeName = this.response.entityTypeName;
                Jade.UI.Dialogs.MessageDialog.open({
                    dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                    dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Success,
                    title: `${entityTypeName} Creation Success`,
                    message: `The new ${entityTypeName} "${this.response.entityName}" was created successfully. Would you like to open it now?`,
                    select: (e) => {
                        e.close();
                        if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                            PDJS.System.Environment.current.profile.preferences.onOpenBehavior == 1 ?
                                this.openInNewWindow() :
                                this.openInCurrentWindow();
                        }
                    }
                });
            }
            toasterToExplore() {
                let url = Jade.Path.resolve(`~/Explore/${this.response.entityId}`);
                let msg = `"${this.response.entityName}" created successfully.<br/> 
                                Click <a href="${url}" target="_blank">here to explore</a>.`;
                PDJS.Shared.MessageStack.instance.success(msg, {});
            }
            openInCurrentWindow() {
                window.location.href = Jade.Path.resolve(`~/Explore/${this.response.entityId}`);
            }
            openInNewWindow() {
                window.open(Jade.Path.resolve(`~/Explore/${this.response.entityId}`));
            }
            handleDefaultBehavior() {
                if (this.handleScriptActions()) {
                    return;
                }
                if (this.arguments.promptToOpen == true) {
                    this.promptToExplore();
                    return;
                }
                if (this.arguments.promptToOpen == false) {
                    this.toasterToExplore();
                    return;
                }
                this.handleProfileBehavior();
            }
            handleProfileBehavior() {
                let createBehavior = PDJS.System.Environment
                    .current.profile.preferences.onCreateBehavior;
                switch (createBehavior) {
                    case 2:
                        this.toasterToExplore();
                        break;
                    default:
                        this.promptToExplore();
                        break;
                }
            }
            handlePrompt(action) {
                if (this.arguments.allowPrompts !== false) {
                    action.handle();
                }
            }
            handleRedirect(action) {
                if (this.arguments.allowRedirects !== false) {
                    action.handle();
                }
            }
        }
        Entities.EntityCreateResponse = EntityCreateResponse;
    })(Entities = PDJS.Entities || (PDJS.Entities = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Entities;
    (function (Entities) {
        class EntityDialogs {
            static showCreate(options) {
                PDJS.Shared.Features.FeatureDialogForNhib.open({
                    height: "500px",
                    width: "680px",
                    args: {
                        arbiterType: "ProspectDirector.Web.Shared.Modules.Entities.EntityDialogArbiter",
                        targetType: "ProspectDirector.Web.Shared.Modules.Entities.EntityDialogUIO",
                        properties: {
                            entityTypeId: options.entityTypeId,
                            parentId: options.parentId ? options.parentId : null
                        }
                    },
                    select: {
                        ok: (sender, e) => {
                            if (_.isFunction(options.onCreate)) {
                                options.onCreate(sender, e);
                            }
                            let response = new Entities.EntityCreateResponse(e.output.scriptResponse);
                            response.handle(options);
                        }
                    }
                });
            }
            static showProperties(options) {
                PDJS.Shared.Features.FeatureDialogForNhib.open({
                    height: "500px",
                    width: "680px",
                    args: {
                        arbiterType: "ProspectDirector.Web.Shared.Modules.Entities.EntityDialogArbiter",
                        targetType: "ProspectDirector.Web.Shared.Modules.Entities.EntityDialogUIO",
                        properties: {
                            entityId: parseInt(options.entityId)
                        }
                    },
                    select: {
                        ok: (sender, e) => {
                            if (_.isFunction(options.onSave)) {
                                options.onSave(sender, e);
                            }
                            let response = new PDJS.Shared.Rules.ScriptResponse(e.output.scriptResponse);
                            response.handle(options);
                        }
                    }
                });
            }
        }
        Entities.EntityDialogs = EntityDialogs;
    })(Entities = PDJS.Entities || (PDJS.Entities = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Entities;
    (function (Entities) {
        class FileDialogs {
            static showProperties(options) {
                PDJS.Shared.Features.FeatureDialogForNhib.open({
                    height: "500px",
                    width: "680px",
                    args: {
                        targetId: options.fileId,
                        arbiterType: "ProspectDirector.Web.Shared.Modules.Files.FilePropertiesDialogArbiter",
                        targetType: "ProspectDirector.Web.Shared.Modules.Files.FilePropertiesDialogUIO"
                    },
                    select: {
                        ok: (sender, e) => {
                            if (_.isFunction(options.onSave)) {
                                options.onSave(sender, e);
                            }
                            let response = new PDJS.Shared.Rules.ScriptResponse(e.output.scriptResponse);
                            response.handle(options);
                        }
                    }
                });
            }
        }
        Entities.FileDialogs = FileDialogs;
    })(Entities = PDJS.Entities || (PDJS.Entities = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Entities;
        (function (Entities) {
            class EntityBrowserDialog extends Jade.UI.Dialogs.DialogOf {
                get filters() {
                    return this.state.get("filters", []);
                }
                set filters(value) {
                    this.state.set("filters", value);
                }
                get dialogTitle() {
                    return this.state.get("dialogTitle", null);
                }
                get dialogMessage() {
                    return this.state.get("dialogMessage", null);
                }
                get messageNode() {
                    return this.node.find("div[role=message]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                set entityTypeId(value) {
                    this.state.set("entityTypeId", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-shared-entity-browser-dialog">
                    <div role="header">
                        <div role="message">${this.dialogMessage}</div>
                    </div>
                    <div role="grid"></div>
                    <div role="buttons">
                        <button data-command="ok" class="-pdjs-dialog-button">OK</button>
                        <button data-command="cancel" class="-pdjs-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.startUp();
                    this.grid_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    this.dialogMessage == null ?
                        this.messageNode.hide() :
                        this.messageNode.show();
                    if (!Jade.String.isNullOrWhiteSpace(this.dialogTitle)) {
                        this.setWindowOptions({
                            title: this.dialogTitle
                        });
                    }
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Entity",
                        height: 400,
                        width: 600,
                        maximized: false
                    };
                }
                static open(options) {
                    return new EntityBrowserDialog(options);
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        entityId: item.ObjectId,
                                        entityName: item.ObjectName,
                                        entityTypeIcon: item.d0_general_TypeIcon,
                                        entityTypeName: item.d0_general_TypeName
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.m_selection = e.selection;
                        },
                        dblclick: (e) => {
                            this.m_selection = e.selection;
                            this.closeAndReturn();
                        },
                        needContext: (e) => {
                            this.filters.forEach((item) => {
                                e.filters[e.filters.length] = item.toJSON();
                            });
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.m_selection != null) {
                        this.close({
                            name: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No entity has been selected. Select a document type and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    if (this.viewStateId == null) {
                        service.getViewStateId({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.PARENT_SELECTION,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                            }
                        });
                    }
                }
            }
            Entities.EntityBrowserDialog = EntityBrowserDialog;
        })(Entities = Shared.Entities || (Shared.Entities = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessControlEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get acl() {
                    return this.m_acl;
                }
                set acl(value) {
                    this.m_acl = value;
                }
                get editor() {
                    return this.m_editor;
                }
                get aces() {
                    return this.feature.getValue("aces");
                }
                set aces(value) {
                    this.feature.setValue("aces", value);
                }
                get permissions() {
                    return this.feature.getValue("permissions");
                }
                get securableId() {
                    return this.feature.getValue("securableId");
                }
                get enabled() {
                    return this.feature.getValue("enabled");
                }
                get isAdvancedAllowed() {
                    return this.feature.getValue("isAdvancedAllowed");
                }
                focus() {
                    super.focus();
                    if (this.m_editor) {
                        this.m_editor.resize();
                    }
                }
                onCreated() {
                    super.onCreated();
                    this.acl = new PDJS.Core.Security.AccessControlList({
                        aces: this.aces,
                        permissions: this.permissions,
                        commit: () => {
                            this.aces = this.acl.aces.toJSON();
                            if (this.m_editor != null) {
                                this.m_editor.aclEditor.refresh();
                            }
                        }
                    });
                }
                onResized() {
                    super.onResized();
                    if (this.m_editor) {
                        this.m_editor.resetSize();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.acl_init();
                }
                onViewResized() {
                    if (this.m_editor != null) {
                        this.m_editor.resize();
                    }
                }
                acl_init() {
                    this.m_editor =
                        new PDJS.Shared.Security.AccessContol({
                            acl: this.acl,
                            readOnly: !this.enabled,
                            securableId: this.securableId,
                            enableAdvanced: this.isAdvancedAllowed,
                            enableEffectivePermissions: this.isAdvancedAllowed
                        });
                    this.controls.add(this.m_editor);
                }
            }
            Security.AccessControlEditor = AccessControlEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Security.AccessControlEditor", AccessControlEditor);
            });
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Entity;
        (function (Entity) {
            const PARENT_CHANGED_EVENT = PDJS.Canvas.Actual.Forms.EntityParentField.PARENT_CHANGED_EVENT;
            class AccessControlEditor extends PDJS.Shared.Security.AccessControlEditor {
                get isCreate() {
                    return this.source.getFeatureValue("isCreate", false);
                }
                onCreated() {
                    super.onCreated();
                    if (this.isCreate) {
                        this.subscribeToParentChangeEvent();
                    }
                }
                parent_onChange(e) {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve("~/Entity/GetSecurity"),
                        data: {
                            entityTypeId: e.entityTypeId,
                            parentId: e.parentId,
                            entityId: this.securableId
                        },
                        success: (e) => {
                            var _a;
                            let aces = ((_a = e === null || e === void 0 ? void 0 : e.acl) === null || _a === void 0 ? void 0 : _a.aces) || [];
                            this.acl.aces.clear();
                            aces.forEach(ace => {
                                this.acl.aces.add(new PDJS.Core.Security.Ace(ace));
                            });
                            this.acl.commit();
                            if (this.editor != null) {
                                this.editor.aclEditor.refresh(true);
                                this.editor.aceEditor.loadAce(null);
                            }
                        }
                    });
                }
                subscribeToParentChangeEvent() {
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(PARENT_CHANGED_EVENT, (e) => {
                        this.parent_onChange(e);
                    }));
                }
            }
            Entity.AccessControlEditor = AccessControlEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Entity.AccessControlEditor", AccessControlEditor);
            });
        })(Entity = Shared.Entity || (Shared.Entity = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Entity;
        (function (Entity) {
            class CanvasEditor extends FeatureBlendJS.Views.MacroEditorBase {
                template() {
                    return `<div class="-pdjs-fb-canvas-editor">
                        <div role="canvas"></div>
                    </div>`;
                }
                blur() {
                    super.blur();
                    this.node.closest(".feature-blend-dialog").find(".-pdjs-feature-dialog-button").removeAttr("tabindex");
                }
                focus() {
                    super.focus();
                    this.node.closest(".feature-blend-dialog").find(".-pdjs-feature-dialog-button").attr("tabindex", "9999");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.canvas_init();
                    this.node.parent().css({
                        inset: 0
                    });
                }
                onValidationErrors() {
                    super.onValidationErrors();
                    let error = _.first(this.source.feature.errors.filter((error) => {
                        return error.tags["canvas-response"] != undefined;
                    }));
                    if (!error) {
                        return;
                    }
                    let validationErrors = error.tags["canvas-response"].validationErrors;
                    PDJS.Canvas.Actual.CanvasRefresh.validate({
                        validationErrors: validationErrors
                    });
                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.error);
                }
                onCommit() {
                    PDJS.Canvas.Actual.CanvasRefresh.validate({
                        validationErrors: {}
                    });
                    this.source.primaryValue = this.m_canvas.getDocumentJSON();
                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.pending);
                }
                canvas_init() {
                    this.m_canvas = new PDJS.Canvas.Actual.CanvasViewBoxOnCreate({
                        insertAt: "div[role=canvas]",
                        documentState: this.source.primaryValue
                    });
                    this.controls.add(this.m_canvas);
                }
            }
            Entity.CanvasEditor = CanvasEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Entity.CanvasEditor", CanvasEditor);
        })(Entity = Shared.Entity || (Shared.Entity = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Entity;
        (function (Entity) {
            class TagsEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get entityTags() {
                    return this.source.getFeatureValue("tags");
                }
                template() {
                    return `<div class="-pdjs-fb-tags-editor">
                        <div role="grid"></div>
                    </div>`;
                }
                focus() {
                    super.focus();
                    if (this.m_grid) {
                        this.m_grid.refresh();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    let data = [];
                    this.entityTags.forEach((value) => {
                        data[data.length] = { tag: value };
                    });
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.node.children("div[role=grid]"),
                        showToolbar: false,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        dataSource: {
                            data: data
                        },
                        messaging: {
                            noRecordsMessage: "No tags."
                        },
                        selectionMode: "none",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "tag",
                                title: "Tag",
                                width: "450px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
            }
            Entity.TagsEditor = TagsEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Entity.TagsEditor", TagsEditor);
        })(Entity = Shared.Entity || (Shared.Entity = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Entity;
        (function (Entity) {
            class AncestorsEditor extends FeatureBlendJS.Views.MicroEditorBase {
                get items() {
                    return this.source.getFeaturePrimaryValue([]);
                }
                template() {
                    return `<div class="-pdjs-fb-ancestors-editor"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.empty();
                    this.items.reverse();
                    this.items.forEach(item => {
                        this.node.append(this.itemTemplate(item));
                    });
                }
                itemTemplate(item) {
                    return `<div role="row">
                        <div><img src="${Jade.IconSet.get("pd").resolve(item.typeIcon, Jade.IconSetSizeSpecificDirectory.x16)}"/></div>
                        <div title="${item.typeName}">${item.name}</div>
                    </div>`;
                }
            }
            Entity.AncestorsEditor = AncestorsEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Entity.AncestorsEditor", AncestorsEditor);
        })(Entity = Shared.Entity || (Shared.Entity = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            class FeatureDialogForElem extends Features.FeatureDialog {
                getRequestData() {
                    return {
                        "initialized": false,
                        "arbiter": {
                            type: "ProspectDirector.Web.UI.Canvas.ElementArbiter",
                            targetType: this.targetType,
                            json: JSON.stringify(this.targetData),
                            attributes: this.attributes,
                            properties: this.properties
                        }
                    };
                }
                static open(options) {
                    return new FeatureDialogForElem(options);
                    ;
                }
            }
            Features.FeatureDialogForElem = FeatureDialogForElem;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            class FeatureDialogForJson extends Features.FeatureDialog {
                getRequestData() {
                    return {
                        "initialized": false,
                        "arbiter": {
                            id: this.targetId,
                            type: this.arbiterType || "ProspectDirector.Web.UI.FeatureSets.JsonArbiter",
                            targetType: this.targetType,
                            json: JSON.stringify(this.targetData),
                            attributes: this.attributes,
                            properties: this.properties
                        }
                    };
                }
                static open(options) {
                    return new FeatureDialogForJson(options);
                    ;
                }
            }
            Features.FeatureDialogForJson = FeatureDialogForJson;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            let LoadMethod;
            (function (LoadMethod) {
                LoadMethod[LoadMethod["LoadWithValidaton"] = 0] = "LoadWithValidaton";
                LoadMethod[LoadMethod["LoadWithoutValidaton"] = 1] = "LoadWithoutValidaton";
            })(LoadMethod = Features.LoadMethod || (Features.LoadMethod = {}));
            class FeatureEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get layoutView() {
                    return this.m_layoutView;
                }
                get layoutType() {
                    return this.state.get("layoutType", FeatureBlendJS.Views.FeatureBlendLayoutType.Tabbed);
                }
                get rootModel() {
                    return this.m_rootModel;
                }
                get targetId() {
                    return this.state.get("targetId");
                }
                get targetData() {
                    return this.state.get("targetData");
                }
                get targetType() {
                    return this.state.get("targetType");
                }
                get arbiterType() {
                    return this.state.get("arbiterType");
                }
                get attributes() {
                    return this.state.get("attributes");
                }
                get properties() {
                    return this.state.get("properties");
                }
                get loadMethod() {
                    return this.state.get("loadMethod", LoadMethod.LoadWithoutValidaton);
                }
                get onLoadErrorCallback() {
                    return this.state.get("onLoadError", () => { });
                }
                get onRequestStartCallback() {
                    return this.state.get("onRequestStart", () => { });
                }
                get onRequestEndCallback() {
                    return this.state.get("onRequestEnd", () => { });
                }
                get onValidationErrorCallback() {
                    return this.state.get("onValidationError", () => { });
                }
                get onCommitSuccessCallback() {
                    return this.state.get("onCommitSuccess", () => { });
                }
                get onFeatureValueChangedCallback() {
                    return this.state.get("onFeatureValueChanged", () => { });
                }
                get onLoadSuccessCallback() {
                    return this.state.get("onLoadSuccess", () => { });
                }
                template() {
                    return `
            <div class="--pdjs-feature-blend-editor">
                <div role="feature"></div>
            </div>`;
                }
                load(args) {
                    this.requestMonitorStart();
                    PDJS.Ajax.call({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: Jade.Path.resolve(this.loadMethod == LoadMethod.LoadWithoutValidaton ?
                            "~/Hub/Target/Edit" : "~/Hub/Target/EditWithValidation"),
                        data: JSON.stringify(args),
                        success: (e) => {
                            this.loadContextIntoLayoutView(e);
                            this.onLoadSuccessCallback(e);
                        },
                        error: (e) => {
                            this.requestMonitorStop();
                            if (this.loadMethod == LoadMethod.LoadWithValidaton) {
                                if (this.isEditorInJsonResponse(e)) {
                                    e.errorHandled = true;
                                    this.loadContextIntoLayoutView(e.responseJSON.editor);
                                }
                            }
                            this.onLoadErrorCallback(e);
                        }
                    });
                }
                reload(validate = false) {
                    var url = !validate ? "~/Target/RefreshNoValidation?NoValidate=1" : "~/Target/Refresh";
                    this.requestMonitorStart();
                    PDJS.Ajax.call({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: Jade.Path.resolve(url),
                        data: JSON.stringify(this.rootModel.context.toJSON()),
                        success: (e) => {
                            this.loadContextIntoLayoutView(e);
                        },
                        error: (e) => {
                            this.onLoadErrorCallback(e);
                        }
                    });
                }
                commit(args = {}) {
                    this.requestMonitorStart();
                    if (!_.isFunction(args.success)) {
                        args.success = () => { };
                    }
                    if (!_.isFunction(args.error)) {
                        args.error = () => { };
                    }
                    this.layoutView.commit();
                    PDJS.Ajax.call({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: Jade.Path.resolve("~/Target/Save"),
                        data: JSON.stringify(this.rootModel.context.toJSON()),
                        success: (e) => { this.commit_onSuccess(e); args.success(e); },
                        error: (e) => { this.commit_onError(e); args.error(e); }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                }
                layout_init() {
                    let previous = this.m_layoutView;
                    this.m_layoutView = new FeatureBlendJS.Views.FeatureBlendView({
                        layout: this.layoutType
                    });
                    this.controls.add(this.m_layoutView);
                    if (previous != null) {
                        previous.destroy();
                    }
                }
                commit_onSuccess(e) {
                    this.requestMonitorStop();
                    this.onCommitSuccessCallback(e);
                }
                commit_onError(e) {
                    this.requestMonitorStop();
                    if (this.isEditorInJsonResponse(e)) {
                        let errors = e.responseJSON.editor.errors;
                        let keyfull = errors.filter(item => {
                            return !Jade.String.isNullOrWhiteSpace(item.key);
                        });
                        let keyless = errors.filter(item => {
                            return Jade.String.isNullOrWhiteSpace(item.key);
                        });
                        if (keyless.length > 0) {
                            PDJS.Shared.Dialogs.ErrorDialogLauncher.open({
                                title: "Warning | Errors Detected",
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                errors: keyless
                            });
                        }
                        else {
                            PDJS.Shared.MessageStack.instance.warning("Validation errors detected.");
                        }
                        e.errorHandled = true;
                        if (this.layoutView != null) {
                            this.layoutView.loadErrors(keyfull);
                        }
                        this.onValidationErrorCallback();
                        return;
                    }
                }
                loadContextIntoLayoutView(context) {
                    this.m_rootModel = new FeatureBlendJS.Models.RootModel(context);
                    this.rootModel.postbackHandler = () => { this.reload(); };
                    this.rootModel.context.featureSet.onValueChanged(args => {
                        this.onFeatureValueChangedCallback();
                    });
                    this.layout_init();
                    this.layoutView.loadModel(this.m_rootModel);
                    this.requestMonitorStop();
                }
                requestMonitorStart() {
                    let control = this.controls.getByType(Shared.UI.Controls.LoadingMessageControl).first();
                    if (control == null) {
                        control = new Shared.UI.Controls.LoadingMessageControl({
                            message: "Loading...",
                            showLoadingIcon: true
                        });
                        this.controls.add(control);
                    }
                    this.m_timeout = window.setTimeout(() => {
                        control.node.show();
                    }, 3000);
                    if (this.m_rootModel != null) {
                        this.m_rootModel.errors.clear();
                    }
                    this.onRequestStartCallback();
                }
                requestMonitorStop() {
                    let control = this.controls.getByType(Shared.UI.Controls.LoadingMessageControl).first();
                    if (control != null) {
                        control.node.hide();
                    }
                    if (this.m_timeout != null) {
                        clearTimeout(this.m_timeout);
                        this.m_timeout = null;
                    }
                    this.onRequestEndCallback();
                }
                isEditorInJsonResponse(e) {
                    var _a;
                    return ((_a = e === null || e === void 0 ? void 0 : e.responseJSON) === null || _a === void 0 ? void 0 : _a.editor) != null;
                }
            }
            Features.FeatureEditor = FeatureEditor;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.StringEditor", Editors.StringEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.IntegerEditor", Editors.IntegerEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.ListEditor", Editors.ListEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.ListEditorBase", Editors.ListEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.ColorEditor", Editors.ColorEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.FormatEditor", Editors.FormatEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.ViewEditor", Editors.ViewEditor);
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.TextAreaEditor", Editors.TextAreaEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class AceEditor extends Editors.PopUpEditor {
                    get ace() {
                        return this.feature.getValue("creatorAce");
                    }
                    set ace(value) {
                        this.feature.setValue("creatorAce", value);
                    }
                    get permissions() {
                        return this.feature.getValue("creatorPermissions");
                    }
                    focus() {
                        super.focus();
                        this.popupButtonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.hide();
                        this.showImage(false);
                        this.setDisplayText();
                        this.node.addClass("-pdjs-ace-editor");
                    }
                    popupButton_onClick() {
                        PDJS.Shared.Security.AceEditorDialog.open({
                            ace: this.ace,
                            permissions: this.permissions,
                            select: {
                                ok: (sender, e) => {
                                    this.ace = e.ace.toJSON();
                                    this.setDisplayText();
                                }
                            }
                        });
                    }
                    setDisplayText() {
                        let text = [];
                        this.maskNode.empty();
                        PDJS.Shared.Security.EntityPermissions.list.forEach(permission => {
                            let coverage = PDJS.Shared.Security.EntityPermissions.getCoverage({
                                info: permission,
                                allow: this.ace.allow,
                                deny: this.ace.deny
                            });
                            let tooltip = "";
                            switch (coverage) {
                                case PDJS.Shared.Security.IPermissionCoverage.Allow:
                                    tooltip = `${permission.name} Fully Allowed`;
                                    break;
                                case PDJS.Shared.Security.IPermissionCoverage.Deny:
                                    tooltip = `${permission.name} Fully Denied`;
                                    break;
                                case PDJS.Shared.Security.IPermissionCoverage.Partial:
                                    tooltip = `${permission.name} Partially Allowed/Denied`;
                                    break;
                                case PDJS.Shared.Security.IPermissionCoverage.None:
                                    tooltip = `${permission.name} Not Set`;
                                    break;
                            }
                            text[text.length] = `<span role="${coverage}" title="${tooltip}">${permission.name}</span>`;
                        });
                        this.maskNode.append(text.join(""));
                    }
                }
                Editors.AceEditor = AceEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.AceEditor", AceEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ActionEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        return "No Action Selected";
                    }
                    get action() {
                        return this.source.getFeaturePrimaryValue({
                            id: null,
                            name: null,
                            description: null
                        });
                    }
                    set action(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get hasAction() {
                        var _a;
                        return ((_a = this.action) === null || _a === void 0 ? void 0 : _a.id) != null;
                    }
                    clearButton_onClick() {
                        this.action = { id: null, pluginId: null, parameters: [] };
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Actions.ActionDialog.open({
                            originalAction: this.action,
                            select: {
                                ok: (sender, e) => {
                                    this.action = e;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-action-selector-editor");
                        this.inputNode.prop("readonly", true);
                        this.inputNode.prop("tabindex", "-1");
                        this.updateUI();
                    }
                    setInputText(name) {
                        var _a;
                        let plugin = this.getPlugin();
                        let action = this.getAction();
                        if (this.action != null && ((_a = this.action) === null || _a === void 0 ? void 0 : _a.id) != null) {
                            this.inputNode.val(`${(action === null || action === void 0 ? void 0 : action.name) ? action === null || action === void 0 ? void 0 : action.name : action === null || action === void 0 ? void 0 : action.id} (${plugin ? plugin === null || plugin === void 0 ? void 0 : plugin.name : action === null || action === void 0 ? void 0 : action.pluginId})`);
                            this.toggleState("ok");
                        }
                        else {
                            this.inputNode.val(this.getDefaultText());
                            this.toggleState("error");
                        }
                    }
                    getPlugin() {
                        var _a;
                        return PDJS.Shared.Plugins.PluginManager
                            .instance
                            .getPlugin((_a = this.action) === null || _a === void 0 ? void 0 : _a.pluginId);
                    }
                    getAction() {
                        var _a, _b, _c;
                        return PDJS.Shared.Actions.Action
                            .getAction((_a = this.action) === null || _a === void 0 ? void 0 : _a.id, (_b = this.action) === null || _b === void 0 ? void 0 : _b.pluginId, (_c = this.action) === null || _c === void 0 ? void 0 : _c.parameters);
                    }
                    setIcon() {
                        if (this.action) {
                            this.imageNode.attr("src", Jade.IconSet.get("pd").resolve("FLASH_YELLOW.PNG", Jade.IconSetSizeSpecificDirectory.x16));
                            this.imageNode.attr("title", "Action");
                        }
                    }
                    updateUI() {
                        this.showImage(true);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasAction);
                        this.setIcon();
                        this.setInputText(this.text);
                    }
                }
                Editors.ActionEditor = ActionEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ActionEditor", ActionEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ColorEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get allowInlineColors() {
                        return this.source.state.get("allowInlineColors", false);
                    }
                    get allowThemeColors() {
                        return this.source.state.get("allowThemeColors", false);
                    }
                    get allowTransparent() {
                        return this.source.state.get("allowTransparent", false);
                    }
                    get defaultName() {
                        return this.source.state.get("defaultName");
                    }
                    get convertedDefault() {
                        return this.source.state.get("convertedDefault");
                    }
                    set convertedDefault(value) {
                        this.source.state.set("convertedDefault", value);
                    }
                    get input() {
                        return this.m_input;
                    }
                    get targetTheme() {
                        return this.source.state.get("targetTheme");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue("");
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-color-editor"></div>`;
                    }
                    focus() {
                        super.focus();
                        this.input.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.convertDefaultValue();
                        this.input_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_input.enabled = this.source.enabled && !this.source.readOnly;
                    }
                    input_init() {
                        this.m_input = new PDJS.Shared.UI.Controls.ColorEditor({
                            default: this.defaultName,
                            allowInlineColors: this.allowInlineColors,
                            allowTransparent: this.allowTransparent,
                            allowThemeColors: this.allowThemeColors,
                            targetTheme: this.targetTheme,
                            value: this.value,
                            change: (color) => {
                                this.value = this.convertDefaultToNull(color);
                            }
                        });
                        this.controls.add(this.m_input);
                    }
                    convertDefaultToNull(value) {
                        let currentValue = value === null || value === void 0 ? void 0 : value.toLowerCase();
                        let defaultValue = this.convertedDefault;
                        if (Jade.String.isNullOrWhiteSpace(value) || currentValue == defaultValue) {
                            return null;
                        }
                        return value;
                    }
                    convertDefaultValue() {
                        var _a;
                        if (this.defaultName == null) {
                            return null;
                        }
                        let defaultName = this.defaultName.toLowerCase();
                        let match = (_a = _.first(Shared.Themes.Theme.colors.filter((color) => {
                            return color.uniqueName.toLowerCase() == defaultName;
                        }))) === null || _a === void 0 ? void 0 : _a.id;
                        if (match) {
                            this.convertedDefault = `var(--${match})`;
                        }
                    }
                }
                Editors.ColorEditor = ColorEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ColorEditor", ColorEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ColorsEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get allowThemeColors() {
                        return this.source.state.get("allowThemeColors", false);
                    }
                    get input() {
                        return this.m_input;
                    }
                    get targetTheme() {
                        return this.source.state.get("targetTheme");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue([]);
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-colors-editor">
                        <div></div>
                        <div role="buttons">
                            <button ${this.source.readOnly ? "disabled" : ""} title="Edit">...</button>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.input.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.input_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_input.enabled = this.source.enabled && !this.source.readOnly;
                    }
                    input_init() {
                        this.controls.add(this.m_input);
                    }
                }
                Editors.ColorsEditor = ColorsEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ColorsEditor", ColorsEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class DateEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get watermark() {
                        return this.source.state.get("watermark", null);
                    }
                    get calendar() {
                        return this.m_calendar;
                    }
                    set calendar(value) {
                        this.m_calendar = value;
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-pdjs-fb-date-editor"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.calendar_init();
                    }
                    calendar_init() {
                        this.calendar = new Shared.UI.Controls.DateTextBox({
                            format: "MMMM dd, yyyy",
                            defaultMask: this.watermark,
                            onChange: (e) => {
                                this.value = e.value;
                            }
                        });
                        this.controls.add(this.calendar);
                        if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                            let value = new Date(this.value).toLocaleDateString();
                            this.calendar.setValue(value);
                        }
                    }
                }
                Editors.DateEditor = DateEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.DateEditor", DateEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class DecimalEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get inputValue() {
                        return Jade.String.isNullOrWhiteSpace(this.inputRawValue) ?
                            null : parseFloat(this.inputRawValue);
                    }
                    get inputRawValue() {
                        return this.inputNode.val();
                    }
                    template() {
                        return `<div class="-fb-decimal-editor">
                    <input type="text" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}  />
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_valueHandler = new PDJS.Shared.UI.InputValueHandler({
                            input: this.inputNode.get(0),
                            changing: (e) => {
                                if (e.isActionable !== false && !(/^-?\d*\.?\d*$/).test(e.futureValue)) {
                                    e.cancel();
                                }
                            }
                        });
                        this.inputNode.val(this.source.getFeaturePrimaryValue(""));
                        this.inputNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.source.setFeaturePrimaryValue(this.inputValue);
                        });
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        if (this.m_valueHandler) {
                            this.m_valueHandler.destroy();
                        }
                    }
                }
                Editors.DecimalEditor = DecimalEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.DecimalEditor", DecimalEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class DocumentTypeSelectorEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        return "No Document Type Selected";
                    }
                    get documentTypeId() {
                        return this.value;
                    }
                    set documentTypeId(value) {
                        this.value = value;
                    }
                    get documentTypeName() {
                        return this.text;
                    }
                    set documentTypeName(value) {
                        this.text = value;
                    }
                    get hasDocumentType() {
                        return this.hasValue;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    clearButton_onClick() {
                        this.documentTypeId = null;
                        this.documentTypeName = null;
                        this.updateUI();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-document-type-selector-editor");
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Shared.DocumentTypes.DocumentTypeBrowserDialog.open({
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    let file = _.first(e);
                                    this.documentTypeId = file.id;
                                    this.documentTypeName = file.name;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    updateUI() {
                        this.showImage(false);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasDocumentType);
                        this.setInputText();
                    }
                }
                Editors.DocumentTypeSelectorEditor = DocumentTypeSelectorEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.DocumentTypeSelectorEditor", DocumentTypeSelectorEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get expressionId() {
                        return this.source.getFeatureValue(this.expressionIdProperty);
                    }
                    set expressionId(value) {
                        this.source.setFeatureValue(this.expressionIdProperty, value);
                    }
                    get expressionName() {
                        return this.source.getFeatureValue(this.expressionNameProperty);
                    }
                    set expressionName(value) {
                        this.source.setFeatureValue(this.expressionNameProperty, value);
                    }
                    get expressionIdProperty() {
                        return _.camelCase(this.source.state.get("expressionIdProperty"));
                    }
                    get expressionNameProperty() {
                        return _.camelCase(this.source.state.get("expressionNameProperty"));
                    }
                    template() {
                        return `<div class="-pdjs-shared-feature-editors-expression-editor">
                        <div role="input"></div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (this.m_input) {
                            this.m_input.focus();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.input_init();
                    }
                    input_init() {
                        this.m_input = new Editors.ExpressionEditorInput({
                            insertAt: "div[role=input]",
                            expressionId: this.expressionId,
                            expressionName: this.expressionName,
                            enabled: this.source.enabled,
                            readOnly: this.source.readOnly,
                            change: (e) => {
                                this.expressionId = e.expressionId;
                                this.expressionName = e.expressionName;
                            }
                        });
                        this.controls.add(this.m_input);
                    }
                }
                Editors.ExpressionEditor = ExpressionEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ExpressionEditor", ExpressionEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionEditorDialog extends Jade.UI.Dialogs.DialogOf {
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.getSelections().toArray();
                    }
                    get gridNode() {
                        return this.node.find("div[role=grid]");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-shared-feature-editors-expression-editor-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.startUp();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Expression",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.gridNode,
                            selectionMode: "single",
                            viewStateId: this.viewStateId,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.ObjectId,
                                            name: item.ObjectName
                                        };
                                    });
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            }
                        });
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Expression Selected",
                                message: "No expression has been selected. Select an expression and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                    startUp() {
                        PDJS.Ajax.call({
                            contentType: "application/json",
                            url: Jade.Path.resolve("~/Manage/Expressions/Index"),
                            data: {},
                            success: (e) => {
                                this.viewStateId = e.viewStateId;
                                this.grid_init();
                            },
                            error: (e) => {
                                this.close();
                            }
                        });
                    }
                    static open(options) {
                        return new ExpressionEditorDialog(options);
                    }
                }
                Editors.ExpressionEditorDialog = ExpressionEditorDialog;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionEditorInput extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get expressionId() {
                        return this.state.get("expressionId");
                    }
                    set expressionId(value) {
                        this.state.set("expressionId", value);
                    }
                    get expressionName() {
                        return this.state.get("expressionName");
                    }
                    set expressionName(value) {
                        this.state.set("expressionName", value);
                    }
                    get readOnly() {
                        return this.state.get("readOnly");
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    focus() {
                        this.inputNode.focus().select();
                    }
                    clear() {
                        this.inputNode.val("No Expression Assigned");
                        this.expressionId = null;
                        this.expressionName = null;
                        this.changeCallback({
                            expressionId: null,
                            expressionName: null
                        });
                        this.setState();
                    }
                    clearText() {
                        this.inputNode.val("No Expression Assigned");
                    }
                    template() {
                        return `<div class="-pdjs-shared-feature-editors-expression-editor-input">
                    <div>
                        <input type="text" readonly />
                    </div>
                    <div>
                        <button ${this.readOnly || !this.enabled ? "disabled" : ""}>...</button>
                    </div>
                </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.focus();
                        });
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.expressionName != null ?
                            this.inputNode.val(this.expressionName) :
                            this.clearText();
                        this.setState();
                    }
                    setState() {
                        let state = Jade.String
                            .isNullOrWhiteSpace(this.expressionId) ? "error" : "ok";
                        this.inputNode.removeClass("-fb-grid-input-status-error");
                        this.inputNode.removeClass("-fb-grid-input-status-ok");
                        switch (state) {
                            case "error":
                                this.inputNode.addClass("-fb-grid-input-status-error");
                                break;
                            case "ok":
                                this.inputNode.addClass("-fb-grid-input-status-ok");
                                break;
                        }
                    }
                    button_onClick() {
                        Editors.ExpressionEditorDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    let result = _.first(e);
                                    this.inputNode.val(result.name);
                                    this.expressionId = result.id,
                                        this.expressionName = result.name,
                                        this.changeCallback({
                                            expressionId: result.id,
                                            expressionName: result.name
                                        });
                                    this.setState();
                                }
                            }
                        });
                    }
                }
                Editors.ExpressionEditorInput = ExpressionEditorInput;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ExpressionOrListEditorSelect extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get selectNode() {
                        return this.node.children("select");
                    }
                    get value() {
                        return this.state.get("value", false);
                    }
                    get list() {
                        return this.state.get("list", []);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    template() {
                        return `<div class="-pdjs-shared-feature-editors-expression-or-list-editor-input">
                        <select></select>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.changeCallback(this.selectNode.val());
                        });
                        this.list.forEach(item => {
                            this.selectNode.append(`<option value="${item.value}">${item.name}</option>`);
                        });
                        this.selectNode.val(this.value.toString());
                    }
                }
                Editors.ExpressionOrListEditorSelect = ExpressionOrListEditorSelect;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                let FormatDataType;
                (function (FormatDataType) {
                    FormatDataType[FormatDataType["DateTime"] = 0] = "DateTime";
                    FormatDataType[FormatDataType["Decimal"] = 1] = "Decimal";
                    FormatDataType[FormatDataType["Integer"] = 2] = "Integer";
                })(FormatDataType || (FormatDataType = {}));
                class FormatEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get inputNode() {
                        return this.node.children("input");
                    }
                    get sampleNode() {
                        return this.node.children("div[role=sample]");
                    }
                    get formatType() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    template() {
                        return `<div class="-fb-format-editor">
                        <input type="text" />
                        <div role="sample"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.input_onKeyUp(e);
                        });
                        this.inputNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.input_onBlur(e);
                        });
                        this.inputNode.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.focus();
                        });
                        this.inputNode.val(this.formatType.format);
                        this.sampleNode.text(this.getSampleValueFormatted());
                        this.source.set.onValueChanged((e) => {
                            if (e.name == "decimalPlaces") {
                                this.formatType.scale = e.value;
                                this.sampleNode.text(this.getSampleValueFormatted());
                            }
                        });
                    }
                    input_onKeyUp(e) {
                        this.sampleNode.text(this.getSampleValueFormatted());
                    }
                    input_onBlur(e) {
                        this.formatType.format = this.inputNode.val();
                        this.source.setFeaturePrimaryValue(this.formatType);
                    }
                    getSampleValue() {
                        let result = null;
                        let scale = this.formatType.scale;
                        switch (this.formatType.type) {
                            case FormatDataType.DateTime:
                                result = new Date(2010, 9, 31);
                                break;
                            case FormatDataType.Decimal:
                                if (scale > 16) {
                                    scale = 16;
                                }
                                if (scale >= 0) {
                                    result = (parseInt("999999999".substr(0, 16 - scale)));
                                }
                                break;
                            case FormatDataType.Integer:
                                result = 1750000;
                                break;
                        }
                        return result;
                    }
                    getSampleValueFormatted() {
                        let value = this.getSampleValue();
                        let format = this.inputNode.val();
                        let scale = this.formatType.scale;
                        let result = "";
                        switch (this.formatType.type) {
                            case FormatDataType.DateTime:
                                format = (!format || format === "" ? "d" : format);
                                break;
                            case FormatDataType.Decimal:
                                format = (!format || format === "" || format === "g" ? "n" + scale : format);
                                break;
                            case FormatDataType.Integer:
                                format = (!format || format === "" || format === "g" ? "n0" : format);
                                break;
                        }
                        try {
                            result = kendo.toString(value, format.toString());
                        }
                        catch (ex) {
                            result = null;
                        }
                        if (!result || result === "") {
                            this.showError();
                            return;
                        }
                        else {
                            this.hideError();
                        }
                        return result;
                    }
                    hideError() {
                        this.sampleNode.css({
                            color: "black",
                            backgroundColor: "#dbffce"
                        });
                    }
                    showError() {
                        this.sampleNode.text("Invalid Format");
                        this.sampleNode.css({
                            color: "white",
                            backgroundColor: "darkred"
                        });
                    }
                }
                Editors.FormatEditor = FormatEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class IconEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get imageNode() {
                        return this.node.find("img");
                    }
                    get hasIcon() {
                        return !Jade.String.isNullOrWhiteSpace(this.icon);
                    }
                    get icon() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set icon(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get iconPath() {
                        let result = null;
                        if (this.hasIcon) {
                            result = Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16);
                        }
                        return result;
                    }
                    template() {
                        return `<div class="-pdjs-fb-icon-editor">
                    <div><img src="" style="display:none;" /></div>
                    <div><input type="text" ${this.source.readOnly ? "readonly" : ""} /></div>
                    <div><button ${this.source.readOnly ? "disabled" : ""}>...</button></div>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (!Jade.String.isNullOrWhiteSpace(this.icon)) {
                            this.inputNode.val(this.icon);
                        }
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.source.setFeaturePrimaryValue(this.inputNode.val());
                        });
                        this.inputNode.on(Jade.BrowserEvent.KEYUP, () => {
                            this.source.setFeaturePrimaryValue(this.inputNode.val());
                            this.setIconImage();
                        });
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.setIconImage();
                    }
                    button_onClick() {
                        PDJS.Shared.Dialogs.IconBrowserDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    this.inputNode.val(e.value);
                                    this.source.setFeaturePrimaryValue(e.value);
                                    this.setIconImage();
                                }
                            }
                        });
                    }
                    setIconImage() {
                        if (this.hasIcon) {
                            this.imageNode.attr("src", "");
                            this.imageNode.attr("src", this.iconPath);
                            this.imageNode.show();
                        }
                        else {
                            this.imageNode.attr("src", "");
                            this.imageNode.hide();
                        }
                    }
                }
                Editors.IconEditor = IconEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.IconEditor", IconEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class MaskedPopUpEditorBase extends FeatureBlendJS.Views.MicroEditorBase {
                    get clearButtonNode() {
                        return this.node.find("button[role=clear]");
                    }
                    get clearButtonVisible() {
                        return this.clearButtonNode.is(":visible");
                    }
                    set clearButtonVisible(value) {
                        value ? this.clearButtonNode.show()
                            : this.clearButtonNode.hide();
                    }
                    get popupButtonNode() {
                        return this.node.find("button[role=popup]");
                    }
                    get popupButtonVisible() {
                        return this.popupButtonNode.is(":visible");
                    }
                    set popupButtonVisible(value) {
                        value ? this.popupButtonNode.show()
                            : this.popupButtonNode.hide();
                    }
                    get imageNode() {
                        return this.node.find("img[role=image]");
                    }
                    get imageVisible() {
                        return this.imageNode.is(":visible");
                    }
                    set imageVisible(value) {
                        value ? this.imageNode.show()
                            : this.imageNode.hide();
                    }
                    get input() {
                        return this.m_input;
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get text() {
                        return this.source.getFeatureValueByProp("textProperty");
                    }
                    set text(value) {
                        this.source.setFeatureValueByProp("textProperty", value);
                    }
                    get defaultText() {
                        return this.source.getFeatureValueByProp("defaultTextProperty") || "";
                    }
                    get defaultTextEnabled() {
                        return this.source.isPropertyDefined("defaultTextProperty");
                    }
                    get shouldShowDefaultText() {
                        return this.defaultTextEnabled &&
                            Jade.String.isNullOrWhiteSpace(this.text) &&
                            Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    get hasDefaultText() {
                        return Jade.String.isNullOrWhiteSpace(this.defaultText);
                    }
                    get hasText() {
                        return Jade.String.isNullOrWhiteSpace(this.text);
                    }
                    get hasValue() {
                        return !Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    template() {
                        return `<div class="-pdjs-shared-masked-popup-editor">
                        <div>
                            <img src="" role="image" />
                        </div>
                        <div data-controls></div>
                        <div role="buttons">
                            <div>
                                <button ${this.source.readOnly ? "disabled" : ""} role="clear" title="Clear">
                                    <i class="icofont-close" />
                                </button>
                                <button ${this.source.readOnly ? "disabled" : ""} role="popup" title="Edit">...</button>
                            </div>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.input.focusText();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.imageVisible = false;
                        this.clearButtonVisible = false;
                        this.clearButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.clearButton_onClick();
                        });
                        this.popupButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.popupButton_onClick();
                        });
                        this.m_input = this.createInput();
                        this.controls.add(this.m_input);
                        this.input.enabled = this.source.enabled;
                        this.refreshUserInterface();
                    }
                    popupButton_onClick() {
                    }
                    clearButton_onClick() {
                        this.clearValueAndText();
                        this.refreshUserInterface();
                    }
                    input_onBlur() {
                    }
                    createInput() {
                        return new PDJS.Shared.UI.Controls.MaskedTextBox({
                            onTextBlur: (e) => {
                                this.input_onBlur();
                            },
                            defaultMaskText: this.defaultText || ""
                        });
                    }
                    refreshUserInterface() {
                        this.input.maskValue = this.text || this.value || this.defaultText || "";
                        this.input.textValue = this.value || "";
                        this.popupButtonVisible = this.source.enabled;
                        this.clearButtonVisible = this.hasValue;
                        this.imageVisible = this.hasValue || this.shouldShowDefaultText;
                        this.setIcon();
                        this.shouldShowDefaultText ?
                            this.input.maskNode.addClass("-pdjs-no-value") :
                            this.input.maskNode.removeClass("-pdjs-no-value");
                        if (Jade.String.isNullOrWhiteSpace(this.imageNode.attr("src"))) {
                            this.imageNode.remove();
                        }
                    }
                    clearValueAndText() {
                        this.text = null;
                        this.value = null;
                        this.input.maskValue = "";
                        this.input.textValue = "";
                    }
                    setIcon() {
                    }
                }
                Editors.MaskedPopUpEditorBase = MaskedPopUpEditorBase;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                let IdentitySelectionType;
                (function (IdentitySelectionType) {
                    IdentitySelectionType[IdentitySelectionType["all"] = 0] = "all";
                    IdentitySelectionType[IdentitySelectionType["usersOnly"] = 1] = "usersOnly";
                    IdentitySelectionType[IdentitySelectionType["groupsOnly"] = 2] = "groupsOnly";
                })(IdentitySelectionType || (IdentitySelectionType = {}));
                class IdentitySelectionEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        switch (this.selectionType) {
                            case IdentitySelectionType.groupsOnly:
                                return "No Group Assigned";
                            case IdentitySelectionType.usersOnly:
                                return "No User Assigned";
                            case IdentitySelectionType.all:
                                return "No User or Group Assigned";
                        }
                    }
                    get hasIdentity() {
                        return !Jade.String.isNullOrWhiteSpace(this.identityName);
                    }
                    get identityName() {
                        return this.value;
                    }
                    set identityName(value) {
                        this.value = value;
                    }
                    get selectionType() {
                        return this.source.state.get("selectionType", IdentitySelectionType.all);
                    }
                    get shouldShowDefaultText() {
                        return this.defaultTextEnabled &&
                            Jade.String.isNullOrWhiteSpace(this.identityName);
                    }
                    clearButton_onClick() {
                        this.text = "";
                        this.identityName = null;
                        this.updateUI();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-identity-selection-editor");
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Shared.Security.IdentityBrowserDialog.open({
                            title: this.getTitle(),
                            filters: this.getFilters(),
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    this.identityName = _.first(e).accountId;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    setIcon() {
                        if (this.shouldShowDefaultText || this.hasIdentity) {
                            this.imageNode.attr("src", Jade.IconSet.get("pd")
                                .resolve("USERS.PNG", Jade.IconSetSizeSpecificDirectory.x16));
                        }
                    }
                    getFilters() {
                        let result = [];
                        switch (this.selectionType) {
                            case IdentitySelectionType.groupsOnly:
                                result.push(PDJS.Core.Views.IdentityFilter.groupsOnly());
                                result.push(PDJS.Core.Views.IdentityFilter.excludeEveryone());
                                break;
                            case IdentitySelectionType.usersOnly:
                                result.push(PDJS.Core.Views.IdentityFilter.usersOnly());
                                break;
                            case IdentitySelectionType.all:
                                result.push(PDJS.Core.Views.IdentityFilter.excludeEveryone());
                                break;
                        }
                        return result;
                    }
                    getTitle() {
                        switch (this.selectionType) {
                            case IdentitySelectionType.groupsOnly:
                                return "Select | Group";
                            case IdentitySelectionType.usersOnly:
                                return "Select | User";
                            default:
                                return "Select | User or Group";
                        }
                    }
                    updateUI() {
                        let showImage = !Jade.String.isNullOrWhiteSpace(this.identityName) ||
                            !Jade.String.isNullOrWhiteSpace(this.defaultText);
                        this.showImage(showImage);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasIdentity);
                        this.setIcon();
                        this.setInputText(this.identityName);
                    }
                }
                Editors.IdentitySelectionEditor = IdentitySelectionEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.IdentitySelectionEditor", IdentitySelectionEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class IntegerEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get inputValue() {
                        return Jade.String.isNullOrWhiteSpace(this.inputRawValue) ?
                            null : parseInt(this.inputRawValue);
                    }
                    get inputRawValue() {
                        return this.inputNode.val();
                    }
                    template() {
                        return `<div class="-fb-integer-editor">
                    <input type="text" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}  />
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_valueHandler = new PDJS.Shared.UI.InputValueHandler({
                            input: this.inputNode.get(0),
                            changing: (e) => {
                                if (e.isActionable !== false && !(/^(-?[1-9]+\d*)$|^0$|^$|^\-$/).test(e.futureValue)) {
                                    e.cancel();
                                }
                            }
                        });
                        this.inputNode.val(this.source.getFeaturePrimaryValue(""));
                        this.inputNode.blur(Jade.BrowserEvent.BLUR, (e) => {
                            this.source.setFeaturePrimaryValue(this.inputValue);
                        });
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        if (this.m_valueHandler) {
                            this.m_valueHandler.destroy();
                        }
                    }
                }
                Editors.IntegerEditor = IntegerEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class LdeSelectionDialog extends Jade.UI.Dialogs.DialogOf {
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.getSelections().toArray();
                    }
                    get gridNode() {
                        return this.node.find("div[role=grid]");
                    }
                    template() {
                        return super.template(`
                <div class="-fb-lde-selection-editor-dialog">
                    <div role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.startUp();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | List Data Extension",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.gridNode,
                            selectionMode: "single",
                            viewStateId: this.viewStateId,
                            defaultSelectionEnabled: true,
                            needContext: (e) => {
                                e.filters[e.filters.length] = {
                                    id: "IsList",
                                    params: {
                                        isList: 1
                                    }
                                };
                            },
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item.ObjectId,
                                            name: item.ExtensionName
                                        };
                                    });
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            }
                        });
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: {
                                    items: this.selections
                                }
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Extension Selected",
                                message: "No list data extension has been selected. Select an list data extension and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                    startUp() {
                        PDJS.Ajax.call({
                            contentType: "application/json",
                            url: Jade.Path.resolve("~/Manage/DataModel/Index/list"),
                            data: {},
                            success: (e) => {
                                this.viewStateId = e.tablesViewStateId;
                                this.grid_init();
                            },
                            error: (e) => {
                                this.close();
                            }
                        });
                    }
                    static open(options) {
                        return new LdeSelectionDialog(options);
                    }
                }
                Editors.LdeSelectionDialog = LdeSelectionDialog;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class LdeSelectionEditor extends PDJS.Shared.Features.Editors.PopUpEditor {
                    get emptyText() {
                        return "No Extension Assigned";
                    }
                    get extensionId() {
                        return this.value;
                    }
                    set extensionId(value) {
                        this.value = value;
                    }
                    get extensionName() {
                        return this.text;
                    }
                    set extensionName(value) {
                        this.text = value;
                    }
                    clearButton_onClick() {
                        this.extensionId = null;
                        this.extensionName = null;
                        this.updateUI();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.source.readOnly) {
                            this.inputNode.attr("readonly", "readonly");
                        }
                        if (!this.source.enabled) {
                            this.inputNode.attr("disabled", "disabled");
                        }
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        Editors.LdeSelectionDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    let result = _.first(e.items);
                                    this.extensionId = result.id;
                                    this.extensionName = result.name;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    updateUI() {
                        this.showImage(false);
                        this.showPopUpButton(true);
                        this.showClearButton(false);
                        this.setInputText();
                    }
                }
                Editors.LdeSelectionEditor = LdeSelectionEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.Manage.Modules.ExplorerModel.LdeSelectionEditor", LdeSelectionEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ListEditorBase extends FeatureBlendJS.Views.MicroEditorBase {
                    get items() {
                        let result;
                        result = this.listId == "list" ?
                            this.source.state.get(this.listId) :
                            this.source.feature.initializers[this.listId];
                        return result || [];
                    }
                    get listId() {
                        return this.source.state.get("listId", "list");
                    }
                }
                Editors.ListEditorBase = ListEditorBase;
                class ListEditor extends ListEditorBase {
                    get selectNode() {
                        return this.node.find("select");
                    }
                    template() {
                        return `<div><select style="box-sizing:border-box;width: 100%; height: 25px;border:0 solid transparent;box-shadow:none;" ${this.source.enabled ? "" : "disabled"}></select></div>`;
                    }
                    focus() {
                        super.focus();
                        this.node.find("select").focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        let value = `${this.source.getFeaturePrimaryValue("")}`;
                        this.items.forEach(item => {
                            this.selectNode.append(`<option value="${item.value}">${item.name}</option>`);
                        });
                        this.selectNode.val(value);
                        this.selectNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.source.setFeaturePrimaryValue(this.selectNode.val());
                            this.onSelectionChange(this.selectNode.val());
                        });
                    }
                    onSelectionChange(value) {
                    }
                }
                Editors.ListEditor = ListEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                let ListViewEditorValueType;
                (function (ListViewEditorValueType) {
                    ListViewEditorValueType[ListViewEditorValueType["List"] = 0] = "List";
                    ListViewEditorValueType[ListViewEditorValueType["DelimitedString"] = 1] = "DelimitedString";
                    ListViewEditorValueType[ListViewEditorValueType["Flags"] = 2] = "Flags";
                })(ListViewEditorValueType = Editors.ListViewEditorValueType || (Editors.ListViewEditorValueType = {}));
                class ListViewEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get selectNode() {
                        return this.node.find("select");
                    }
                    get iconBinding() {
                        return this.source.state.get("iconBinding", null);
                    }
                    get labelBinding() {
                        return this.source.state.get("labelBinding", "label");
                    }
                    get valueType() {
                        return this.source.state.get("valueType", false);
                    }
                    get height() {
                        return this.source.state.get("height", 100);
                    }
                    get items() {
                        let result;
                        result = this.listId == "list" ?
                            this.source.state.get(this.listId) :
                            this.source.feature.initializers[this.listId];
                        return result || [];
                    }
                    get listId() {
                        return this.source.state.get("listId", "list");
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    get valueBinding() {
                        return this.source.state.get("valueBinding", "value");
                    }
                    template() {
                        return `<div class="-pdjs-fb-list-view-editor"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.loadList();
                        this.loadValues();
                    }
                    list_init() {
                        this.list =
                            new Shared.UI.Controls.ListView({
                                binding: {
                                    icon: this.iconBinding,
                                    label: this.labelBinding,
                                    value: this.valueBinding
                                },
                                height: `${this.height}px`,
                                showCheckboxes: true,
                                checkOnSelect: true,
                                selectMode: Shared.UI.Controls.ListViewSelectMode.none,
                                createItem: (e) => {
                                    return new Shared.UI.Controls.ListViewItem(e);
                                },
                                change: (e) => {
                                    let checked = this.list.items.checked.toArray();
                                    switch (this.valueType) {
                                        case ListViewEditorValueType.List:
                                            this.commitValueAsList(checked);
                                            break;
                                        case ListViewEditorValueType.DelimitedString:
                                            this.commitValuesAsDelimitedString(checked);
                                            break;
                                        case ListViewEditorValueType.Flags:
                                            this.commitValuesAsFlags(checked);
                                            break;
                                    }
                                }
                            });
                        this.controls.add(this.list);
                    }
                    commitValueAsList(items) {
                        this.source.setFeaturePrimaryValue(items.map(item => item.value));
                    }
                    commitValuesAsDelimitedString(items) {
                        this.source.setFeaturePrimaryValue(items.map(item => item.value).join(","));
                    }
                    commitValuesAsFlags(items) {
                        let flags = 0;
                        items.map(item => {
                            flags |= item.value;
                        });
                        this.source.setFeaturePrimaryValue(flags);
                    }
                    loadValues() {
                        this.list.items.toArray().forEach(item => {
                            item.checked = false;
                        });
                        switch (this.valueType) {
                            case ListViewEditorValueType.List:
                                this.loadValuesFromList();
                                break;
                            case ListViewEditorValueType.DelimitedString:
                                this.loadValuesFromDelimitedString();
                                break;
                            case ListViewEditorValueType.Flags:
                                this.loadValuesFromFlags();
                                break;
                        }
                    }
                    loadValuesFromList() {
                        if (!_.isArray(this.value)) {
                            return;
                        }
                        let value = this.value;
                        this.list.items.toArray().forEach(item => {
                            if (value.indexOf(item.value) > -1) {
                                item.checked = true;
                            }
                        });
                    }
                    loadValuesFromDelimitedString() {
                        if (!_.isString(this.value)) {
                            return;
                        }
                        let value = this.value.split(",");
                        this.list.items.toArray().forEach(item => {
                            if (value.indexOf(item.value) > -1) {
                                item.checked = true;
                            }
                        });
                    }
                    loadValuesFromFlags() {
                        if (!_.isNumber(this.value)) {
                            return;
                        }
                        let flags = this.value;
                        this.list.items.toArray().forEach(item => {
                            item.checked = (flags & item.value) > 0;
                        });
                    }
                    loadList() {
                        this.items.forEach(item => {
                            this.list.addItem(item);
                        });
                    }
                }
                Editors.ListViewEditor = ListViewEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ListViewEditor", ListViewEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class PasswordEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get input() {
                        return this.node.children("input:nth-child(1)");
                    }
                    get mask() {
                        return this.node.children("input:nth-child(2)");
                    }
                    template() {
                        return `<div class="-fb-password-editor">
                        <input type="password" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""} />
                        <input type="password" value="********" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""} />
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.input.on(Jade.BrowserEvent.BLUR, (e) => {
                            this.source.setFeaturePrimaryValue(this.input.val());
                            this.showPasswordMask(this.input.val() === "");
                        });
                        this.input.on(Jade.BrowserEvent.FOCUS, () => {
                            this.showPasswordMask(false);
                        });
                        this.mask.on(Jade.BrowserEvent.FOCUS, (e) => {
                            this.showPasswordMask(false);
                            this.input.focus();
                            this.input.select();
                        });
                        this.showPasswordMask(true);
                    }
                    showPasswordMask(show) {
                        if (show) {
                            this.mask.show();
                        }
                        else {
                            this.mask.hide();
                        }
                    }
                }
                Editors.PasswordEditor = PasswordEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.PasswordEditor", PasswordEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                let ReportSelectorFilter;
                (function (ReportSelectorFilter) {
                    ReportSelectorFilter[ReportSelectorFilter["OnlyHTML"] = 0] = "OnlyHTML";
                    ReportSelectorFilter[ReportSelectorFilter["NotHTML"] = 1] = "NotHTML";
                })(ReportSelectorFilter || (ReportSelectorFilter = {}));
                class ReportSelectorEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        return "No Report Selected";
                    }
                    get filter() {
                        return this.source.state.get("filter");
                    }
                    get reportId() {
                        return this.value;
                    }
                    set reportId(value) {
                        this.value = value;
                    }
                    get reportName() {
                        return this.text;
                    }
                    set reportName(value) {
                        this.text = value;
                    }
                    get viewStateId() {
                        return this.source.getFeatureValueByProp("viewStateIdProperty");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Reports.ReportSelectionDialog.open({
                            viewStateId: this.viewStateId,
                            filter: this.getFilter(),
                            select: {
                                ok: (sender, e) => {
                                    this.reportId = e.report.id;
                                    this.reportName = e.report.name;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    getFilter() {
                        switch (this.filter) {
                            case ReportSelectorFilter.NotHTML:
                                return "NotHTML";
                            case ReportSelectorFilter.OnlyHTML:
                                return "OnlyHTML";
                        }
                    }
                    updateUI() {
                        this.showImage(false);
                        this.showPopUpButton(true);
                        this.showClearButton(false);
                        this.setInputText();
                    }
                }
                Editors.ReportSelectorEditor = ReportSelectorEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ReportSelectorEditor", ReportSelectorEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ResourceSelectionEditor extends Editors.PopUpEditor {
                    get allowFreeForm() {
                        return this.source.state.get("allowFreeForm", false);
                    }
                    get validExtensions() {
                        return this.source.state.get("extensions", []);
                    }
                    get resourcePathProperty() {
                        return _.camelCase(this.source.state.get("resourcePathProperty"));
                    }
                    get resourcePath() {
                        return this.source.getFeatureValue(this.resourcePathProperty, "");
                    }
                    set resourcePath(value) {
                        this.source.setFeatureValue(this.resourcePathProperty, value);
                    }
                    get resourceId() {
                        return this.source.getFeaturePrimaryValue("");
                    }
                    set resourceId(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get hasResource() {
                        return !Jade.String.isNullOrWhiteSpace(this.resourcePath);
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-resource-selection-editor");
                        this.updateUI();
                    }
                    clearButton_onClick() {
                        this.resourceId = null;
                        this.resourcePath = null;
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Resources.SelectFileDialog.open({
                            extensions: this.validExtensions,
                            select: {
                                ok: (sender, e) => {
                                    let file = _.first(e);
                                    this.resourceId = file.id;
                                    this.resourcePath = `${file.path}`;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    updateUI() {
                        let path = this.hasResource ? this.resourcePath.slice(1) : "";
                        this.inputNode.attr("title", this.hasResource ? path : "");
                        this.inputNode.val(`${this.hasResource ? path : ""}`);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasResource);
                        this.hasResource ?
                            this.inputNode.removeClass("-pdjs-no-value") :
                            this.inputNode.addClass("-pdjs-no-value");
                    }
                }
                Editors.ResourceSelectionEditor = ResourceSelectionEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.ResourceSelectionEditor", ResourceSelectionEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class RuleScriptSelectorEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        return "No Script Assigned";
                    }
                    get hasScript() {
                        return this.hasValue;
                    }
                    get scriptName() {
                        return this.text;
                    }
                    set scriptName(value) {
                        this.text = value;
                    }
                    get scriptId() {
                        return this.value;
                    }
                    set scriptId(value) {
                        this.value = value;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-rule-script-selector-editor");
                        this.inputNode.prop("readonly", true);
                        this.inputNode.prop("tabindex", "-1");
                        this.updateUI();
                        this.inputNode.on(Jade.BrowserEvent.MOUSEOVER, (e) => {
                            if (!Jade.String.isNullOrWhiteSpace(this.scriptId)) {
                                this.clearButtonNode.show();
                            }
                        });
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Rules.RuleScriptSelectionDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    this.text = e.name;
                                    this.scriptId = e.id;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    clearButton_onClick() {
                        this.text = "";
                        this.scriptId = null;
                        this.updateUI();
                    }
                    setIcon() {
                        if (this.scriptId == null && this.defaultTextEnabled) {
                            this.imageNode.attr("src", Jade.IconSet.get("pd").resolve("FLASH_YELLOW.PNG", Jade.IconSetSizeSpecificDirectory.x16));
                            this.imageNode.attr("title", "Rule Event");
                        }
                        else {
                            this.imageNode.attr("src", Jade.IconSet.get("pd").resolve("CODE.PNG", Jade.IconSetSizeSpecificDirectory.x16));
                            this.imageNode.attr("title", "Rule Script");
                        }
                    }
                    updateUI() {
                        let showImage = !Jade.String.isNullOrWhiteSpace(this.scriptId) ||
                            !Jade.String.isNullOrWhiteSpace(this.defaultText);
                        this.showImage(showImage);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasScript);
                        this.setIcon();
                        this.setInputText(this.text);
                    }
                }
                Editors.RuleScriptSelectorEditor = RuleScriptSelectorEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.RuleScriptSelectorEditor", RuleScriptSelectorEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class SelectionListEditor extends Editors.MaskedPopUpEditorBase {
                    get listId() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set listId(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-selection-list-editor");
                        this.input.enabled = this.source.enabled;
                        this.imageVisible = false;
                        this.clearButtonVisible = false;
                    }
                    popupButton_onClick() {
                        PDJS.Manage.DataModel.SelectionLists.SelectListDialog.open({
                            title: "Select | Selection List",
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            select: {
                                ok: (sender, e) => {
                                    let item = _.first(e.items);
                                    this.listId = item.id;
                                    this.text = item.name;
                                    this.refreshUserInterface();
                                }
                            }
                        });
                    }
                }
                Editors.SelectionListEditor = SelectionListEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.SelectionListEditor", SelectionListEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class SingleFileUploadEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get fileId() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set fileId(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get fileName() {
                        return this.source.getFeatureValue(this.fileNameProperty, "");
                    }
                    set fileName(value) {
                        this.source.setFeatureValue(this.fileNameProperty, value);
                    }
                    get fileNameProperty() {
                        return this.source.state.get("fileNameProperty");
                    }
                    template() {
                        return `<div class="-fb-single-file-upload-editor"></div>`;
                    }
                    focus() {
                        super.focus();
                        this.m_upload.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.upload_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.m_upload.setLabelText(this.fileName);
                    }
                    upload_init() {
                        this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                            onUploadComplete: (e) => {
                                this.fileId = `${e.id}${e.extension}`;
                                this.fileName = e.name;
                            }
                        });
                        this.controls.add(this.m_upload);
                    }
                }
                Editors.SingleFileUploadEditor = SingleFileUploadEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editor.SingleFileUploadEditor", SingleFileUploadEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class StringEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        value = Jade.String.isNullOrWhiteSpace(value) ? null : value;
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-string-editor">
                        <div>
                            <input type="text" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}  />
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                            this.inputNode.val(this.value);
                        }
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.value = this.inputNode.val();
                        });
                    }
                }
                Editors.StringEditor = StringEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class SystemVariableEditor extends Editors.PopUpEditor {
                    get emptyText() {
                        return "No Variable Assigned";
                    }
                    get hasVariable() {
                        return this.variableId != null;
                    }
                    get variableId() {
                        return this.value;
                    }
                    set variableId(value) {
                        this.value = value;
                    }
                    get variableName() {
                        return this.text;
                    }
                    set variableName(value) {
                        this.text = value;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    clearButton_onClick() {
                        this.variableId = null;
                        this.variableName = null;
                        this.updateUI();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-system-variable-editor");
                        this.updateUI();
                    }
                    popupButton_onClick() {
                        PDJS.Manage.SystemVariables.SystemVariableEdtiorDialog.open({
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    this.variableId = e.id;
                                    this.variableName = e.name;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    setIcon() {
                        if (this.hasVariable) {
                            this.imageNode.attr("src", Jade.IconSet.get("pdv2")
                                .resolve("formula.png", Jade.IconSetSizeSpecificDirectory.x16));
                        }
                    }
                    updateUI() {
                        this.showImage(this.hasVariable);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasVariable);
                        this.setInputText();
                        this.setIcon();
                    }
                }
                Editors.SystemVariableEditor = SystemVariableEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.SystemVariableEditor", SystemVariableEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var SystemVariables;
        (function (SystemVariables) {
            class SystemVariableEdtiorDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get grid() {
                    return this.m_grid;
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-manage-system-variables-editor-dialog">
                    <div data-role="grid"></div>
                    <div data-role="buttons">
                        <button data-command="ok" class="-pdjs-dialog-button">OK</button>
                        <button data-command="cancel" class="-pdjs-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Select | System Variable",
                        height: "400px",
                        width: "600px",
                        maximized: false
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.dialog_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role=grid]"),
                        selectionMode: "single",
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.Name
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            this.m_selection = e.selection;
                        },
                        dblclick: (e) => {
                            this.m_selection = e.selection;
                            this.closeAndReturn();
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.m_selection != null) {
                        this.close({
                            name: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No system variable has been selected. Select a system variable and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                dialog_init() {
                    let service = new PDJS.Services.Views.ViewService();
                    service.getViewStateId({
                        viewCustomId: PDJS.Services.Views.BuiltInViews.SYSTEM_VARIABLE_SELECTION,
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                            this.grid_init();
                            this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                            this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                        }
                    });
                }
                static open(options) {
                    return new SystemVariableEdtiorDialog(options);
                }
            }
            SystemVariables.SystemVariableEdtiorDialog = SystemVariableEdtiorDialog;
        })(SystemVariables = Manage.SystemVariables || (Manage.SystemVariables = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                let TagType;
                (function (TagType) {
                    TagType[TagType["Default"] = 2] = "Default";
                    TagType[TagType["Wildcard"] = 1] = "Wildcard";
                    TagType[TagType["Clear"] = 0] = "Clear";
                })(TagType || (TagType = {}));
                ;
                class TagEditor extends Editors.PopUpEditor {
                    get tagslist() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set tagslist(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get allowWildcards() {
                        return this.source.state.get("allowWildcards", false);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.hide();
                        this.showImage(false);
                        this.setDisplayText();
                        this.node.addClass("-pdjs-tag-editor");
                        this.node.on(Jade.BrowserEvent.DOUBLECLICK, "span.a2, span.r2", (e) => {
                            this.showTagListDialog();
                        });
                        this.node.on(Jade.BrowserEvent.DOUBLECLICK, "span.r0, span.r1", (e) => {
                            let text = $(e.currentTarget).find("[role=text]").text();
                            this.showTagPatternDialog(text);
                        });
                        this.node.on(Jade.BrowserEvent.CLICK, "span[role=delete]", (e) => {
                            this.deleteTag($(e.currentTarget).closest("[role=tag]"));
                        });
                        this.popup_init();
                    }
                    popupButton_onClick() {
                        if (this.allowWildcards) {
                            this.m_popup.visible ?
                                this.m_popup.hide() :
                                this.m_popup.show();
                        }
                        else {
                            this.showTagListDialog();
                        }
                    }
                    setDisplayText() {
                        let tags = [];
                        let list = this.getSortedTagList();
                        let icon = Jade.IconSet.get("pd")
                            .resolve("cancel_white.png", Jade.IconSetSizeSpecificDirectory.misc);
                        this.maskNode.empty();
                        list.forEach(item => {
                            let html = `
                    <span role="tag" title="${item.text}" class="${this.allowWildcards ? "r" : "a"}${item.type}">
                        <span role="text">${item.text}</span>
                        <span role="delete" style="background-image:url(${icon})"></span>
                    </span>`;
                            tags.push(html);
                        });
                        this.maskNode.append(tags.join(""));
                    }
                    getTagType(tag) {
                        let result = TagType.Default;
                        switch (true) {
                            case tag == "*":
                                return TagType.Clear;
                            case tag.indexOf("*") > -1:
                                return TagType.Wildcard;
                        }
                        return result;
                    }
                    getSortedTagList() {
                        let result = [];
                        result = this.tagslist.map(tag => {
                            return {
                                text: tag,
                                type: this.getTagType(tag)
                            };
                        }).sort((a, b) => {
                            let aValue = `${a.type}-${a.text}`.toLowerCase();
                            let bValue = `${b.type}-${b.text}`.toLowerCase();
                            return aValue.localeCompare(bValue);
                        });
                        return result;
                    }
                    deleteTag(node) {
                        let tag = node.find("span[role=text]").text();
                        let index = this.tagslist.indexOf(tag);
                        if (index > -1) {
                            this.tagslist = this.tagslist.filter(item => item != tag);
                        }
                        this.setDisplayText();
                    }
                    popup_init() {
                        this.m_popup = new PDJS.Shared.UI.Controls.PopUp({
                            anchor: this.popupButtonNode,
                            width: 120,
                            tipped: {
                                skin: "themed",
                                position: {
                                    target: "bottomright",
                                    tooltip: "topright"
                                },
                                container: $("body"),
                                offset: {
                                    y: 4,
                                    x: 2
                                }
                            }
                        });
                        this.controls.add(this.m_popup);
                        this.m_popup.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: { label: "Add Tag", value: 1 },
                            click: () => {
                                this.m_popup.hide();
                                this.showTagListDialog();
                            }
                        }));
                        this.m_popup.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: { label: "Add Tag Pattern", value: 2 },
                            click: () => {
                                this.m_popup.hide();
                                this.showTagPatternDialog();
                            }
                        }));
                    }
                    showTagListDialog() {
                        Editors.TagListDialog.open({
                            allowWildcards: this.allowWildcards,
                            select: {
                                ok: (sender, e) => {
                                    this.updateList(e.tags);
                                }
                            }
                        });
                    }
                    showTagPatternDialog(pattern = "") {
                        PDJS.Manage.Tags.TagPatternDialog.open({
                            pattern: pattern,
                            select: {
                                ok: (sender, e) => {
                                    Jade.String.isNullOrWhiteSpace(e.oldPattern) ?
                                        this.updateList([e.newPattern]) :
                                        this.updatePattern(e);
                                }
                            }
                        });
                    }
                    updateList(items, patterns = null) {
                        let list = this.tagslist.slice(0);
                        items.forEach((item, index) => {
                            if (list.indexOf(item) == -1) {
                                list.push(item);
                            }
                        });
                        this.tagslist = list;
                        this.setDisplayText();
                    }
                    updatePattern(patterns = null) {
                        let list = this.tagslist.slice(0);
                        this.tagslist.forEach((item, index) => {
                            var _a;
                            if (((_a = patterns === null || patterns === void 0 ? void 0 : patterns.oldPattern) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == item.toLowerCase()) {
                                list[index] = patterns.newPattern;
                            }
                        });
                        this.tagslist = list;
                        this.setDisplayText();
                    }
                }
                Editors.TagEditor = TagEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.TagEditor", TagEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class TagListDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get buttonOk() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get buttonCancel() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-tag-list-dialog">
                    <div role="grid"></div>
                    <div role="deck">
                        <button
                            data-command="ok"
                            class="-jadeui-dialog-button">
                            OK
                        </button>
                        <button 
                            data-command="cancel"
                            class="-jadeui-dialog-button">
                            Cancel
                        </button>
                    </div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.startUp();
                        this.buttonCancel.on(Jade.BrowserEvent.CLICK, () => {
                            this.close();
                        });
                        this.buttonOk.on(Jade.BrowserEvent.CLICK, () => {
                            this.closeAndReturn();
                        });
                    }
                    onInputReturnKeystroke() {
                        this.buttonOk.focus();
                        this.buttonOk.click();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Tags",
                            height: "400px",
                            minHeight: "300px",
                            width: "500px",
                            minWidth: "300px",
                            resizable: true
                        };
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            footer: {
                                visible: false
                            },
                            selection: {
                                mapping: (e) => {
                                    return e.ObjectName;
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            }
                        });
                    }
                    startUp() {
                        let service = new PDJS.Services.Views.ViewService();
                        if (this.viewStateId == null) {
                            service.getViewStateId({
                                viewCustomId: PDJS.Services.Views.BuiltInViews.TAG_SELECTION,
                                success: (e) => {
                                    this.viewStateId = e.data.viewStateId;
                                    this.grid_init();
                                }
                            });
                        }
                    }
                    closeAndReturn() {
                        let selections = this.m_grid.getSelections().toArray();
                        if (selections.length) {
                            this.close({
                                name: "ok",
                                data: {
                                    tags: selections
                                }
                            });
                        }
                        else {
                            this.close();
                        }
                    }
                    static open(options) {
                        return new TagListDialog(options);
                    }
                }
                Editors.TagListDialog = TagListDialog;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class TextAreaEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get allowDataTags() {
                        return this.source.state.get("allowDataTags", false);
                    }
                    get height() {
                        return this.source.state.get("height", 60);
                    }
                    get inputNode() {
                        return this.node.find("textarea");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        value = Jade.String.isNullOrWhiteSpace(value) ? null : value;
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-text-area-editor">
                        <div>
                            <textarea ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}></textarea>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        if (!this.inputNode.is(":focus")) {
                            this.inputNode.focus().select();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.FOCUS, () => {
                            this.focus();
                        });
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.value = this.inputNode.val();
                        });
                        this.writeTextToInput();
                        this.inputNode.css({
                            minHeight: `${this.height}px`
                        });
                    }
                    writeTextToInput() {
                        this.inputNode.val(this.source.getFeaturePrimaryValue());
                    }
                }
                Editors.TextAreaEditor = TextAreaEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                const RegEx12HourFormat = /^(((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm])))$/i;
                const RegEx24HourFormat = /^(([0-1]?[0-9]|2[0-3]):[0-5][0-9])$/i;
                class TimeEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get fixedNode() {
                        return this.node.find("select[role=fixed]");
                    }
                    get masked() {
                        return this.m_masked;
                    }
                    set masked(value) {
                        this.m_masked = value;
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue("");
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get minutesProperty() {
                        return this.source.attributes["minutesProperty"];
                    }
                    get hoursProperty() {
                        return this.source.attributes["hoursProperty"];
                    }
                    get hasMinutesProperty() {
                        return !Jade.String
                            .isNullOrWhiteSpace(this.minutesProperty);
                    }
                    get hasHoursProperty() {
                        return !Jade.String
                            .isNullOrWhiteSpace(this.hoursProperty);
                    }
                    get hours() {
                        return this.source.getFeatureValue(this.hoursProperty);
                    }
                    set hours(value) {
                        this.source.setFeatureValue(this.hoursProperty, value);
                    }
                    get minutes() {
                        return this.source.getFeatureValue(this.minutesProperty);
                    }
                    set minutes(value) {
                        this.source.setFeatureValue(this.minutesProperty, value);
                    }
                    template() {
                        return `<div class="-pdjs-fb-time-editor">
                        <select role="fixed"></select>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.init_fixed();
                        this.init_masked();
                        this.fixedNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                            this.masked.maskValue = this.fixedNode.val();
                            this.masked.textValue = this.fixedNode.val();
                            this.changeValue(this.fixedNode.val());
                        });
                        this.masked.maskValue = this.value;
                        this.masked.textValue = this.value;
                    }
                    init_fixed() {
                        let items = [];
                        for (let i = 0; i < 24; i++) {
                            for (let j = 0; j < 2; j++) {
                                let isPM = i > 11;
                                let hour = isPM ? (i == 12 ? 12 : i - 12) : (i == 0 ? 12 : i);
                                let minute = j * 30;
                                let value = `${hour.toString()}:${Jade.String.padLeft(minute.toString(), "0", 2)} ${isPM ? "PM" : "AM"}`;
                                items.push(`<option value="${value}">${value}</option>`);
                            }
                        }
                        this.fixedNode.append(items.join(""));
                    }
                    init_masked() {
                        this.masked = new Shared.UI.Controls.MaskedTextBox({
                            onMaskFocus: (e) => {
                                this.masked.showText();
                                this.masked.focusText();
                            },
                            onTextKeyUp: (e) => {
                                this.setValidationState(this.masked.textValue);
                            },
                            onTextBlur: (e) => {
                                this.changeValue(this.masked.textValue);
                            }
                        });
                        this.controls.add(this.masked);
                        this.masked.node.css({
                            position: "absolute",
                            inset: 0,
                            right: "20px"
                        });
                    }
                    isValidTime(value) {
                        let trimmedValue = value === null || value === void 0 ? void 0 : value.trim();
                        return this.is12HourFormat(trimmedValue) ||
                            this.is24HourFormat(trimmedValue);
                    }
                    setValidationState(value) {
                        !this.isValidTime(value) ?
                            this.masked.textNode.css({ color: "red" }) :
                            this.masked.textNode.css({ color: "initial" });
                    }
                    is12HourFormat(value) {
                        return RegEx12HourFormat.test(value);
                    }
                    is24HourFormat(value) {
                        return RegEx24HourFormat.test(value);
                    }
                    changeValue(value) {
                        if (this.isValidTime(value)) {
                            this.masked.textValue = this.formatValue(value);
                            this.masked.maskValue = this.masked.textValue;
                            this.masked.showMask();
                            this.commitValue(this.masked.textValue);
                        }
                        else {
                            this.value = null;
                        }
                        this.setValidationState(value);
                    }
                    commitValue(value) {
                        let parts = this.getTimeParts(value);
                        this.value = value;
                        if (this.hasHoursProperty) {
                            this.hours = parts.hours;
                        }
                        if (this.hasMinutesProperty) {
                            this.minutes = parts.minutes;
                        }
                    }
                    getTimeParts(value) {
                        let is12Hours = this.is12HourFormat(value);
                        let meridiem = is12Hours ?
                            value.split(" ")[1].toUpperCase() : null;
                        let time = is12Hours ?
                            value.split(" ")[0] : value;
                        let hoursText = time.split(":")[0];
                        let hours = parseInt(hoursText);
                        let minutesText = time.split(":")[1];
                        let minutes = parseInt(minutesText);
                        if (meridiem != null) {
                            if (meridiem == "PM") {
                                hours = hours == 12 ? 12 : hours + 12;
                            }
                            if (meridiem == "AM") {
                                hours = hours == 12 ? 0 : hours;
                            }
                        }
                        return {
                            hours: hours,
                            hoursAdjusted: hours,
                            hoursText: hoursText,
                            meridiem: meridiem,
                            minutes: minutes,
                            minutesText: minutesText
                        };
                    }
                    formatValue(value) {
                        let parts = this.getTimeParts(value);
                        return parts.meridiem == null ?
                            `${parts.hoursText}:${parts.minutesText}` :
                            `${parts.hoursText}:${parts.minutesText} ${parts.meridiem}`;
                    }
                }
                Editors.TimeEditor = TimeEditor;
                Jade.Application.onStart(() => {
                    FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.TimeEditor", TimeEditor);
                });
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                class ViewEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get linkNode() {
                        return this.node.find("a");
                    }
                    template() {
                        return `<div class="-fb-view-editor">
                       <div>
                        <a href="#">Click here to edit the view</a>
                        </div>
                        <div>
                            <button ${this.source.readOnly ? "readonly" : ""}>...</button>
                        </div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.showViewEditorDialog, this));
                        this.linkNode.on(Jade.BrowserEvent.CLICK, _.bind(this.showViewEditorDialog, this));
                    }
                    showViewEditorDialog() {
                        PDJS.Shared.Features.FeatureDialogForNhib.open({
                            title: `View Editor`,
                            height: 550,
                            width: 700,
                            args: {
                                targetId: this.source.getFeaturePrimaryValue(),
                                targetType: "ProspectDirector.Web.Manage.Modules.Views.ViewUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Views.ViewArbiter",
                                properties: {
                                    designerOnly: true
                                }
                            }
                        });
                        return true;
                    }
                }
                Editors.ViewEditor = ViewEditor;
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class MacroEditor extends FeatureBlendJS.Views.MacroEditorBase {
                        get dialogNode() {
                            var _a;
                            return (_a = this.node) === null || _a === void 0 ? void 0 : _a.closest(".-jadejs-window");
                        }
                        get dialog() {
                            var _a;
                            return (_a = this.dialogNode) === null || _a === void 0 ? void 0 : _a.data("dialog");
                        }
                        setDimensons(args) {
                            this.dialogNode.hide();
                            if (this.dialog) {
                                this.dialog.setWindowOptions({
                                    height: args.height,
                                    width: args.width
                                });
                            }
                            this.dialogNode.show();
                        }
                    }
                    Macro.MacroEditor = MacroEditor;
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class AceTextEditor extends FeatureBlendJS.Views.MacroEditorBase {
                        get editorNode() {
                            return this.node.find("div[role=editor]");
                        }
                        get editor() {
                            return this.m_editor;
                        }
                        get mode() {
                            return this.state.get("mode", "text");
                        }
                        get readOnly() {
                            return this.source.state.get("readOnly", false);
                        }
                        get value() {
                            return this.source.primaryValue;
                        }
                        set value(value) {
                            this.source.primaryValue = value;
                        }
                        get theme() {
                            return PDJS.System.Environment
                                .current.profile.themes.manageEditor || "ace/theme/chrome";
                        }
                        template() {
                            return `<div class="-fb-ace-text-editor">
                        <div role="editor"></div>
                    </div>`;
                        }
                        resize() {
                            if (this.editor != null) {
                                this.editor.resize();
                            }
                        }
                        destroy() {
                            super.destroy();
                            if (this.editor != null) {
                                this.editor.destroy();
                            }
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.editor_init();
                        }
                        editor_init() {
                            ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                            this.m_editor = ace.edit(this.editorNode[0]);
                            this.editor.renderer.setShowPrintMargin(false);
                            this.editor.setShowFoldWidgets(true);
                            this.editor.getSession().setUseSoftTabs(false);
                            this.editor.setTheme(this.theme);
                            this.editor.session.setMode({ path: "ace/mode/" + this.mode, v: Date.now() });
                            this.editor.setFontSize("14px");
                            this.editor.setValue(this.value || "");
                            this.editor.setReadOnly(this.readOnly);
                            this.editor_focus();
                            this.editor.on("change", (e) => {
                                this.source.primaryValue = this.editor.getValue();
                            });
                            this.subscriptions.add(PDJS.Profiles.EventsHub.themeChangedSubscribe(() => {
                                this.editor.setTheme(this.theme);
                            }));
                        }
                        editor_focus() {
                            let session = this.editor.getSession();
                            let lineCount = session.getLength();
                            this.editor.focus();
                            this.editor.gotoLine(lineCount, session.getLine(lineCount - 1).length);
                        }
                    }
                    Macro.AceTextEditor = AceTextEditor;
                    Jade.Application.onStart(() => {
                        FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.Macro.AceTextEditor", AceTextEditor);
                    });
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class RichTextEditor extends FeatureBlendJS.Views.MacroEditorBase {
                        get containerNode() {
                            return this.node.find("div[role=container]");
                        }
                        get editor() {
                            return this.m_editor;
                        }
                        get editorNode() {
                            return this.node.find(".mce-tinymce");
                        }
                        focus() {
                            if (this.editor != null) {
                                try {
                                    this.editor.focus();
                                }
                                catch (ex) { }
                            }
                        }
                        template() {
                            return `<div class="-fb-rich-text-editor">
                        <div role="container">
                            <textarea id="textarea-${this.ID}"></textarea>
                        </div>
                    </div>`;
                        }
                        resize() {
                            this.editor_sizeToFit();
                        }
                        destroy() {
                            super.destroy();
                            if (this.editor != null) {
                                this.editor.destroy();
                            }
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.editor_init();
                            setTimeout(() => { this.editor_sizeToFit(); }, 300);
                        }
                        editor_init() {
                            tinymce.init({
                                selector: `#${this.ID} > DIV > TEXTAREA`,
                                apply_source_formatting: true,
                                plugins: "link hr textcolor colorpicker",
                                menubar: false,
                                statusbar: false,
                                auto_focus: `textarea-${this.ID}`,
                                toolbar: [
                                    "undo redo | fontsizeselect forecolor backcolor | bold italic | alignleft aligncenter alignright | bullist numlist hr | outdent indent | link unlink"
                                ],
                                color_picker_callback: (sender, e) => { this.editor_onShowColorPicker(e); },
                                fontsize_formats: "8px 10px 11px 12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 28px 32px 36px 40px",
                                content_css: Jade.Path.resolve("~/scripts/pdjs/external/tinymce/tinymce-content.css?" + Jade.Guid.new().toString()),
                                setup: (editor) => { this.editor_onSetup(editor); }
                            });
                        }
                        editor_onSetup(editor) {
                            this.m_editor = editor;
                            editor.on('init', (e) => {
                                this.editor_loadContent();
                                this.editorNode.css({
                                    borderWidth: 0,
                                    borderStyle: "none"
                                });
                            });
                            editor.on('change', () => {
                                this.source.primaryValue = this.editor.getContent();
                            });
                        }
                        editor_onShowColorPicker(callback) {
                            PDJS.JS.ProspectDirector.Web.UI.FeatureSets.Editors.ColorEditorDialog.open({
                                config: {
                                    title: "Text Color"
                                },
                                data: {
                                    hex: "#000000"
                                },
                                callbacks: {
                                    ok: (sender, e) => {
                                        callback(e);
                                    }
                                }
                            });
                        }
                        editor_loadContent() {
                            let content = this.source.primaryValue;
                            this.editor_setBackgroundColor(this.source.getFeatureValue("backgroundColor"));
                            if (content == null) {
                                return;
                            }
                            if (_.isString(content)) {
                                this.editor.setContent(content);
                            }
                        }
                        editor_sizeToFit() {
                            let max = this.containerNode.outerHeight() - 4;
                            max -= this.containerNode.find('.mce-menubar.mce-toolbar').outerHeight();
                            max -= this.containerNode.find('.mce-toolbar-grp').outerHeight();
                            this.containerNode.find('.mce-edit-area').height(max);
                            this.containerNode.find('IFRAME').height(max);
                        }
                        editor_setBackgroundColor(color) {
                            try {
                                if (this.editor != null) {
                                    this.editor.getBody().style.backgroundColor = color || "#FFFFFF";
                                }
                            }
                            catch (_a) {
                            }
                        }
                    }
                    Macro.RichTextEditor = RichTextEditor;
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class TemplateEditor extends FeatureBlendJS.Views.MacroEditorBase {
                        get rich() {
                            return this.m_rich;
                        }
                        get value() {
                            return this.source.primaryValue;
                        }
                        set value(value) {
                            this.source.primaryValue = value;
                        }
                        template() {
                            return `<div class="-fb-macro-template-editor">
                        <div role="toolbar"></div>
                        <div role="rich"></div>
                    </div>`;
                        }
                        destroy() {
                            super.destroy();
                            if (this.rich != null) {
                                this.rich.destroy();
                            }
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.rich_init();
                            this.toolbar_init();
                            this.setCommandState();
                        }
                        onComplete(e) {
                            super.onComplete(e);
                            setTimeout(() => {
                                this.rich.switchToText();
                            }, 100);
                        }
                        rich_init() {
                            this.m_rich = new PDJS.Shared.UI.Controls.RichText({
                                insertAt: "div[role=rich]",
                                change: (e) => {
                                    this.source.primaryValue = e.value;
                                    this.setCommandState();
                                }
                            });
                            this.controls.add(this.m_rich);
                        }
                        toolbar_init() {
                            this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                                insertAt: "div[role=toolbar]",
                                segments: [new Macro.TemplateEditorToolbar({
                                        discriminator: this.ID
                                    })]
                            });
                            this.controls.add(this.m_toolbar);
                        }
                        setCommandState() {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands.setState({
                                "pdjs/shared/editors/macros/template": {
                                    $editor: this,
                                    $rich: this.rich
                                }
                            }, { force: true, discriminatorId: this.ID });
                        }
                    }
                    Macro.TemplateEditor = TemplateEditor;
                    Jade.Application.onStart(() => {
                        FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Features.Editors.Macro.TemplateEditor", TemplateEditor);
                    });
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class TemplateEditorCommand extends Jade.Command {
                        constructor(options = {}) {
                            super(options);
                            this.state.set("$editor", null);
                            this.state.set("$rich", null);
                        }
                        get editor() {
                            return this.state.get("$editor");
                        }
                        get rich() {
                            return this.state.get("$rich");
                        }
                        setCommandState() {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands.setState({
                                "pdjs/shared/editors/macros/template": {
                                    $editor: this.editor,
                                    $rich: this.rich
                                }
                            }, { force: true });
                        }
                    }
                    Macro.TemplateEditorCommand = TemplateEditorCommand;
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class ToggleViewCommand extends Macro.TemplateEditorCommand {
                        onStateChanged(e) {
                            super.onStateChanged(e);
                            this.updateButtonUI();
                        }
                        onExecute(e) {
                            super.onExecute(e);
                            this.rich.view == "text" ?
                                this.rich.switchToHtml() :
                                this.rich.switchToText();
                            this.updateButtonUI();
                        }
                        getDefaultValuesForProps() {
                            return {
                                id: `editor/toggle`,
                                label: null,
                                icon: null,
                                enabled: true,
                                display: "icon label",
                                iconSetId: "pdjs"
                            };
                        }
                        updateButtonUI() {
                            this.rich.view == "text" ?
                                this.label = "Switch to HTML View" :
                                this.label = "Switch to Text View";
                            this.rich.view == "text" ?
                                this.icon = "document_tag.png" :
                                this.icon = "document_text.png";
                        }
                    }
                    Macro.ToggleViewCommand = ToggleViewCommand;
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class TemplateEditorCommands extends Jade.CommandGroup {
                        constructor(id) {
                            super(`pdjs/shared/editors/macros/template`);
                        }
                        registerCommands(e) {
                            e.commands.add(new Macro.ToggleViewCommand());
                        }
                        static get isCommandGroupType() {
                            return true;
                        }
                    }
                    Macro.TemplateEditorCommands = TemplateEditorCommands;
                    Jade.CommandGroups.add(TemplateEditorCommands);
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Editors;
            (function (Editors) {
                var Macro;
                (function (Macro) {
                    class TemplateEditorToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                        constructor(options) {
                            super();
                            this.m_discriminator = options.discriminator;
                        }
                        get discriminator() {
                            return this.m_discriminator;
                        }
                        onAddItems(e) {
                            let prefix = Jade.CommandPath
                                .buildGroup("pdjs/shared/editors/macros/template", this.discriminator);
                            e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                                commandId: `${prefix}:editor/toggle`
                            }));
                        }
                    }
                    Macro.TemplateEditorToolbar = TemplateEditorToolbar;
                })(Macro = Editors.Macro || (Editors.Macro = {}));
            })(Editors = Features.Editors || (Features.Editors = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Features;
        (function (Features) {
            var Interop;
            (function (Interop) {
                class MacroEditor extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_adpatedEditor = options.adaptedEditor;
                        this.state.unset("adaptedEditor");
                        this.adaptedEditor.commit = _.bind(this.onCommit, this);
                        this.adaptedEditor.destroy = _.bind(this.onDestroy, this);
                        this.adaptedEditor.focus = _.bind(this.onFocus, this);
                        this.adaptedEditor.size = _.bind(this.onResize, this);
                        this.adaptedEditor.onValidationErrors = (errors) => {
                            let converted = [];
                            errors.forEach((error) => {
                                let data = error.toJSON();
                                converted[converted.length] = {
                                    key: data.key,
                                    code: data.code,
                                    target: error.get_propertyName().toLowerCase(),
                                    message: data.message,
                                    tags: data.tags
                                };
                            });
                            this.onValidationErrors(converted);
                        };
                        this.onEditorReady();
                    }
                    get adaptedEditor() {
                        return this.m_adpatedEditor;
                    }
                    template() {
                        return `<div></div>`;
                    }
                    onEditorReady() {
                    }
                    onCommit() {
                    }
                    onDestroy() {
                    }
                    onFocus() {
                    }
                    onResize() {
                    }
                    onValidationErrors(errors) {
                    }
                    setValue(key, value) {
                        this.adaptedEditor.setValue(key, value);
                    }
                    getValue(key) {
                        return this.adaptedEditor.getValue(key);
                    }
                }
                Interop.MacroEditor = MacroEditor;
            })(Interop = Features.Interop || (Features.Interop = {}));
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
Jade.Application.onStart(() => {
    $(function () {
        kendo.ui.Window.fn._keydown = function (originalFn) {
            return function (e) {
                let kendoWindow = $(e.target).data("kendoWindow");
                let alternate = kendoWindow != null ?
                    kendoWindow.onEscKey : null;
                if (e.which == Jade.KeyCode.Escape && _.isFunction(alternate)) {
                    alternate(e);
                }
                else {
                    originalFn.call(this, e);
                }
            };
        }(kendo.ui.Window.fn._keydown);
    });
});
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceMonitor {
                constructor() {
                    var client = MaintenanceMonitor.signalR.connection.maintenance.client;
                    client.broadcastMaintenanceModeWarning =
                        _.bind(this.onBroadcastMaintenanceModeWarning, this);
                    client.broadcastApplicationExit =
                        _.bind(this.onBroadcastApplicationExit, this);
                    client.broadcastMaintenanceStart =
                        _.bind(this.onBroadcastMaintenanceStart, this);
                    client.broadcastMaintenanceEnded =
                        _.bind(this.onBroadcastMaintenanceEnded, this);
                    MaintenanceMonitor.signalR.connection.hub.start({
                        pingInterval: null
                    });
                }
                onBroadcastMaintenanceModeWarning(e) {
                    Maintenance.MaintenanceNotification.show(e.timeUntil, e.maintenanceId);
                }
                onBroadcastApplicationExit(e) {
                    window.location.href = Jade.Path.resolve("~/hub/home");
                }
                onBroadcastMaintenanceStart(e) {
                    Maintenance.MaintenanceWatermark.show();
                }
                onBroadcastMaintenanceEnded(e) {
                    Maintenance.MaintenanceWatermark.hide();
                }
                static get signalR() {
                    return $;
                }
                static start() {
                    if (this.m_instance == null) {
                        this.m_instance = new MaintenanceMonitor();
                    }
                }
            }
            Maintenance.MaintenanceMonitor = MaintenanceMonitor;
            PDJS.Application.onStart(() => {
                MaintenanceMonitor.start();
            });
        })(Maintenance = Shared.Maintenance || (Shared.Maintenance = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceNotification {
                static get isDialogVisible() {
                    return this.m_dialog != null;
                }
                static show(timeUntilStart, maintenanceId) {
                    if (this.isDialogVisible) {
                        return;
                    }
                    this.isAcknowledged(maintenanceId) ?
                        this.showToast(timeUntilStart, maintenanceId) :
                        this.showDialog(timeUntilStart, maintenanceId);
                }
                static acknowledge(maintenanceId) {
                    localStorage.setItem("maintenanceId", maintenanceId);
                }
                static isAcknowledged(maintenanceId) {
                    return localStorage.getItem("maintenanceId") === maintenanceId;
                }
                static showDialog(timeUntilStart, maintenanceId) {
                    if (this.isDialogVisible) {
                        return;
                    }
                    this.m_dialog = Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        allowClose: false,
                        title: "Scheduled System Maintenance Notification",
                        message: `<div class="-pdjs-maintenance-dialog">
                            <div class="-pdjs-maintenance-dialog-warning">WARNING: Upcoming System Maintenance</div>
                            <div class="-pdjs-maintenance-dialog-content">Maintenance will start in ${timeUntilStart}.</div>
                            <div class="-pdjs-maintenance-dialog-footer">Complete your work and exit the application before maintenance begins to ensure no work is lost.</div>`,
                        select: (sender, e) => {
                            this.acknowledge(maintenanceId);
                            this.m_dialog = null;
                            sender.close();
                        }
                    });
                }
                static showToast(timeUntilStart, maintenanceId) {
                    PDJS.Shared.MessageStack.instance.warning(`
            <div class="-pdjs-maintenance-toast">
                    <b>WARNING</b><br/> Maintenance will start in ${timeUntilStart}.
            </div>`);
                }
            }
            Maintenance.MaintenanceNotification = MaintenanceNotification;
        })(Maintenance = Shared.Maintenance || (Shared.Maintenance = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Maintenance;
        (function (Maintenance) {
            class MaintenanceWatermark extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get iconPath() {
                    return Jade.IconSet.get("pdv2")
                        .resolve("construction_barrier.png", Jade.IconSetSizeSpecificDirectory.x32);
                }
                template() {
                    return `<div class="-pd-maintenance-watermark">
                        <img src="${this.iconPath}"/>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    PDJS.Shared.PopOver.tooltip(this.node, `<div style="font-size: 12px;">Application is currently undergoing maintenance.</div>`, {
                        position: {
                            target: "left",
                            tooltip: "right"
                        }
                    });
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.onClick(e);
                    });
                    this.node.on(Jade.BrowserEvent.MOUSEENTER, (e) => {
                        PDJS.Shared.PopOver.show(this.node);
                    });
                    this.node.on(Jade.BrowserEvent.MOUSELEAVE, (e) => {
                        PDJS.Shared.PopOver.hide(this.node);
                    });
                }
                onClick(e) {
                    this.node.css({ display: "none" });
                    setTimeout(() => {
                        this.node.css({ display: "" });
                    }, 3000);
                }
                static show() {
                    if (this.m_instance == null) {
                        this.m_instance = new MaintenanceWatermark({
                            container: "BODY"
                        });
                    }
                }
                static hide() {
                    if (this.m_instance != null) {
                        this.m_instance.destroy();
                    }
                }
            }
            Maintenance.MaintenanceWatermark = MaintenanceWatermark;
        })(Maintenance = Shared.Maintenance || (Shared.Maintenance = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Mce;
        (function (Mce) {
            ;
            ;
            ;
            class MceEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get bodyNode() {
                    return this.node.find(".-pdjs-shared-mce-editor-body");
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get content() {
                    return this.state.get("content");
                }
                get mce() {
                    this.editor_init();
                    return this.m_mce;
                }
                get mceNode() {
                    return this.node.find(".mce-tinymce");
                }
                get readOnly() {
                    return this.state.get("readOnly", false);
                }
                set readOnly(value) {
                    this.state.set("readOnly", value);
                }
                get readyCallback() {
                    return this.state.get("ready", () => { });
                }
                get setupCallback() {
                    return this.state.get("setup", () => { });
                }
                get style() {
                    return this.state.get("style", 0);
                }
                get theme() {
                    return this.state.get("theme");
                }
                get value() {
                    return this.mce.getContent();
                }
                set value(value) {
                    this.m_isSilentSet = true;
                    this.setValue(value);
                    this.m_isSilentSet = false;
                }
                template() {
                    return `<div class="-pdjs-shared-mce-editor">
                        <div class="-pdjs-shared-mce-editor-body">
                            <textarea></textarea>
                        </div>
                    </div>`;
                }
                resize() {
                    this.editor_resize();
                }
                destroy() {
                    if (this.mce != null) {
                        try {
                            this.mce.remove(`#${this.ID} > DIV > TEXTAREA`);
                            this.mce.destroy();
                        }
                        catch (ex) {
                            console.log("tiny mce destroy failed");
                        }
                    }
                    super.destroy();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_resize_init();
                    this.editor_init();
                }
                editor_onSetup(editor) {
                    this.m_mce = editor;
                    editor.on("init", (e) => {
                        this.editor_onInit(e);
                        setTimeout(() => {
                            this.readyCallback({
                                mce: this.mce
                            });
                            this.addThemeClassToPreviewButtons();
                        }, 250);
                    });
                    editor.on("change", (e) => {
                        this.editor_onDirty();
                    });
                    editor.on("paste", (e) => {
                        this.editor_onDirty();
                    });
                    editor.on("ExecCommand", (e) => {
                        this.editor_onDirty();
                    });
                    if (this.content != null) {
                        editor.setContent(this.content);
                    }
                    this.setupCallback({
                        mce: editor
                    });
                }
                editor_onInit(e) {
                    this.mceNode.css({
                        borderWidth: 0,
                        borderStyle: "none"
                    });
                    this.editor_resize();
                }
                editor_onDirty() {
                    if (this.m_isSilentSet !== true) {
                        this.changeCallback({
                            value: this.mce.getContent()
                        });
                    }
                }
                editor_onShowColorPicker(callback, e) {
                    let targetTheme = null;
                    switch (this.theme) {
                        case "hub":
                            targetTheme = PDJS.Services.Themes.ThemeScope.Hub;
                            break;
                        case "manage":
                            targetTheme = PDJS.Services.Themes.ThemeScope.Manage;
                            break;
                    }
                    let color = tinycolor(e);
                    let isThemeColor = PDJS.Shared.Colors.Color.isThemeColor(e);
                    PDJS.Shared.UI.Controls.ColorsDialog.open({
                        color: isThemeColor ? e : color.toHex8String(),
                        targetTheme: targetTheme,
                        availablePanels: this.style === 1 ? "themes" : "inline",
                        select: {
                            ok: (e, data) => {
                                callback(data.color);
                            }
                        }
                    });
                }
                editor_init() {
                    if (this.m_mce != null) {
                        return;
                    }
                    tinymce.init({
                        selector: `#${this.ID} > DIV > TEXTAREA`,
                        content_css: this.getCssFiles(),
                        document_base_url: null,
                        apply_source_formatting: true,
                        plugins: `link hr ${this.style === 0 ? "textcolor" : "colorThemes"} colorpicker`,
                        force_hex_style_colors: true,
                        menubar: false,
                        statusbar: false,
                        toolbar: [
                            "undo redo | fontsizeselect forecolor backcolor | bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent hr | link unlink | source"
                        ],
                        color_picker_callback: (sender, e) => { this.editor_onShowColorPicker(sender, e); },
                        fontsize_formats: "8px 10px 11px 12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 28px 32px 36px 40px",
                        setup: (editor) => { this.editor_onSetup(editor); }
                    });
                }
                editor_resize() {
                    let max = this.bodyNode.outerHeight();
                    max -= this.bodyNode.find('.mce-menubar.mce-toolbar').outerHeight();
                    max -= this.bodyNode.find('.mce-toolbar-grp').outerHeight();
                    this.bodyNode.find('.mce-edit-area').height(max);
                    this.bodyNode.find('IFRAME').height(max);
                }
                editor_resize_init() {
                    let debounced = _.debounce((e) => {
                        this.editor_resize();
                    }, 250);
                    this.m_resizeObserver =
                        new ResizeObserver((e) => {
                            debounced(e);
                        });
                    this.m_resizeObserver.observe(this.node.get(0));
                }
                getThemeCssUrl() {
                    switch (this.theme) {
                        case "hub":
                            return PDJS.Shared.Themes.ThemeUrl.hub;
                        case "manage":
                            return PDJS.Shared.Themes.ThemeUrl.manage;
                        default:
                            return;
                    }
                }
                getBaseContentCssUrl() {
                    return Jade.Path.resolve("~/scripts/pdjs/external/tinymce/tinymce-content.css?" + Jade.Guid.new().toString());
                }
                getThemeContentCssUrl() {
                    return Jade.Path.resolve("~/scripts/pdjs/external/tinymce/tinymce-content-theme.css?" + Jade.Guid.new().toString());
                }
                getCssFiles() {
                    let result = [
                        this.getBaseContentCssUrl(),
                        this.getThemeContentCssUrl()
                    ];
                    if (this.style === 1) {
                        result.push(Jade.Path.resolve(`~/scripts/pdjs/internal/index.css?${Jade.Guid.new().toString()}`));
                    }
                    if (this.theme != null && this.theme != "none") {
                        let themeCss = this.getThemeCssUrl();
                        if (themeCss) {
                            result.push(themeCss);
                        }
                    }
                    return result;
                }
                setValue(value) {
                    try {
                        this.mce.setContent(value || "");
                    }
                    catch (ex) { }
                }
                addThemeClassToPreviewButtons() {
                    this.node.find(".mce-preview").addClass("-theme-hub");
                    if (this.theme == "hub") {
                    }
                }
            }
            Mce.MceEditor = MceEditor;
        })(Mce = Shared.Mce || (Shared.Mce = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Mce;
        (function (Mce) {
            PDJS.Application.onStart(() => {
                if (PDJS.Application.instance.area !== "manage") {
                    return;
                }
                tinymce.PluginManager.add("colorThemes", function (a) {
                    function b(b) {
                        var c;
                        return a.dom.getParents(a.selection.getStart(), function (a) {
                            var d;
                            (d = a.style["forecolor" == b ? "color" : "background-color"]) && (c = d);
                        }), c;
                    }
                    function c() {
                        var b, c, d = [];
                        for (c = a.settings.textcolor_map || [
                            "var(--visiv-system-red)", "Red",
                            "var(--visiv-system-orange)", "Orange",
                            "var(--visiv-system-yellow)", "Yellow",
                            "var(--visiv-system-green)", "Green",
                            "var(--visiv-system-cyan)", "Cyan",
                            "var(--visiv-system-blue)", "Blue",
                            "var(--visiv-system-purple)", "Purple",
                            "var(--visiv-system-violet)", "Violet",
                            "var(--visiv-system-red-dark)", "Dark Red",
                            "var(--visiv-system-orange-dark)", "Dark Orange",
                            "var(--visiv-system-yellow-dark)", "Dark Yellow",
                            "var(--visiv-system-green-dark)", "Dark Green",
                            "var(--visiv-system-cyan-dark)", "Dark Cyan",
                            "var(--visiv-system-blue-dark)", "Dark Blue",
                            "var(--visiv-system-purple-dark)", "Dark Purple",
                            "var(--visiv-system-violet-dark)", "Dark Violet",
                            "var(--visiv-branding-base-color)", "Branding Base Color",
                            "var(--visiv-branding-base-color-dark)", "Branding Base Color Dark",
                            "var(--visiv-branding-base-color-light)", "Branding Base Color Light",
                            "var(--visiv-branding-base-color)", "Branding Base Text Color",
                            "var(--visiv-branding-accent-color)", "Branding Accent Color",
                            "var(--visiv-branding-accent-color-dark)", "Branding Accent Color Dark",
                            "var(--visiv-branding-accent-color-light)", "Branding Accent Color Light",
                            "var(--visiv-branding-accent-color)", "Branding Accent Text Color",
                            "var(--visiv-theme-base-1-back-color)", "Base 1 Back Color",
                            "var(--visiv-theme-base-2-back-color)", "Base 2 Back Color",
                            "var(--visiv-theme-base-3-back-color)", "Base 3 Back Color",
                            "var(--visiv-theme-base-4-back-color)", "Base 4 Back Color",
                            "var(--visiv-theme-base-5-back-color)", "Base 5 Back Color",
                            "var(--visiv-system-grey-dark)", "Dark Grey",
                            "var(--visiv-system-grey)", "Grey",
                            "var(--visiv-system-grey-light)", "Light Grey",
                            "var(--visiv-theme-base-1-text-color)", "Base 1 Text Color",
                            "var(--visiv-theme-base-2-text-color)", "Base 2 Text Color",
                            "var(--visiv-theme-base-3-text-color)", "Base 3 Text Color",
                            "var(--visiv-theme-base-4-text-color)", "Base 4 Text Color",
                            "var(--visiv-theme-base-5-text-color)", "Base 5 Text Color",
                            "var(--visiv-system-black)", "Black",
                            "var(--visiv-system-white)", "White"
                        ], b = 0; b < c.length; b += 2)
                            d.push({
                                text: c[b + 1],
                                color: c[b]
                            });
                        return d;
                    }
                    function d() {
                        function b(a, b) {
                            var c = "transparent" == a;
                            return '<td class="mce-grid-cell' + (c ? " mce-colorbtn-trans" : "") + '"><div id="' + n + "-" + o++ + '" data-mce-color="' + (a ? a : "") + '" role="option" tabIndex="-1" style="' + (a ? "background-color: " + a : "") + '" title="' + tinymce.translate(b) + '">' + (c ? "&#215;" : "") + "</div></td>";
                        }
                        var d, e, f, g, h, k, l, m = this, n = m._id, o = 0;
                        for (d = c(), d.push({
                            text: tinymce.translate("No color"),
                            color: "transparent"
                        }), f = '<table class="mce-grid mce-grid-border mce-colorbutton-grid" role="list" cellspacing="0"><tbody>', g = d.length - 1, k = 0; j > k; k++) {
                            for (f += "<tr>", h = 0; i > h; h++)
                                l = k * i + h, l > g ? f += "<td></td>" : (e = d[l], f += b(e.color, e.text));
                            f += "</tr>";
                        }
                        if (a.settings.color_picker_callback) {
                            for (f += '<tr><td colspan="' + i + '" class="mce-custom-color-btn"><div id="' + n + '-c" class="mce-widget mce-btn mce-btn-small mce-btn-flat" role="button" tabindex="-1" aria-labelledby="' + n + '-c" style="width: 100%"><button type="button" role="presentation" tabindex="-1">' + tinymce.translate("Custom...") + "</button></div></td></tr>", f += "<tr>", h = 0; i > h; h++)
                                f += b("", "Custom color");
                            f += "</tr>";
                        }
                        return f += "</tbody></table>";
                    }
                    function e(b, c) {
                        a.undoManager.transact(function () {
                            a.focus(), a.formatter.apply(b, {
                                value: c
                            }), a.nodeChanged();
                        });
                    }
                    function f(b) {
                        a.undoManager.transact(function () {
                            a.focus(), a.formatter.remove(b, {
                                value: null
                            }, null, !0), a.nodeChanged();
                        });
                    }
                    function g(c) {
                        function d(a) {
                            k.hidePanel(), k.color(a), e(k.settings.format, a);
                        }
                        function g() {
                            k.hidePanel(), k.resetColor(), f(k.settings.format);
                        }
                        function h(a, b) {
                            a.style.background = b, a.setAttribute("data-mce-color", b);
                        }
                        var j, k = this.parent();
                        tinymce.DOM.getParent(c.target, ".mce-custom-color-btn") && (k.hidePanel(), a.settings.color_picker_callback.call(a, function (a) {
                            var b, c, e, f = k.panel.getEl().getElementsByTagName("table")[0];
                            for (b = tinymce.map(f.rows[f.rows.length - 1].childNodes, function (a) {
                                return a.firstChild;
                            }), e = 0; e < b.length && (c = b[e], c.getAttribute("data-mce-color")); e++)
                                ;
                            if (e == i)
                                for (e = 0; i - 1 > e; e++)
                                    h(b[e], b[e + 1].getAttribute("data-mce-color"));
                            h(c, a), d(a);
                        }, b(k.settings.format))), j = c.target.getAttribute("data-mce-color"), j ? (this.lastId && document.getElementById(this.lastId).setAttribute("aria-selected", !1), c.target.setAttribute("aria-selected", !0), this.lastId = c.target.id, "transparent" == j ? g() : d(j)) : null !== j && k.hidePanel();
                    }
                    function h() {
                        var a = this;
                        a._color ? e(a.settings.format, a._color) : f(a.settings.format);
                    }
                    var i, j;
                    j = a.settings.textcolor_rows || 5, i = a.settings.textcolor_cols || 8, a.addButton("forecolor", {
                        type: "colorbutton",
                        tooltip: "Text color",
                        format: "forecolor",
                        panel: {
                            role: "application",
                            ariaRemember: !0,
                            html: d,
                            onclick: g
                        },
                        onclick: h
                    }), a.addButton("backcolor", {
                        type: "colorbutton",
                        tooltip: "Background color",
                        format: "hilitecolor",
                        panel: {
                            role: "application",
                            ariaRemember: !0,
                            html: d,
                            onclick: g
                        },
                        onclick: h
                    });
                });
            });
        })(Mce = Shared.Mce || (Shared.Mce = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Navigate;
        (function (Navigate) {
            class ChangeMonitor extends PDJS.Core.Model {
                constructor(options = {}) {
                    super(options);
                    this.m_anchorClick = (e) => { this.onAnchorClick(e); };
                    this.validators = new Navigate.ChangeMonitorValidatorCollection();
                    if (this.captureAnchorNavigation) {
                        this.addAnchorNavigationHandlers();
                    }
                }
                get captureAnchorNavigation() {
                    return this.state.get("captureAnchorNavigation", false);
                }
                get promptCallback() {
                    return this.state.get("prompt", (fn) => { this.defaultPrompt(fn); });
                }
                get proceedCallback() {
                    return this.state.get("proceed", () => { });
                }
                get validators() {
                    return this.m_validators;
                }
                set validators(value) {
                    this.m_validators = value;
                }
                go(e) {
                    this.attemptNavigate(e);
                }
                destroy() {
                    this.removeAnchorNavigationHandlers();
                }
                addAnchorNavigationHandlers() {
                    $(document).on("click", "A", this.m_anchorClick);
                }
                removeAnchorNavigationHandlers() {
                    $(document).off("click", "A", this.m_anchorClick);
                }
                attemptNavigate(args) {
                    var _a;
                    if (((_a = document === null || document === void 0 ? void 0 : document.activeElement) === null || _a === void 0 ? void 0 : _a.nodeName) !== "BODY") {
                        document.activeElement.blur();
                    }
                    if (args == null || args.directive == null) {
                        return;
                    }
                    switch (true) {
                        case _.isString(args.directive):
                            this.goUrl(args);
                            break;
                        case _.isFunction(args.directive):
                            this.goFunction(args);
                            break;
                        case _.isObject(args.directive):
                            this.goAnchor(args);
                            break;
                    }
                }
                goUrl(args) {
                    this.canGo(() => {
                        window.location.href = Jade.Path.resolve(args.directive);
                    }, args);
                }
                goFunction(args) {
                    this.canGo(() => {
                        args.directive();
                    }, args);
                }
                goAnchor(args) {
                    let e = args.directive;
                    let anchor = e.target;
                    if (this.isObservableAnchor(anchor)) {
                        e.preventDefault();
                        this.canGo(() => {
                            window.location.href = anchor.href;
                        }, args);
                    }
                }
                canGo(fn, e) {
                    let error = _.isFunction(e.error)
                        ? e.error : (() => { });
                    if (this.validators.hasChanges()) {
                        error();
                        this.promptCallback(fn);
                        return false;
                    }
                    fn(e.arguments);
                    return true;
                }
                isObservableAnchor(element) {
                    return element.tagName === "A"
                        && element.href !== null
                        && element.href.length !== 0
                        && !element.href.match(/\#$/);
                }
                defaultPrompt(fn) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        title: "Unsaved Changes Detected",
                        message: "There are unsaved changes. Discard changes and continue?",
                        select: (e) => {
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                                this.validators.reset();
                                this.proceedCallback();
                                fn();
                            }
                            e.close();
                        }
                    });
                }
                onAnchorClick(e) {
                    if (this.isObservableAnchor(e.target)) {
                        this.go({
                            directive: e,
                        });
                    }
                }
            }
            Navigate.ChangeMonitor = ChangeMonitor;
        })(Navigate = Shared.Navigate || (Shared.Navigate = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Navigate;
        (function (Navigate) {
            class ChangeMonitorValidator extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                }
                get changesCallback() {
                    return this.state.get("changes", () => { return false; });
                }
                get resetCallback() {
                    return this.state.get("reset", () => { return false; });
                }
                hasChanges() {
                    return this.changesCallback();
                }
                reset() {
                    this.resetCallback();
                }
            }
            Navigate.ChangeMonitorValidator = ChangeMonitorValidator;
        })(Navigate = Shared.Navigate || (Shared.Navigate = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Navigate;
        (function (Navigate) {
            class ChangeMonitorValidatorCollection extends Jade.Collection {
                hasChanges() {
                    let result = false;
                    this.each(validator => {
                        if (!result) {
                            result = validator.hasChanges();
                        }
                    });
                    return result;
                }
                reset() {
                    this.each(validator => {
                        validator.reset();
                    });
                }
            }
            Navigate.ChangeMonitorValidatorCollection = ChangeMonitorValidatorCollection;
        })(Navigate = Shared.Navigate || (Shared.Navigate = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Navigate;
        (function (Navigate) {
            class TreeViewProxy {
                constructor(options) {
                    var _a, _b;
                    this.m_changeCallback = (_b = (_a = options.tree) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.change;
                    this.m_monitor = options.monitor;
                    this.m_suppressEvent = false;
                    this.m_tree = options.tree;
                    this.tree.setOptions({
                        change: (e) => { this.changeHandler(e); },
                        select: (e) => { this.selectHandler(e); }
                    });
                }
                get changeCallback() {
                    return this.m_changeCallback;
                }
                get monitor() {
                    this.ensureMonitor();
                    return this.m_monitor;
                }
                get suppressEvent() {
                    return this.m_suppressEvent;
                }
                set suppressEvent(value) {
                    this.m_suppressEvent = value;
                }
                get tree() {
                    return this.m_tree;
                }
                select(arg1, options = {}) {
                    let item = null;
                    let node = null;
                    if (arg1 == undefined) {
                        node = this.tree.select();
                        item = this.tree.dataItem(node);
                    }
                    if (!(arg1 instanceof jQuery)) {
                        node = this.tree.findByUid(arg1);
                    }
                    if (node != null && node.length > 0) {
                        this.suppressEvent = options.silent || false;
                        this.tree.select(node);
                    }
                }
                changeHandler(e) {
                    if (this.suppressEvent) {
                        this.suppressEvent = false;
                        return;
                    }
                    this.changeCallback(e);
                }
                selectHandler(e) {
                    this.monitor.go({
                        directive: () => {
                            this.m_suppressEvent = false;
                            this.select($(e.node).data("uid"));
                        },
                        error: () => {
                            this.suppressEvent = true;
                            e.preventDefault();
                            setTimeout(() => {
                                $(e.node).find(".k-state-focused").removeClass("k-state-focused");
                            });
                        }
                    });
                }
                ensureMonitor() {
                    if (this.m_monitor == null) {
                        this.m_monitor = PDJS.Manage.Modules.instance.current.monitor;
                    }
                }
            }
            Navigate.TreeViewProxy = TreeViewProxy;
        })(Navigate = Shared.Navigate || (Shared.Navigate = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Personalization;
        (function (Personalization) {
            class Preferences {
                constructor(options) {
                    this.m_state = new Jade.StateBag(options);
                    this.m_state.bind("change", () => { this.onStateChanged(); });
                }
                static get current() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                get state() {
                    return this.m_state;
                }
                get contentListDoubleClickBehavior() {
                    return this.state.get("contentListDoubleClickBehavior", 0);
                }
                get explorerAncestorDisplayMode() {
                    return this.state.get("explorerAncestorDisplayMode", 0);
                }
                get globalDoubleClickBehavior() {
                    return this.state.get("globalDoubleClickBehavior", 0);
                }
                get openLastViewedExplorerFolder() {
                    return this.state.get("openLastViewedExplorerFolder", false);
                }
                load(options) {
                    this.state.set(options);
                }
                onStateChanged() {
                }
                static ensureInstance() {
                    if (!this.m_instance) {
                        this.m_instance = new Preferences();
                    }
                }
            }
            Personalization.Preferences = Preferences;
        })(Personalization = Shared.Personalization || (Shared.Personalization = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Plugins;
        (function (Plugins) {
            class Plugin {
                constructor(options) {
                    this.m_options = _.extend({
                        id: null,
                        name: null,
                        version: "0.0.0.0",
                        description: null
                    }, options);
                    this.m_actions = new PDJS.Shared.Actions.ActionManager({
                        pluginId: this.id
                    });
                    this.m_modules = new Plugins.PluginModulesCollection();
                }
                get id() {
                    return this.m_options.id;
                }
                get name() {
                    return this.m_options.name;
                }
                get description() {
                    return this.m_options.description;
                }
                get version() {
                    return this.m_options.version;
                }
                get actions() {
                    return this.m_actions;
                }
                get modules() {
                    return this.m_modules;
                }
                toJSON() {
                    return {
                        id: this.id,
                        name: this.name,
                        description: this.description,
                        version: this.version
                    };
                }
            }
            Plugins.Plugin = Plugin;
        })(Plugins = Shared.Plugins || (Shared.Plugins = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Plugins;
        (function (Plugins) {
            class PluginManager {
                constructor() {
                    this.m_plugins = {};
                }
                static get instance() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                get plugins() {
                    return this.m_plugins;
                }
                addPlugin(plugin) {
                    if (!(plugin.id in this.plugins)) {
                        this.plugins[plugin.id] = plugin;
                    }
                }
                removePlugin(id) {
                    if (id in this.plugins) {
                        delete this.plugins[id];
                    }
                }
                getPlugin(id) {
                    var result = null;
                    if (id != null && id in this.plugins) {
                        result = this.plugins[id];
                    }
                    return result;
                }
                getPlugins() {
                    var result = [];
                    for (let key in this.plugins) {
                        result.push(this.plugins[key]);
                    }
                    let builtin = result.find(plugin => {
                        return plugin.id == "builtin";
                    });
                    result = result.filter(plugin => {
                        return plugin.id != "builtin";
                    });
                    if (builtin != null) {
                        result.unshift(builtin);
                    }
                    return result;
                }
                static ensureInstance() {
                    if (this.m_instance == null) {
                        this.m_instance = new PluginManager();
                    }
                }
            }
            Plugins.PluginManager = PluginManager;
        })(Plugins = Shared.Plugins || (Shared.Plugins = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Plugins;
        (function (Plugins) {
            class PluginModulesCollection {
                constructor() {
                    this.m_scripts = {};
                }
                get default() {
                    return null;
                }
                add(key, value) {
                    let containsKeys = null;
                    if (!this.m_scripts.hasOwnProperty(key)) {
                        containsKeys = this.containsKeys();
                        this.m_scripts[key] = value;
                        if (!containsKeys) {
                            this.m_scripts = value;
                        }
                    }
                }
                remove(key, value) {
                    if (this.m_scripts[key] != undefined) {
                        delete this.m_scripts[key];
                    }
                }
                get(key) {
                    let result = null;
                    if (this.containsKey(key)) {
                        result = this.m_scripts[key];
                    }
                    return result;
                }
                containsKeys() {
                    let result = false;
                    for (let key in this.m_scripts) {
                        if (this.m_scripts.hasOwnProperty(key)) {
                            result = true;
                            break;
                        }
                    }
                    return result;
                }
                containsKey(key) {
                    let x = PDJS.Shared.Plugins.PluginModulesCollection;
                    let y = new x();
                    let result = false;
                    for (let key in this.m_scripts) {
                        if (this.m_scripts.hasOwnProperty(key)) {
                            result = true;
                            break;
                        }
                    }
                    return result;
                }
            }
            Plugins.PluginModulesCollection = PluginModulesCollection;
        })(Plugins = Shared.Plugins || (Shared.Plugins = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Plugins;
        (function (Plugins) {
            class PluginRouter {
                static get instance() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                registerRoutes() {
                    window["Path"].map("#/plugin/:pluginId(/:moduleId)(/:targetId)(/:args)").to(function (e) {
                        PDJS.Manage.ModuleLoader.load(window.location.hash);
                    });
                }
                static ensureInstance() {
                    if (!this.m_instance) {
                        this.m_instance = new PluginRouter();
                    }
                }
            }
            Plugins.PluginRouter = PluginRouter;
            PDJS.Application.onStart(() => {
                PluginRouter.instance.registerRoutes();
            });
        })(Plugins = Shared.Plugins || (Shared.Plugins = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Routing;
        (function (Routing) {
            class Router {
                static get routes() {
                    return Routing.Routes.current.items;
                }
                static init() {
                    navigation.addEventListener('navigate', (e) => {
                        if (this.shouldNotIntercept(e))
                            return;
                        let route = this.routes.find(route => route.canHandle(e));
                        if (route == null) {
                            return;
                        }
                        let handler = route.execute(e);
                        this.addCustomEventProperties(e);
                        if (handler) {
                            try {
                                e.intercept({
                                    handler: handler
                                });
                            }
                            catch (e) {
                                throw e;
                            }
                            return;
                        }
                    });
                }
                static addCustomEventProperties(event) {
                    var _a;
                    let requestId = (_a = event.destination.getState()) === null || _a === void 0 ? void 0 : _a.requestId;
                    let extendedState = !Jade.String.isNullOrWhiteSpace(requestId) ?
                        this.m_extendedState[requestId] || {} : {};
                    event.extendedState = extendedState;
                    event.currentUrl = window.location.href;
                    delete this.m_extendedState[requestId];
                }
                static navigate(url, state = {}, extendedState = {}) {
                    let requestId = Jade.Guid.new();
                    this.m_extendedState[requestId] = extendedState;
                    navigation.navigate(url, {
                        state: _.extend({ requestId: requestId }, state),
                    });
                }
                static shouldNotIntercept(event) {
                    return Jade.String.isNullOrWhiteSpace(event.destination.url) || event.downloadRequest != null;
                }
            }
            Router.m_extendedState = {};
            Routing.Router = Router;
            PDJS.Application.onStart(() => {
                Router.init();
            });
        })(Routing = Shared.Routing || (Shared.Routing = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Routing;
        (function (Routing) {
            class Routes {
                constructor() {
                    this.m_routes = [];
                }
                static get current() {
                    this.ensureInstance();
                    return this.m_instance;
                }
                get items() {
                    return this.m_routes.slice(0);
                }
                add(route) {
                    this.m_routes.push(route);
                }
                remove(route) {
                    let index = this.m_routes.indexOf(route);
                    if (index > -1) {
                        this.m_routes.splice(index, 1);
                    }
                }
                static ensureInstance() {
                    if (this.m_instance == null) {
                        this.m_instance = new Routes();
                    }
                }
            }
            Routing.Routes = Routes;
        })(Routing = Shared.Routing || (Shared.Routing = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Rules;
        (function (Rules) {
            class ScriptAction {
                constructor(parent) {
                    this.m_response = parent.response;
                    this.m_responseType = parent.type;
                }
                static get actions() {
                    return this.m_actions;
                }
                get response() {
                    return this.m_response;
                }
                get responseType() {
                    return this.m_responseType;
                }
                canHandle() {
                    return false;
                }
                handle() {
                    return false;
                }
            }
            ScriptAction.m_actions = [];
            Rules.ScriptAction = ScriptAction;
            PDJS.Application.onStart(() => {
                ScriptAction.actions.push(Rules.ScriptRedirect);
                ScriptAction.actions.push(Rules.ScriptPrompt);
            });
        })(Rules = Shared.Rules || (Shared.Rules = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Rules;
        (function (Rules) {
            class ScriptPrompt extends Rules.ScriptAction {
                get prompt() {
                    return this.response.prompt;
                }
                handle() {
                    if (!this.canHandle()) {
                        return;
                    }
                    switch (this.prompt.mode) {
                        case "default":
                            this.showDefaultDialog();
                            break;
                        case "radio":
                            this.showRadioDialog();
                            break;
                    }
                    return true;
                }
                canHandle() {
                    return this.prompt != null;
                }
                onRedirectEntity(entityId, folderId) {
                    switch (true) {
                        case folderId != null:
                            window.location.href = Jade.Path.resolve(`~/explore/${entityId}/folder/${folderId}`);
                            break;
                        case folderId == null:
                            window.location.href = Jade.Path.resolve(`~/explore/${entityId}`);
                            break;
                    }
                }
                onRedirectUrl(url) {
                    if (!Jade.String.isNullOrWhiteSpace(url)) {
                        window.location.href = Jade.Path.resolve(url);
                    }
                }
                onExecuteScript(script) {
                    let service = new PDJS.Services.Rules.RulesService();
                    let context = this.prompt.context || {};
                    let values = {};
                    if (script.contextId != null) {
                        values[script.contextId] = script.contextValue;
                    }
                    service.executeScriptByName({
                        scriptName: script.name,
                        context: {
                            entityId: context.entityId,
                            extensionId: context.extensionId,
                            rowId: context.rowId,
                            values: values
                        },
                        success: (e) => {
                            let response = this.createScriptResponse(e.data);
                            this.handleRuleScriptOnSuccess(response);
                        }
                    });
                }
                createScriptResponse(e) {
                    return new (this.responseType)(e);
                }
                handleRuleScriptOnSuccess(e) {
                    e.handle(e.arguments);
                }
                executeOption(value) {
                    let promptOption = this.prompt.options[value];
                    if (promptOption == null) {
                        return;
                    }
                    if (!Jade.String.isNullOrWhiteSpace(promptOption.url)) {
                        this.onRedirectUrl(promptOption.url);
                        return;
                    }
                    if (promptOption.entityId !== null) {
                        this.onRedirectEntity(promptOption.entityId, promptOption.folderId);
                        return;
                    }
                    if (promptOption.script != null) {
                        this.onExecuteScript(promptOption.script);
                        return;
                    }
                }
                getDialogStyle() {
                    switch (this.prompt.type) {
                        case "error":
                            return Jade.UI.Dialogs.MessageDialogStyle.Error;
                        case "info":
                            return Jade.UI.Dialogs.MessageDialogStyle.Information;
                        case "question":
                            return Jade.UI.Dialogs.MessageDialogStyle.Question;
                        case "success":
                            return Jade.UI.Dialogs.MessageDialogStyle.Success;
                        case "warn":
                            return Jade.UI.Dialogs.MessageDialogStyle.Warning;
                    }
                }
                getDialogButtonStyle() {
                    return this.prompt.allowCancel ?
                        Jade.UI.Dialogs.MessageDialogButtonStyle.OKCancel :
                        Jade.UI.Dialogs.MessageDialogButtonStyle.OK;
                }
                replaceEscapedCharacters(text) {
                    if (text != null) {
                        return text.replaceAll("\\n", "<br/>");
                    }
                    return text;
                }
                showDefaultDialog() {
                    let buttons = [];
                    this.prompt.options.forEach((option, index) => {
                        buttons.push(this.createDialogButton(option, index));
                    });
                    if (buttons.length === 0) {
                        buttons.push(this.createDialogButton({ label: "OK" }, 0));
                    }
                    Jade.UI.Dialogs.MessageDialog.open({
                        title: this.prompt.title,
                        dialogStyle: this.getDialogStyle(),
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.None,
                        message: this.replaceEscapedCharacters(this.prompt.message),
                        buttons: buttons,
                        select: (sender, e) => {
                            sender.close();
                            this.executeOption(parseInt(sender.button.name));
                        }
                    });
                }
                createDialogButton(option, index) {
                    return {
                        label: option.label,
                        name: index.toString(),
                        value: index
                    };
                }
                showRadioDialog() {
                    let items = [];
                    this.prompt.options.forEach((option, index) => {
                        items.push(this.createRadioOption(option, index));
                    });
                    Jade.UI.Dialogs.MultiChoiceDialog.open({
                        title: this.prompt.title,
                        dialogStyle: this.getDialogStyle(),
                        dialogButtons: this.getDialogButtonStyle(),
                        items: items,
                        header: this.replaceEscapedCharacters(this.prompt.message),
                        select: (sender, e) => {
                            sender.close();
                            this.executeOption(e.selection.value);
                        }
                    });
                }
                createRadioOption(option, index) {
                    return {
                        value: index,
                        message: this.replaceEscapedCharacters(option.detail) || "",
                        title: this.replaceEscapedCharacters(option.label),
                        selected: index === 0
                    };
                }
            }
            Rules.ScriptPrompt = ScriptPrompt;
        })(Rules = Shared.Rules || (Shared.Rules = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Rules;
        (function (Rules) {
            class ScriptRedirect extends Rules.ScriptAction {
                get redirect() {
                    return this.response.redirect;
                }
                handle() {
                    if (!this.canHandle()) {
                        return;
                    }
                    if (this.executeRedirectUrl(this.response.redirect.url)) {
                        return true;
                    }
                    this.executeRedirectEntity();
                    return true;
                }
                canHandle() {
                    return this.redirect != null;
                }
                executeRedirectUrl(url) {
                    if (!Jade.String.isNullOrWhiteSpace(url)) {
                        window.location.href = Jade.Path.resolve(this.redirect.url);
                        return true;
                    }
                    return false;
                }
                executeRedirectEntity() {
                    let entityId = this.redirect.entityId;
                    let folderId = this.redirect.folderId;
                    switch (true) {
                        case folderId != null:
                            window.location.href = Jade.Path.resolve(`~/explore/${entityId}/folder/${folderId}`);
                            break;
                        case folderId == null:
                            window.location.href = Jade.Path.resolve(`~/explore/${entityId}`);
                            break;
                    }
                }
            }
            Rules.ScriptRedirect = ScriptRedirect;
        })(Rules = Shared.Rules || (Shared.Rules = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AceEditorDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get ace() {
                    return this.m_ace;
                }
                get acl() {
                    return this.m_acl;
                }
                get editor() {
                    return this.m_editor;
                }
                get buttonOk() {
                    return this.node.find("button[data-command=ok]");
                }
                get buttonCancel() {
                    return this.node.find("button[data-command=cancel]");
                }
                template() {
                    return `<div class="-pdjs-ace-editor-dialog">
                        <div role="body">
                            <div role="editor"></div>
                        </div>
                        <div role="deck">
                            <button
                                data-command="ok"
                                class="-jadeui-dialog-button">
                                OK
                            </button>
                            <button 
                                data-command="cancel"
                                class="-jadeui-dialog-button">
                                Cancel
                            </button>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.acl_init();
                    this.editor_init();
                    this.buttonCancel.on(Jade.BrowserEvent.CLICK, () => {
                        this.close();
                    });
                    this.buttonOk.on(Jade.BrowserEvent.CLICK, () => {
                        this.close({
                            name: "ok",
                            data: {
                                ace: this.ace
                            }
                        });
                    });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.editor.loadAce(this.ace);
                }
                getDefaultOptions() {
                    return {
                        entityId: null,
                        identity: null,
                        title: "Creator Permissions",
                        height: "300px",
                        minHeight: "300px",
                        width: "500px",
                        minWidth: "300px",
                        resizable: true
                    };
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Security.AccessControlAce({
                        insertAt: "div[role=editor]",
                        acl: this.acl
                    });
                    this.controls.add(this.m_editor);
                }
                acl_init() {
                    this.m_ace = new PDJS.Core.Security.Ace(this.state.get("ace"));
                    this.m_acl = new PDJS.Core.Security.AccessControlList({
                        aces: [this.m_ace.toJSON()],
                        permissions: this.state.get("permissions"),
                        commit: () => {
                        }
                    });
                }
                static open(options) {
                    return new AceEditorDialog(options);
                }
            }
            Security.AceEditorDialog = AceEditorDialog;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            let IPermissionCoverage;
            (function (IPermissionCoverage) {
                IPermissionCoverage["None"] = "none";
                IPermissionCoverage["Partial"] = "partial";
                IPermissionCoverage["Allow"] = "allow";
                IPermissionCoverage["Deny"] = "deny";
            })(IPermissionCoverage = Security.IPermissionCoverage || (Security.IPermissionCoverage = {}));
            let PermissionExpanded;
            (function (PermissionExpanded) {
                PermissionExpanded[PermissionExpanded["None"] = 0] = "None";
                PermissionExpanded[PermissionExpanded["Read"] = 1] = "Read";
                PermissionExpanded[PermissionExpanded["EditFormData"] = 2] = "EditFormData";
                PermissionExpanded[PermissionExpanded["AddFiles"] = 4] = "AddFiles";
                PermissionExpanded[PermissionExpanded["AddChildren"] = 8] = "AddChildren";
                PermissionExpanded[PermissionExpanded["DeleteListItem"] = 16] = "DeleteListItem";
                PermissionExpanded[PermissionExpanded["DeleteFile"] = 32] = "DeleteFile";
                PermissionExpanded[PermissionExpanded["ReplaceFile"] = 64] = "ReplaceFile";
                PermissionExpanded[PermissionExpanded["ExecuteProcess"] = 512] = "ExecuteProcess";
                PermissionExpanded[PermissionExpanded["ChangePermissions"] = 4096] = "ChangePermissions";
                PermissionExpanded[PermissionExpanded["ChangeEntityStatus"] = 8192] = "ChangeEntityStatus";
                PermissionExpanded[PermissionExpanded["ReparentEntity"] = 16384] = "ReparentEntity";
            })(PermissionExpanded = Security.PermissionExpanded || (Security.PermissionExpanded = {}));
            let PermissionBasic;
            (function (PermissionBasic) {
                PermissionBasic[PermissionBasic["None"] = 0] = "None";
                PermissionBasic[PermissionBasic["Read"] = 1] = "Read";
                PermissionBasic[PermissionBasic["Write"] = 14] = "Write";
                PermissionBasic[PermissionBasic["Delete"] = 112] = "Delete";
                PermissionBasic[PermissionBasic["Manage"] = 512] = "Manage";
                PermissionBasic[PermissionBasic["Administrate"] = 28672] = "Administrate";
            })(PermissionBasic = Security.PermissionBasic || (Security.PermissionBasic = {}));
            class EntityPermissions {
                static get list() {
                    return [
                        {
                            name: "Read",
                            value: PermissionBasic.Read,
                            items: [PermissionExpanded.Read]
                        },
                        {
                            name: "Write",
                            value: PermissionBasic.Write,
                            items: [
                                PermissionExpanded.EditFormData,
                                PermissionExpanded.AddFiles,
                                PermissionExpanded.AddChildren
                            ]
                        },
                        {
                            name: "Delete",
                            value: PermissionBasic.Delete,
                            items: [
                                PermissionExpanded.DeleteFile,
                                PermissionExpanded.DeleteListItem,
                                PermissionExpanded.ReplaceFile
                            ]
                        },
                        {
                            name: "Manage",
                            value: PermissionBasic.Manage,
                            items: [PermissionExpanded.ExecuteProcess]
                        },
                        {
                            name: "Administrate",
                            value: PermissionBasic.Administrate,
                            items: [
                                PermissionExpanded.ChangePermissions,
                                PermissionExpanded.ChangeEntityStatus,
                                PermissionExpanded.ReparentEntity
                            ]
                        }
                    ];
                }
                static getCoverage(args) {
                    let isFullyAllowed = this.isFullyActivated(args.info.items, args.allow);
                    if (isFullyAllowed) {
                        return IPermissionCoverage.Allow;
                    }
                    let isFullyDenied = this.isFullyActivated(args.info.items, args.deny);
                    if (isFullyDenied) {
                        return IPermissionCoverage.Deny;
                    }
                    let isPartial = false;
                    args.info.items.forEach(permission => {
                        if (!isPartial) {
                            isPartial = (args.allow & permission) == permission ||
                                (args.deny & permission) == permission;
                        }
                    });
                    if (isPartial) {
                        return IPermissionCoverage.Partial;
                    }
                    return IPermissionCoverage.None;
                }
                static isFullyActivated(permissionList, currentGrant) {
                    let result = true;
                    permissionList.forEach(permission => {
                        result = result &&
                            (currentGrant & permission) == permission;
                    });
                    return result;
                }
            }
            Security.EntityPermissions = EntityPermissions;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class IdentityBrowserDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get filters() {
                    return this.state.get("filters", []);
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get selectionMode() {
                    return this.state.get("selectionMode", PD.Web.UI.Controls.GridSelectionMode.multiple);
                }
                get selections() {
                    return this.m_grid.getSelections().toArray();
                }
                template() {
                    return super.template(`
                <div class="-pdjs-shared-security-identity-browser-dialog">
                    <div data-role="grid"></div>
                    <div>
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.startUp();
                    this.grid_init();
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                }
                getDefaultOptions() {
                    return {
                        title: "Select | Identity",
                        height: 400,
                        width: 600,
                        maximized: false
                    };
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        container: this.node.find("[data-role=grid]"),
                        selectionMode: this.selectionMode,
                        viewStateId: this.viewStateId,
                        selectOnRightClick: false,
                        defaultSelectionEnabled: true,
                        selection: {
                            map: (e) => {
                                return _.map(e.selections.toArray(), (item, index) => {
                                    return {
                                        id: item.ObjectId,
                                        name: item.ObjectName,
                                        accountId: item.AccountID,
                                        type: item.ObjectType
                                    };
                                });
                            }
                        },
                        dblclick: (e) => {
                            this.closeAndReturn();
                        },
                        needContext: (e) => {
                            _.each(this.filters, (item) => {
                                e.filters[e.filters.length] = item.toJSON();
                            });
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.selections.length > -1) {
                        this.close({
                            name: "ok",
                            data: this.selections
                        });
                    }
                    else {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            title: "No Identity Selected",
                            message: "No identity has been selected. Select an identity type and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                startUp() {
                    let service = new PDJS.Services.Views.ViewService();
                    service.getViewStateId({
                        viewCustomId: PDJS.Services.Views.BuiltInViews.IDENTITY_SELECTION,
                        success: (e) => {
                            this.viewStateId = e.data.viewStateId;
                        }
                    });
                }
                static open(options) {
                    return new IdentityBrowserDialog(options);
                }
            }
            Security.IdentityBrowserDialog = IdentityBrowserDialog;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessContol extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get aclEditor() {
                    return this.m_aclEditor;
                }
                set aclEditor(value) {
                    this.m_aclEditor = value;
                }
                get aclEditorNode() {
                    return this.node.find("div[role=acl]");
                }
                get aceEditor() {
                    return this.m_aceEditor;
                }
                set aceEditor(value) {
                    this.m_aceEditor = value;
                }
                get aceEditorNode() {
                    return this.node.find("div[role=ace]");
                }
                get acl() {
                    return this.state.get("acl");
                }
                ;
                get enableAddAndRemove() {
                    return this.state.get("enableAddAndRemove");
                }
                get enableAdvanced() {
                    return this.state.get("enableAdvanced");
                }
                get enableEffectivePermissions() {
                    return this.state.get("enableEffectivePermissions");
                }
                get readOnly() {
                    return this.state.get("readonly", false);
                }
                get splitter() {
                    return this.splitterNode.data("kendoSplitter");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                get securableId() {
                    return this.state.get("securableId");
                }
                get effectivePermissions() {
                    return this.state.get("effectivePermissions", {
                        entityId: this.securableId,
                        userId: PDJS.Profiles.Profile.current.identity.id,
                        userDisplayName: PDJS.Profiles.Profile.current.identity.accountName
                    });
                }
                set effectivePermissions(value) {
                    this.state.get("effectivePermissions", value);
                }
                template() {
                    return `<div class="-pdjs-shared-security-access-control">
                        <div role="splitter">
                            <div role="pane-1">
                                <div role="pane-1-content">
                                    <div
                                        role="acl">
                                    </div>
                                    <div
                                        role="toolbar">
                                    </div>
                                </div>
                            </div>
                            <div role="pane-2">
                                <div
                                    role="ace">
                                </div>
                            </div>
                        </div>
                    </div>`;
                }
                resize() {
                    if (this.splitter) {
                        this.splitter.resize();
                    }
                }
                resetSize() {
                    if (this.splitter) {
                        this.splitter.size(".k-pane:first", "50%");
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.aceEditor_init();
                    this.aclEditor_init();
                    this.toolbar_init();
                    this.splitter_init();
                    this.setCommandState();
                }
                aclEditor_init() {
                    this.aclEditor = new Security.AccessControlAcl({
                        container: this.aclEditorNode,
                        acl: this.acl,
                        change: (e) => {
                            if (this.aceEditor) {
                                this.aceEditor.loadAce(e);
                            }
                        }
                    });
                    this.controls.add(this.aclEditor);
                }
                aceEditor_init() {
                    this.aceEditor = new Security.AccessControlAce({
                        container: this.aceEditorNode,
                        acl: this.acl,
                        enabled: this.readOnly,
                        change: (e) => {
                        }
                    });
                    this.controls.add(this.aceEditor);
                }
                splitter_init() {
                    this.splitterNode.kendoSplitter({
                        orientation: "vertical",
                        panes: [
                            {
                                size: "50%",
                                scrollable: false,
                                resizable: true
                            },
                            {
                                scrollable: false,
                                resizable: true
                            },
                        ],
                        resize: (e) => {
                            this.aclEditor.resize();
                            this.aceEditor.resize();
                        }
                    }).data("kendoSplitter");
                }
                toolbar_init() {
                    this.m_toolbar = new Security.AccessControlToolbar({
                        insertAt: "div[role=toolbar]",
                        enableAddAndRemove: this.enableAddAndRemove,
                        enableAdvanced: this.enableAdvanced,
                        enableEffectivePermissions: this.enableEffectivePermissions
                    });
                    this.controls.add(this.m_toolbar);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/shared/security/access-control": {
                            $accessControl: this
                        }
                    }, { force: true, overwrite: true });
                }
            }
            Security.AccessContol = AccessContol;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessControlCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.state.set("$accessControl");
                }
                get accessControl() {
                    return this.state.get("$accessControl");
                }
                get acl() {
                    return this.accessControl.acl;
                }
                get aceGrid() {
                    return this.accessControl.aceEditor.grid;
                }
                get aclGrid() {
                    return this.accessControl.aclEditor.grid;
                }
                get selectedAce() {
                    return this.accessControl.aclEditor.grid.selection;
                }
                setCommandState() {
                    PDJS.Application.instance.contexts.current.commands.setState({
                        "pdjs/shared/security/access-control": {
                            $accessControl: this.accessControl
                        }
                    }, { force: true, overwrite: true });
                }
            }
            Security.AccessControlCommand = AccessControlCommand;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AddAceCommand extends Security.AccessControlCommand {
                onExecute(e) {
                    this.showIdenitiyFinderDialog((e) => {
                        let selection = _.first(e.map(item => {
                            return item.id;
                        }));
                        e.forEach(item => {
                            this.acl.aces.add(new PDJS.Core.Security.Ace(item));
                        });
                        this.acl.commit();
                        this.aclGrid.refresh(true, [selection]);
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "ace/add",
                        tooltip: "Add",
                        label: "Add",
                        icon: "add.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                showIdenitiyFinderDialog(callback) {
                    PDJS.Shared.Security.IdentityBrowserDialog.open({
                        title: "Select | Users and Groups",
                        filters: [
                            PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
                        ],
                        select: {
                            ok: (sender, e) => {
                                callback(e);
                            }
                        }
                    });
                }
            }
            Security.AddAceCommand = AddAceCommand;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class RemoveAceCommand extends Security.AccessControlCommand {
                onExecute(e) {
                    if (!this.selectedAce) {
                        return;
                    }
                    if (this.selectedAce.isInherited) {
                        this.showIdenitiyFinderDialog();
                    }
                    else {
                        this.acl.aces.remove(this.selectedAce);
                        this.acl.commit();
                        this.aclGrid.refresh(true);
                    }
                }
                getDefaultValuesForProps() {
                    return {
                        id: "ace/remove",
                        tooltip: "Remove",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                showIdenitiyFinderDialog() {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.YesNo,
                        title: "Cannot Remove ACE",
                        message: `Inherited entries cannot be removed.<br/><br/>Do you want to remove entity level permissions and reset the entry to entity type inherited permissions only?`,
                        select: (e) => {
                            e.close();
                            if (e.name === Jade.UI.Dialogs.MessageDialogButton.yes) {
                                this.selectedAce.revertToInherited();
                                this.acl.commit();
                                this.aclGrid.refresh(false);
                            }
                        }
                    });
                }
            }
            Security.RemoveAceCommand = RemoveAceCommand;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class ShowAdvancedCommand extends Security.AccessControlCommand {
                onExecute(e) {
                    PDJS.Shared.Security.AdvancedDialog.open({
                        select: {
                            ok: (sender, e) => {
                                this.executeCascade(e.delete, e.replace);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "advanced",
                        tooltip: "Advanced",
                        label: "Advanced",
                        enabled: true,
                        display: "label",
                        iconSetId: "pd"
                    };
                }
                executeCascade(deleteAces, replaceAces) {
                    let service = new PDJS.Services.Entities.EntityService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Advanced | Cascade Permissions",
                        autoCloseOnSuccess: true,
                        taskStart: (args) => {
                            service.cascadePermissions({
                                entityId: this.accessControl.securableId,
                                replace: replaceAces,
                                delete: deleteAces,
                                success: (e) => {
                                    args.startPolling(e.data);
                                },
                                error: (e) => {
                                    args.abort(e.xhr.responseJSON);
                                }
                            });
                        },
                        taskSuccess: (args) => {
                            args.close();
                            PDJS.Shared.MessageStack.instance.success("Permissions applied to children.");
                        }
                    });
                }
            }
            Security.ShowAdvancedCommand = ShowAdvancedCommand;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class ShowEffectivePermissionsCommand extends Security.AccessControlCommand {
                onExecute(e) {
                    this.ensureIdentity();
                    PDJS.Shared.Security.EffectivePermissionsDialog.open({
                        entityId: this.accessControl.securableId,
                        identity: this.m_identity,
                        aces: this.acl.aces.toJSON(),
                        select: {
                            close: (sender, e) => {
                                if (e.identity != null) {
                                    this.m_identity = e.identity;
                                }
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "effective-permissions",
                        tooltip: "Effective Permissions",
                        label: "Effective Permissions",
                        icon: "add.png",
                        enabled: true,
                        display: "label",
                        iconSetId: "pd"
                    };
                }
                ensureIdentity() {
                    if (!this.m_identity) {
                        this.m_identity = {
                            id: PDJS.Profiles.Profile.current.identity.id,
                            name: PDJS.Profiles.Profile.current.identity.accountName,
                            displayName: PDJS.Profiles.Profile.current.identity.displayName
                        };
                    }
                }
            }
            Security.ShowEffectivePermissionsCommand = ShowEffectivePermissionsCommand;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessControlCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/shared/security/access-control");
                }
                registerCommands(e) {
                    e.commands.add(new Security.AddAceCommand());
                    e.commands.add(new Security.RemoveAceCommand());
                    e.commands.add(new Security.ShowAdvancedCommand());
                    e.commands.add(new Security.ShowEffectivePermissionsCommand());
                }
            }
            Security.AccessControlCommands = AccessControlCommands;
            Jade.CommandGroups.add(AccessControlCommands);
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessControlToolbar extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get enableAdvanced() {
                    return this.state.get("enableAdvanced");
                }
                get enableEffectivePermissions() {
                    return this.state.get("enableEffectivePermissions");
                }
                get enableAddAndRemove() {
                    return this.state.get("enableAddAndRemove");
                }
                get advancedButton() {
                    return this.node.find("button[data-id=0]");
                }
                get effectivePermissionsButton() {
                    return this.node.find("button[data-id=1]");
                }
                get addButton() {
                    return this.node.find("button[data-id=2]");
                }
                get removeButton() {
                    return this.node.find("button[data-id=3]");
                }
                get commandContext() {
                    return Jade.Application.instance.contexts.current.commands;
                }
                template() {
                    return `<div class="-pdjs-shared-security-access-control-toolbar">
                        <div>
                            <button data-id="0" class="-pdjs-button">
                                Advanced...
                            </button>
                        </div>
                        <div>
                            <button data-id="1" class="-pdjs-button">
                                Effective Permissions
                            </button>
                        </div>
                        <div></div>
                        <div>
                            <button data-id="2" class="-pdjs-button">
                                Add
                            </button>
                        </div>
                        <div>
                            <button data-id="3" class="-pdjs-button">
                                Remove
                            </button>
                        </div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.enableAdvanced ?
                        this.advancedButton.parent().show() :
                        this.advancedButton.parent().hide();
                    this.enableEffectivePermissions ?
                        this.effectivePermissionsButton.parent().show() :
                        this.effectivePermissionsButton.parent().hide();
                    this.setGridTemplateRows();
                    this.advancedButton.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.commandContext.execute("pdjs/shared/security/access-control:advanced");
                    });
                    this.effectivePermissionsButton.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.commandContext.execute("pdjs/shared/security/access-control:effective-permissions");
                    });
                    this.addButton.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.commandContext.execute("pdjs/shared/security/access-control:ace/add");
                    });
                    this.removeButton.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.commandContext.execute("pdjs/shared/security/access-control:ace/remove");
                    });
                }
                setGridTemplateRows() {
                    let rows = [];
                    this.enableAdvanced ? rows.push("max-content") : null;
                    this.enableEffectivePermissions ? rows.push("max-content") : null;
                    rows.push("auto");
                    rows.push("max-content");
                    rows.push("max-content");
                    this.node.css({
                        gridTemplateColumns: rows.join(" ")
                    });
                }
            }
            Security.AccessControlToolbar = AccessControlToolbar;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            let PermissionsViewType;
            (function (PermissionsViewType) {
                PermissionsViewType["basic"] = "basic";
                PermissionsViewType["extended"] = "extended";
            })(PermissionsViewType = Security.PermissionsViewType || (Security.PermissionsViewType = {}));
            class AccessControlAce extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get acl() {
                    return this.state.get("acl");
                }
                get ace() {
                    return this.m_ace;
                }
                set ace(value) {
                    this.m_ace = value;
                }
                get permissionsType() {
                    return this.permissionsViewNode.val();
                }
                get permissionsViewNode() {
                    return this.node.find("select");
                }
                template() {
                    return `<div class="-pdjs-shared-security-access-control-ace">
                        <div role="head">
                            <div>Permissions</div>
                            <div>View:</div>
                            <div>
                                <select>
                                    <option value="basic">Basic</option>
                                    <option value="extended">Extended</option>
                                </select>
                            </div>
                        </div>
                        <div role="grid"></div>
                    </div>`;
                }
                loadAce(ace) {
                    this.ace = ace;
                    this.grid.loadAce(ace);
                }
                resize() {
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.permissionsViewNode.on(Jade.BrowserEvent.CHANGE, (e) => {
                        e.cancelBubble = true;
                        e.returnValue = false;
                        e.stopPropagation();
                        this.grid.setPermissionsType(this.ace, this.permissionsType);
                    });
                }
                grid_init() {
                    this.m_grid = new Security.AceGrid({
                        insertAt: "div[role=grid]",
                        acl: this.acl
                    });
                    this.controls.add(this.m_grid);
                }
            }
            Security.AccessControlAce = AccessControlAce;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AceGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get dataSource() {
                    return this.m_grid.get_dataSource();
                }
                get grid() {
                    return this.m_grid;
                }
                get checkboxes() {
                    return this.m_checkboxes;
                }
                get acl() {
                    return this.state.get("acl");
                }
                template() {
                    return `<div class='-pdjs-shared-security-access-control-ace-grid'></div>`;
                }
                loadAce(ace) {
                    this.checkboxes.setAce(ace);
                }
                setPermissionsType(ace, type) {
                    this.dataSource.data([]);
                    switch (type) {
                        case Security.PermissionsViewType.basic:
                            this.dataSource.data(this.acl.permissions.getBasicPermissions());
                            break;
                        case Security.PermissionsViewType.extended:
                            this.dataSource.data(this.acl.permissions.getExpandedPermissions());
                            break;
                    }
                    this.checkboxes_init();
                    this.loadAce(ace);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.checkboxes_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.node,
                        selectionMode: "none",
                        dataSource: {
                            data: [],
                            storeAsLocalVariable: true
                        },
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No permissions defined."
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Name",
                                field: "name"
                            }),
                            new PD.Web.UI.Controls.GridCheckboxColumn({
                                title: "Allow",
                                width: "50px",
                                attributes: {
                                    class: "permission-check allow"
                                }
                            }),
                            new PD.Web.UI.Controls.GridCheckboxColumn({
                                title: "Deny",
                                width: "50px",
                                attributes: {
                                    class: "permission-check deny"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "value",
                                hidden: true,
                                template: function (e) {
                                    return "<input data-id='permission-id' value='" + (e.value == null ? -1 : e.value) + "' />";
                                }
                            })
                        ]
                    });
                    this.dataSource.data(this.acl.permissions.getBasicPermissions());
                }
                checkboxes_init() {
                    this.m_checkboxes = new Security.CheckboxPairCollection({
                        container: this.node,
                        acl: this.acl
                    });
                }
            }
            Security.AceGrid = AceGrid;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            let CheckboxType;
            (function (CheckboxType) {
                CheckboxType["allow"] = "allow";
                CheckboxType["deny"] = "deny";
            })(CheckboxType = Security.CheckboxType || (Security.CheckboxType = {}));
            class Checkbox extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.onActivate();
                }
                get container() {
                    return this.state.get("container");
                }
                get node() {
                    return this.container.find(`.permission-check.${this.type} input`);
                }
                get type() {
                    return this.state.get("type");
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get checked() {
                    return this.node.is(":checked");
                }
                set checked(value) {
                    this.node.prop("checked", value);
                }
                get enabled() {
                    return !this.node.a(":disabled");
                }
                set enabled(value) {
                    this.node.prop("disabled", !value);
                }
                setTriState(isSet) {
                    this.node.css({
                        opacity: isSet ? ".3" : "1"
                    });
                }
                onActivate() {
                    this.node.on(Jade.BrowserEvent.CHANGE, () => {
                        this.changeCallback(this);
                    });
                }
            }
            Security.Checkbox = Checkbox;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class CheckboxPair extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.allowed_init();
                    this.denied_init();
                }
                get container() {
                    return this.state.get("container");
                }
                get permission() {
                    return this.state.get("permission");
                }
                get acl() {
                    return this.state.get("acl");
                }
                get allowed() {
                    return this.m_allowed;
                }
                set allowed(value) {
                    this.m_allowed = value;
                }
                get denied() {
                    return this.m_denied;
                }
                set denied(value) {
                    this.m_denied = value;
                }
                get node() {
                    return this.container.find(`input[data-id=permission-id][value=${this.permission.value}]`).closest("tr");
                }
                get ace() {
                    return this.m_ace;
                }
                set ace(value) {
                    this.m_ace = value;
                }
                setAce(ace) {
                    this.m_ace = ace;
                    ace == null ?
                        this.loadWhenAceNull() :
                        this.loadWhenAceNotNull();
                }
                setEnabled(enabled) {
                    this.allowed.enabled = enabled;
                    this.denied.enabled = enabled;
                }
                allowed_init() {
                    this.allowed = new Security.Checkbox({
                        type: Security.CheckboxType.allow,
                        container: this.node,
                        change: (e) => {
                            this.updateAce(true);
                            this.updateCheckbox(true);
                        }
                    });
                }
                denied_init() {
                    this.denied = new Security.Checkbox({
                        type: Security.CheckboxType.deny,
                        container: this.node,
                        change: (e) => {
                            this.updateAce(false);
                            this.updateCheckbox(false);
                        }
                    });
                }
                updateAce(triggeredByAllow) {
                    if (!this.ace) {
                        return;
                    }
                    let triggeredByDeny = !triggeredByAllow;
                    switch (true) {
                        case this.denied.checked && triggeredByDeny:
                            this.ace.addDeny(this.permission.value);
                            this.ace.clearAllow(this.permission.value);
                            break;
                        case !this.denied.checked && triggeredByDeny:
                            this.ace.clearDeny(this.permission.value);
                            break;
                    }
                    switch (true) {
                        case this.allowed.checked && triggeredByAllow:
                            this.ace.addAllow(this.permission.value);
                            this.ace.clearDeny(this.permission.value);
                            break;
                        case !this.allowed.checked && triggeredByAllow:
                            this.ace.clearAllow(this.permission.value);
                            break;
                    }
                    this.acl.commit();
                }
                updateCheckbox(triggeredByAllow) {
                    if (!this.ace) {
                        return;
                    }
                    let triggeredByDeny = !triggeredByAllow;
                    let isDeniedPartial = this.ace.isDeniedPartial(this.permission.value);
                    let isAllowedPartial = this.ace.isAllowedPartial(this.permission.value);
                    switch (true) {
                        case triggeredByAllow && !isDeniedPartial:
                            this.denied.checked = false;
                            break;
                        case triggeredByDeny && !isAllowedPartial:
                            this.allowed.checked = false;
                            break;
                    }
                    this.allowed.setTriState(isAllowedPartial);
                    this.denied.setTriState(isDeniedPartial);
                }
                loadWhenAceNull() {
                    this.allowed.checked = false;
                    this.denied.checked = false;
                    this.setEnabled(false);
                }
                loadWhenAceNotNull() {
                    let permission = this.permission.value;
                    let isAllowedPartial = this.ace.isAllowedPartial(permission);
                    let isDeniedPartial = this.ace.isDeniedPartial(permission);
                    this.allowed.checked =
                        this.ace.isAllowed(permission) ||
                            isAllowedPartial;
                    this.denied.checked =
                        this.ace.isDenied(permission) ||
                            isDeniedPartial;
                    this.setEnabled(true);
                    this.allowed.setTriState(isAllowedPartial);
                    this.denied.setTriState(isDeniedPartial);
                }
            }
            Security.CheckboxPair = CheckboxPair;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class CheckboxPairCollection extends Jade.Collection {
                constructor(options) {
                    super([]);
                    this.m_container = options.container;
                    this.m_acl = options.acl;
                    this.populate();
                }
                get container() {
                    return this.m_container;
                }
                get permissions() {
                    return this.acl.permissions;
                }
                get acl() {
                    return this.m_acl;
                }
                setAce(ace) {
                    this.each(pair => {
                        pair.setAce(ace);
                    });
                }
                populate() {
                    this.permissions.each(permission => {
                        this.add(new Security.CheckboxPair({
                            container: this.container,
                            acl: this.acl,
                            permission: permission
                        }));
                    });
                }
            }
            Security.CheckboxPairCollection = CheckboxPairCollection;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AccessControlAcl extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get grid() {
                    return this.m_grid;
                }
                get acl() {
                    return this.state.get("acl");
                }
                get changeCallback() {
                    return this.state.get("change");
                }
                template() {
                    return `<div class="-pdjs-shared-security-access-control-acl">
                        <div role="head">Users and Groups</div>
                        <div role="grid"></div>
                    </div>`;
                }
                resize() {
                    this.grid.resize();
                }
                refresh(clear = false, selections) {
                    this.grid.refresh(clear, selections);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new Security.AclGrid({
                        insertAt: "div[role=grid]",
                        acl: this.acl,
                        change: (e) => {
                            this.changeCallback(e);
                        }
                    });
                    this.controls.add(this.m_grid);
                }
            }
            Security.AccessControlAcl = AccessControlAcl;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AclGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get dataSource() {
                    return this.m_grid.get_dataSource();
                }
                get grid() {
                    return this.m_grid;
                }
                get kendo() {
                    return this.m_grid.get_kendo();
                }
                get acl() {
                    return this.state.get("acl");
                }
                get changeCallback() {
                    return this.state.get("change");
                }
                get selection() {
                    return this.getSelectedAce();
                }
                template() {
                    return `<div class='-pdjs-shared-security-access-control-acl-grid'></div>`;
                }
                resize() {
                    this.grid.refresh();
                    this.grid.redraw();
                }
                refresh(clear = false, selections) {
                    this.dataSource.data([]);
                    this.dataSource.data(this.acl.aces.toJSON());
                    this.grid.refresh({ clear: clear, selections: selections });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.node,
                        pk: "id",
                        selectionMode: "single",
                        dataSource: {
                            data: [],
                            sort: [
                                { field: "name", dir: "asc" }
                            ],
                            storeAsLocalVariable: true
                        },
                        schema: {
                            model: {
                                id: "id"
                            }
                        },
                        change: (e) => {
                            this.changeCallback(this.selection);
                        },
                        footer: {
                            visible: false
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                title: "",
                                width: 25,
                                attributes: {
                                    style: "text-align:center;padding:0px;padding-top:3px;"
                                },
                                transform: function (e) {
                                    return (e.type === 0 ? "USER.PNG" : "USERS.PNG");
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Name",
                                field: "name"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Type",
                                field: "inherited",
                                width: 100,
                                template: function (e) {
                                    var result = "";
                                    var isInherited = e.inherited != null;
                                    var isOverridden = null;
                                    if (isInherited) {
                                        isOverridden = (e.inherited.allow != e.allow || e.inherited.deny != e.deny);
                                        result = isOverridden ? "<span style=\"text-decoration:line-through;\">Inherited</span>" : "Inherited";
                                    }
                                    return result;
                                }
                            })
                        ]
                    });
                    this.dataSource.data(this.acl.aces.toJSON());
                }
                getSelectedAce() {
                    if (this.grid == null) {
                        return;
                    }
                    let result = null;
                    let record = this.grid.getSelections().first();
                    if (record != null) {
                        result = this.acl.aces.getById(record.id);
                    }
                    return result;
                }
            }
            Security.AclGrid = AclGrid;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AdvancedDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get buttonCancel() {
                    return this.node.find("button[data-command=cancel]");
                }
                get buttonOk() {
                    return this.node.find("button[data-command=ok]");
                }
                get delete() {
                    return this.deleteNode.is(":checked");
                }
                get deleteNode() {
                    return this.node.find("[data-role=delete]");
                }
                get replace() {
                    return this.replaceNode.is(":checked");
                }
                get replaceNode() {
                    return this.node.find("[data-role=replace]");
                }
                template() {
                    return super.template(`<div class="-pdjs-shared-security-advanced-dialog">

                        <div role="message">
                            Cascade the last saved ACL configuration of this item and apply it to all of its descendant's ACLs.
                        </div>

                        <div role="body">

                            <label>
                                <div><input type="checkbox" data-role="replace" /></div>
                                <div>
                                    Replace matching access rules (ACEs) with the access rules defined within this ACL.
                                </div>
                            </label>

                            <label>
                                <div><input type="checkbox" data-role="delete" /></div>
                                <div>
                                    Delete access rules (ACEs) not defined here from all descendant ACLs.
                                </div>
                            </label>

                        </div>

                        <div role="deck">

                            <button
                                data-command="ok"
                                class="-jadeui-dialog-button">
                                OK
                            </button>

                            <button
                                data-command="cancel"
                                class="-jadeui-dialog-button">
                                Cancel
                            </button>

                        </div>

                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.buttonCancel.on(Jade.BrowserEvent.CLICK, () => {
                        this.close();
                    });
                    this.buttonOk.on(Jade.BrowserEvent.CLICK, () => {
                        this.close({
                            name: "ok",
                            data: {
                                replace: this.replace,
                                delete: this.delete
                            }
                        });
                    });
                }
                getDefaultOptions() {
                    return {
                        title: "Advanced | Cascade Permissions",
                        width: "400px",
                        minWidth: "400px",
                        resizable: false
                    };
                }
                static open(options) {
                    return new AdvancedDialog(options);
                }
            }
            Security.AdvancedDialog = AdvancedDialog;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class EffectivePermissionsComboBox extends PDJS.Shared.UI.Controls.ComboBoxOf {
                constructor(options) {
                    super(options);
                }
                get identity() {
                    return this.state.get("identity");
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.textValue = this.identity.displayName || this.identity.name;
                    this.maskValue = this.identity.displayName || this.identity.name;
                }
                onSelectionChange(selection) {
                    super.onSelectionChange(selection);
                    if (selection != null) {
                        this.maskValue = selection.identityName;
                        this.textValue = selection.identityId;
                        this.changeCallback({
                            displayName: selection.identityName,
                            id: selection.identityId,
                            name: selection.identityName
                        });
                    }
                }
                createListItem(e) {
                    return new PDJS.Shared.UI.Controls.ComboBoxListItem({
                        data: e,
                        uidMap: "identityId",
                        labelMap: "identityName"
                    });
                }
                onFilter(e) {
                    let service = new PDJS.Services.Security.IdentityService();
                    service.query({
                        term: this.textValue,
                        success: (e2) => {
                            e.result.addRange(e2.data.identities);
                            e.complete();
                            this.list.resize(e2.data.identities.length * 24);
                        }
                    });
                }
                onShowDialog(e) {
                    PDJS.Shared.Security.IdentityBrowserDialog.open({
                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                        title: "Select | User or Group",
                        filters: [
                            PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
                        ],
                        select: {
                            ok: (sender, e) => {
                                let selection = _.first(e);
                                if (selection) {
                                    this.textValue = selection.id.toString();
                                    this.maskValue = selection.name;
                                }
                                else {
                                    this.textValue = "";
                                    this.maskValue = "";
                                }
                                this.changeCallback(_.first(e));
                            }
                        }
                    });
                }
            }
            Security.EffectivePermissionsComboBox = EffectivePermissionsComboBox;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class EffectivePermissionsDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get aces() {
                    return this.state.get("aces");
                }
                get closeButton() {
                    return this.node.find("BUTTON[data-id=button-close]");
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get identity() {
                    return this.state.get("identity");
                }
                set identity(value) {
                    this.state.set("identity", value);
                }
                template() {
                    return super.template(`
                <div class="-pdjs-effective-permissions">
                    <div data-role="identity-selector-label">Show Effective Permissions For:</div>
                    <div data-role="identity-selector-container"></div>
                    <div data-role="permissions-grid-container"></div>
                    <div data-role="sources-grid-container"></div>
                    <div data-role="button-deck" class="-pdjs-dialog-button-deck top-padding-10px">
                        <button
                            data-id="button-close"
                            class="-pdjs-dialog-button">
                            Close
                        </button>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.effectivePermissionsComboBox_init();
                    this.effectivePermissionsGrid_init();
                    this.effectivePermissionsSourcesGrid_init();
                    this.closeButton.on(Jade.BrowserEvent.CLICK, _.bind(this.closeButton_onClick, this));
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.effectivePermissionsComboBox_onChange();
                }
                getDefaultOptions() {
                    return {
                        title: "Effective Permissions",
                        permissions: [],
                        entityId: null,
                        identity: null,
                        actions: [],
                        height: "575px",
                        minHeight: "300px",
                        width: "500px",
                        minWidth: "300px",
                        resizable: true
                    };
                }
                effectivePermissionsComboBox_onChange() {
                    PDJS.Ajax.call({
                        type: "POST",
                        contentType: "application/json",
                        url: Jade.Path.resolve("~/Shared/Security/GetEffectivePermissions"),
                        data: JSON.stringify({
                            entityId: this.entityId,
                            identityId: this.identity.id,
                            aces: JSON.stringify(this.aces)
                        }),
                        success: (e) => {
                            this._effectivePermissionsGrid.load(e);
                        }
                    });
                }
                effectivePermissionsComboBox_init() {
                    this._effectivePermissionsComboBox =
                        new Security.EffectivePermissionsComboBox({
                            insertAt: "[data-role=identity-selector-container]",
                            mode: Shared.UI.Controls.ComboBoxMode.PopUp,
                            identity: this.identity,
                            change: (e) => {
                                this.identity = e;
                                this.effectivePermissionsComboBox_onChange();
                            }
                        });
                    this.controls.add(this._effectivePermissionsComboBox);
                }
                effectivePermissionsGrid_init() {
                    this._effectivePermissionsGrid =
                        new Security.EffectivePermissionsGrid({
                            insertAt: "[data-role=permissions-grid-container]",
                            change: (e) => {
                                if (e.selection != null) {
                                    this._effectivePermissionsSourcesGrid.load(e.selection.sources.toJSON());
                                }
                            }
                        });
                    this.controls.add(this._effectivePermissionsGrid);
                }
                effectivePermissionsSourcesGrid_init() {
                    this._effectivePermissionsSourcesGrid =
                        new Security.EffectivePermissionsSourcesGrid({
                            insertAt: "[data-role=sources-grid-container]"
                        });
                    this.controls.add(this._effectivePermissionsSourcesGrid);
                }
                closeButton_onClick() {
                    this.close({
                        name: "close",
                        data: {
                            identity: this.identity
                        }
                    });
                }
                static open(options) {
                    return new EffectivePermissionsDialog(options);
                }
            }
            Security.EffectivePermissionsDialog = EffectivePermissionsDialog;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class EffectivePermissionsGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                load(permissions) {
                    this._grid.getSelections().clear();
                    this._grid.get_dataSource().data(permissions);
                }
                template() {
                    return `
            <div class="-pdjs-effective-permissions-grid">
                <div data-role="label">
                    Permissions
                </div>
                <div data-role="grid"></div>
            </div>
            `;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this._grid = new PD.Web.UI.Controls.Grid({
                        container: this.node.find("div[data-role=grid]"),
                        pk: "expandedName",
                        height: "100%",
                        selectionMode: "single",
                        defaultSelectionEnabled: true,
                        dataSource: {
                            data: []
                        },
                        messaging: {
                            noRecordsMessage: "No Permissions Defined"
                        },
                        footer: {
                            visible: false
                        },
                        change: _.bind(this.changeCallback, this),
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Permission",
                                field: "expandedName",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Basic Group",
                                field: "basicName"
                            }),
                            new PD.Web.UI.Controls.GridCheckboxColumn({
                                title: "Allow",
                                field: "allowed",
                                width: "40px",
                                masked: true,
                                attributes: {
                                    class: "permission-check allow"
                                }
                            }),
                            new PD.Web.UI.Controls.GridCheckboxColumn({
                                title: "Deny",
                                field: "denied",
                                width: "40px",
                                masked: true,
                                attributes: {
                                    class: "permission-check deny"
                                }
                            })
                        ]
                    });
                }
            }
            Security.EffectivePermissionsGrid = EffectivePermissionsGrid;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class EffectivePermissionsSourcesGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                load(sources) {
                    var data = [];
                    if (_.isArray(sources)) {
                        data = sources;
                    }
                    this._grid.get_dataSource().data(data);
                }
                template() {
                    return `
            <div class="-pdjs-effective-permissions-sources-grid">
                <div data-role="label">
                    Permissions Derived From
                </div>
                <div data-role="grid"></div>
            </div>
            `;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    this._grid = new PD.Web.UI.Controls.Grid({
                        container: this.node.find("div[data-role=grid]"),
                        selectionMode: "none",
                        height: "100%",
                        dataSource: {
                            data: []
                        },
                        messaging: {
                            noRecordsMessage: "No Sources Found"
                        },
                        footer: {
                            visible: false
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridIconColumn({
                                title: " ",
                                field: "isUser",
                                transform: function (e) {
                                    return e.isUser ? "USER.PNG" : "USERS.PNG";
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Source",
                                field: "identityName"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                title: "Inherited",
                                field: "inherited",
                                width: "100px",
                                template: function (e) {
                                    return (e.inherited ? "<b>Yes</b>" : "No");
                                }
                            })
                        ]
                    });
                }
            }
            Security.EffectivePermissionsSourcesGrid = EffectivePermissionsSourcesGrid;
        })(Security = Shared.Security || (Shared.Security = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            class AppliedThemeRecord extends Jade.Data.TableOf {
                constructor() {
                    super({
                        name: "settings"
                    });
                }
                get(args) {
                    super.getOf(this.getRecordId(args.themeScope), (e) => {
                        e == null ?
                            this.ensureRecord(args.themeScope, args.success, () => { args.success(null); }) :
                            args.success(e.theme);
                    }, args.error);
                }
                set(args) {
                    args.value.id = this.getRecordId(args.themeScope);
                    super.setOf(null, args.value, args.success, args.error);
                }
                delete(args) {
                    super.delete(this.getRecordId(args.themeScope), args.success, args.error);
                }
                getRecordId(themeScope) {
                    return `theme.applied-theme.${Themes.ThemeScopes[themeScope]}`.toLowerCase();
                }
                ensureRecord(scope, success, error) {
                    new PDJS.Services.Themes.ThemeService().getCurrentTheme({
                        themeScope: scope,
                        success: (e) => {
                            this.set({
                                themeScope: scope,
                                value: {
                                    id: this.getRecordId(scope),
                                    theme: e.data
                                },
                                success: () => {
                                    success(e.data);
                                }
                            });
                        },
                        error: (e) => {
                            error();
                        }
                    });
                }
            }
            Themes.AppliedThemeRecord = AppliedThemeRecord;
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            let Events;
            (function (Events) {
                Events["ThemeChanged"] = "PDJS.Shared.Themes.Events.ThemeChanged";
                Events["ThemeListChanged"] = "PDJS.Shared.Themes.Events.ThemeListChanged";
            })(Events = Themes.Events || (Themes.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static setThemePublish(args) {
                    this.global.publish(Events.ThemeChanged, args);
                }
                static themeListChangedPublish() {
                    this.global.publish(Events.ThemeListChanged);
                }
                static setThemeSubscribe(callback) {
                    return this.global.subscribe(Events.ThemeChanged, callback);
                }
                static themeListChangedSubscribe(callback) {
                    return this.global.subscribe(Events.ThemeListChanged, callback);
                }
            }
            Themes.EventsHub = EventsHub;
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            const VISIV_THEME_DARK = "-visiv-theme-dark";
            const VISIV_THEME_LIGHT = "-visiv-theme-light";
            class Theme {
                constructor(scope) {
                    this.m_service = new PDJS.Services.Themes.ThemeService();
                    this.m_scope = scope;
                    this.m_scopeName = Themes.ThemeScopes[this.scope].toLowerCase();
                    this.m_broadcaster = new Themes.ThemeBroadcaster();
                    this.m_broadcaster.subscribeSwitchTheme(_.bind(this.applyTheme, this));
                }
                static get colors() {
                    return this.m_colors;
                }
                static set colors(value) {
                    this.m_colors = value;
                }
                static get hub() {
                    this.ensureInstance(PDJS.Services.Themes.ThemeScope.Hub);
                    return this.m_hub;
                }
                static get manage() {
                    this.ensureInstance(PDJS.Services.Themes.ThemeScope.Manage);
                    return this.m_manage;
                }
                static get canvas() {
                    this.ensureInstance(PDJS.Services.Themes.ThemeScope.Canvas);
                    return this.m_canvas;
                }
                static get default() {
                    this.ensureInstance(PDJS.Services.Themes.ThemeScope.Canvas);
                    return this.m_canvas;
                }
                get scope() {
                    return this.m_scope;
                }
                get scopeName() {
                    return this.m_scopeName;
                }
                get cssNode() {
                    return $(`#${this.scopeName}-theme-css`);
                }
                get cssLinkNode() {
                    return $(`#${this.scopeName}-theme-css-link`);
                }
                switchTheme(themeId) {
                    if (Jade.String.isNullOrWhiteSpace(themeId)) {
                        themeId = null;
                    }
                    this.m_service.switchTheme({
                        themeScope: this.scope,
                        themeId: themeId,
                        success: (e) => {
                            let args2 = {
                                themeId: themeId,
                                themeCss: e.data.css,
                                themeScope: this.scope,
                                editorTheme: e.data.editorTheme,
                                isDark: e.data.isDark,
                                sourceScope: this.scope
                            };
                            this.applyTheme(args2);
                            this.m_broadcaster.publishSwitchTheme(args2);
                        }
                    });
                }
                static initialize() {
                    Theme.ensureInstance(PDJS.Services.Themes.ThemeScope.Canvas);
                    Theme.ensureInstance(PDJS.Services.Themes.ThemeScope.Hub);
                    Theme.ensureInstance(PDJS.Services.Themes.ThemeScope.Manage);
                    this.refreshColors();
                }
                static setThemeClass(isDark) {
                    let body = $(document.body);
                    body.removeClass(VISIV_THEME_DARK);
                    body.removeClass(VISIV_THEME_LIGHT);
                    isDark ?
                        body.addClass(VISIV_THEME_DARK) :
                        body.addClass(VISIV_THEME_LIGHT);
                }
                refreshTheme() {
                    if (PDJS.Application.instance.area == "hub") {
                        this.switchTheme(PDJS.Profiles.Profile.current.themes.hub);
                        return;
                    }
                    if (PDJS.Application.instance.area == "manage") {
                        this.switchTheme(PDJS.Profiles.Profile.current.themes.manage);
                        return;
                    }
                }
                static refreshColors() {
                    if (PDJS.Application.instance.name != "manage") {
                        return;
                    }
                    new PDJS.Services.Themes.ThemeService().getColors({
                        clearCache: true,
                        success: (e) => {
                            this.colors = [];
                            _.forOwn(e.data, (color) => {
                                this.colors.push(color);
                            });
                        }
                    });
                }
                static ensureInstance(scope) {
                    switch (scope) {
                        case PDJS.Services.Themes.ThemeScope.Hub:
                            this.m_hub != null ? null :
                                this.m_hub = new Theme(scope);
                            break;
                        case PDJS.Services.Themes.ThemeScope.Manage:
                            this.m_manage != null ? null :
                                this.m_manage = new Theme(scope);
                            break;
                        case PDJS.Services.Themes.ThemeScope.Canvas:
                            this.m_canvas != null ? null :
                                this.m_canvas = new Theme(scope);
                            break;
                    }
                }
                applyTheme(args) {
                    if (args.themeScope === PDJS.Services.Themes.ThemeScope.Hub) {
                        if (this.scope === PDJS.Services.Themes.ThemeScope.Manage) {
                            if (PDJS.Profiles.Profile.current.themes.isManageUsingHub) {
                                this.applyTheme({
                                    themeCss: args.themeCss,
                                    themeId: args.themeId,
                                    themeScope: PDJS.Services.Themes.ThemeScope.Manage,
                                    editorTheme: args.editorTheme,
                                    isDark: args.isDark,
                                    sourceScope: args.sourceScope
                                });
                            }
                        }
                    }
                    if (args.themeScope !== this.scope) {
                        return;
                    }
                    if (this.cssNode.length > 0) {
                        this.cssNode.empty();
                        this.cssNode.text(args.themeCss || "");
                    }
                    if (this.cssLinkNode.length > 0) {
                        this.cssLinkNode.remove();
                    }
                    Theme.setThemeClass(args.isDark);
                    Themes.EventsHub.setThemePublish({
                        themeId: args.themeId,
                        themeScope: this.scope,
                        themeEditor: args.editorTheme,
                        isDark: args.isDark,
                        sourceScope: args.sourceScope
                    });
                }
            }
            Themes.Theme = Theme;
            PDJS.Application.onStart(() => {
                Theme.initialize();
            });
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            Themes.ThemeScopes = ["hub", "manage", "canvas"];
            class ThemeBroadcaster extends Shared.Messaging.Broadcaster {
                constructor() {
                    super({ name: "theme-broadcaster" });
                }
                publishSwitchTheme(args) {
                    this.sendMessage(args, "switchTheme");
                }
                subscribeSwitchTheme(handler) {
                    this.subscribe(handler, "switchTheme");
                }
            }
            Themes.ThemeBroadcaster = ThemeBroadcaster;
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            class ThemeColorsRecord extends Jade.Data.TableOf {
                constructor() {
                    super({
                        name: "settings"
                    });
                }
                get recordId() {
                    return "theme.colors";
                }
                get(args) {
                    super.getOf(this.recordId, (e) => {
                        e == null ?
                            this.requestRecord(args.success, () => { args.success(null); }) :
                            args.success(e.colors);
                    }, args.error);
                }
                set(args) {
                    args.value.id = this.recordId;
                    super.setOf(null, args.value, args.success, args.error);
                }
                delete(args) {
                    super.delete(this.recordId, args.success, args.error);
                }
                requestRecord(success, error) {
                    new PDJS.Services.Themes.ThemeService().getColors({
                        success: (e) => {
                            let result = [];
                            _.forOwn(e.data, (color) => {
                                result.push(color);
                            });
                            this.set({
                                value: {
                                    id: this.recordId,
                                    colors: result
                                },
                                success: () => {
                                    success(result);
                                }
                            });
                        },
                        error: (e) => {
                            error();
                        }
                    });
                }
            }
            Themes.ThemeColorsRecord = ThemeColorsRecord;
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Themes;
        (function (Themes) {
            class ThemeUrl {
                static get canvas() {
                    return this.createUrl("~/shared/theme/canvas");
                }
                static get hub() {
                    return this.createUrl("~/shared/theme/hub");
                }
                static get manage() {
                    return this.createUrl("~/shared/theme/manage");
                }
                static createUrl(url) {
                    return Jade.Path.resolve(url, { v: Jade.Guid.new().toString() });
                }
            }
            Themes.ThemeUrl = ThemeUrl;
        })(Themes = Shared.Themes || (Shared.Themes = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            class ControlCommander {
                constructor(options) {
                    this.m_state = new Jade.StateBag(options);
                    this.clear();
                    this.subscribeToCommand();
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get checked() {
                    return this.state.get("checked", false);
                }
                set checked(value) {
                    this.state.set("checked", value);
                }
                get checkedChanged() {
                    return this.state.hasChanged("checked");
                }
                get commandId() {
                    return this.state.get("commandId");
                }
                set commandId(value) {
                    this.state.set("commandId", value);
                }
                get commandUid() {
                    return this.state.get("commandUid");
                }
                set commandUid(value) {
                    this.state.set("commandUid", value);
                }
                get commandUidChanged() {
                    return this.state.hasChanged("commandUid");
                }
                get display() {
                    return this.state.get("display", "label icon");
                }
                set display(value) {
                    this.state.set("display", value);
                }
                get displayChanged() {
                    return this.state.hasChanged("display");
                }
                get enabled() {
                    return this.state.get("enabled", true);
                }
                set enabled(value) {
                    this.state.set("enabled", value);
                }
                get enabledChanged() {
                    return this.state.hasChanged("enabled");
                }
                get icon() {
                    return this.state.get("icon", null);
                }
                set icon(value) {
                    this.state.set("icon", value);
                }
                get iconChanged() {
                    return this.state.hasChanged("icon");
                }
                get isIconVisible() {
                    return this.showIcon();
                }
                get isLabelVisible() {
                    return this.showLabel();
                }
                get label() {
                    return this.state.get("label", "");
                }
                set label(value) {
                    this.state.set("label", value);
                }
                get labelChanged() {
                    return this.state.hasChanged("label");
                }
                get state() {
                    return this.m_state;
                }
                get subscriber() {
                    return this.m_subscriber;
                }
                set subscriber(value) {
                    this.m_subscriber = value;
                }
                get tooltip() {
                    return this.state.get("tooltip", "");
                }
                set tooltip(value) {
                    this.state.set("tooltip", value);
                }
                get tooltipChanged() {
                    return this.state.hasChanged("tooltip");
                }
                get visible() {
                    return this.state.get("visible", true);
                }
                set visible(value) {
                    this.state.set("visible", value);
                }
                get visibleChanged() {
                    return this.state.hasChanged("visible");
                }
                get value() {
                    return this.state.get("value");
                }
                set value(value) {
                    this.state.set("value", value);
                }
                get valueChanged() {
                    return this.state.hasChanged("value");
                }
                execute(args) {
                    if (this.subscriber.command) {
                        this.subscriber.command.execute(args);
                    }
                }
                getResolvedIcon() {
                    var _a, _b;
                    return this.subscriber != null ?
                        (_b = (_a = this.subscriber) === null || _a === void 0 ? void 0 : _a.command) === null || _b === void 0 ? void 0 : _b.getIcon(Jade.IconSetSizeSpecificDirectory.x16, this.icon) :
                        this.icon;
                }
                getCommandState(id) {
                    var _a, _b, _c;
                    return (_c = (_b = (_a = this.subscriber) === null || _a === void 0 ? void 0 : _a.command) === null || _b === void 0 ? void 0 : _b.state) === null || _c === void 0 ? void 0 : _c.get(id);
                }
                subscribeToCommand() {
                    this.subscriber = new Jade.CommandSubscriber();
                    this.checked = false;
                    this.display = "icon label";
                    this.enabled = true;
                    this.icon = null;
                    this.label = "";
                    this.tooltip = null;
                    this.value = null;
                    this.visible = true;
                    this.subscriber.subscribe(this.commandId, () => {
                        let command = this.subscriber.command;
                        if (command) {
                            this.assignCommandValues(command);
                        }
                        this.changeCallback();
                    });
                    if (this.subscriber.command != null) {
                        this.commandUid = this.subscriber.command.UID;
                        this.assignCommandValues(this.subscriber.command);
                    }
                    else if (this.subscriber.command == null) {
                        throw `Cannot resolve command with ID of "${this.commandId}".`;
                    }
                }
                showIcon() {
                    return !Jade.String.isNullOrWhiteSpace(this.icon)
                        && (Jade.String.isNullOrWhiteSpace(this.display)
                            || this.display.indexOf("icon") != -1);
                }
                showLabel() {
                    return !Jade.String.isNullOrWhiteSpace(this.label)
                        && (Jade.String.isNullOrWhiteSpace(this.display)
                            || this.display.indexOf("label") != -1);
                }
                clear() {
                    this.state.set({
                        checked: null,
                        display: null,
                        enabled: null,
                        icon: null,
                        label: null,
                        tooltip: null,
                        value: null,
                        visible: null
                    });
                }
                assignCommandValues(command) {
                    this.state.set({
                        checked: command.checked,
                        display: command.display,
                        enabled: command.enabled,
                        icon: command.icon,
                        label: command.label,
                        tooltip: command.tooltip,
                        value: command.value,
                        visible: command.visible
                    });
                }
            }
            UI.ControlCommander = ControlCommander;
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            let CssClass;
            (function (CssClass) {
                CssClass["Disabled"] = "-pdjs-disabled";
            })(CssClass = UI.CssClass || (UI.CssClass = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            class InputValueHandler {
                constructor(options) {
                    this.m_input = options.input;
                    this.m_changing = options.changing || (() => { });
                    this.addEventHandlers();
                }
                get input() {
                    return this.m_input;
                }
                get inputNode() {
                    return $(this.input);
                }
                get value() {
                    return this.input.value;
                }
                get indexStart() {
                    return this.input.selectionStart;
                }
                get indexEnd() {
                    return this.input.selectionEnd;
                }
                get isRange() {
                    return this.indexStart !== this.indexEnd;
                }
                destroy() {
                    this.removeEventHandlers();
                }
                onCut(e) {
                    this.m_changing({
                        currentValue: this.value,
                        futureValue: this.getFutureValueCut(),
                        isActionable: true,
                        cancel: () => {
                            e.preventDefault();
                            e.cancelBubble = true;
                        }
                    });
                }
                onPaste(e) {
                    let value = this.getClipboardData(e.originalEvent);
                    this.m_changing({
                        currentValue: this.value,
                        futureValue: this.getFutureValuePaste(value),
                        isActionable: true,
                        cancel: () => {
                            e.preventDefault();
                            e.cancelBubble = true;
                        }
                    });
                }
                onKeyDown(e) {
                    let isCutCopyPaste = this.isCutCopyPaste(e.ctrlKey, e.key);
                    let isActionableKey = this.isActionableKey(e.keyCode);
                    if (isCutCopyPaste || !isActionableKey) {
                        return;
                    }
                    this.m_changing({
                        currentValue: this.value,
                        futureValue: this.getFutureValueKeyDown(e.key, e.keyCode),
                        key: e.key,
                        keyCode: e.keyCode,
                        isActionable: (this.isDeleteCharacter(e.keyCode) || this.isPrintableCharacter(e.key)),
                        cancel: () => {
                            e.preventDefault();
                            e.cancelBubble = true;
                        }
                    });
                }
                getFutureValueCut() {
                    return [this.getValueStart(), this.getValueEnd()].join('');
                }
                getFutureValuePaste(value) {
                    return [this.getValueStart(), value, this.getValueEnd()].join('');
                }
                getFutureValueKeyDown(key, keyCode) {
                    return this.isDeleteCharacter(keyCode) ?
                        [this.getValueStart(this.indexStart === 0 ? 0 : -1), this.getValueEnd()].join('') :
                        [this.getValueStart(), key, this.getValueEnd()].join('');
                }
                addEventHandlers() {
                    this.m_cutHandler = (e) => { this.onCut(e); };
                    this.m_keydownHandler = (e) => { this.onKeyDown(e); };
                    this.m_pasteHandler = (e) => { this.onPaste(e); };
                    this.inputNode.on("cut", this.m_cutHandler);
                    this.inputNode.on("keydown", this.m_keydownHandler);
                    this.inputNode.on("paste", this.m_pasteHandler);
                }
                removeEventHandlers() {
                    this.inputNode.off("CUT", this.m_cutHandler);
                    this.inputNode.off("KEYDOWN", this.m_keydownHandler);
                    this.inputNode.off("PASTE", this.m_pasteHandler);
                }
                isPrintableCharacter(key) {
                    return key.length === 1;
                }
                isDeleteCharacter(keyCode) {
                    return keyCode === Jade.KeyCode.Delete
                        || keyCode === Jade.KeyCode.Backspace;
                }
                getValueStart(addIndex = 0) {
                    return this.value.slice(0, this.indexStart + addIndex);
                }
                getValueEnd() {
                    return this.value.slice(this.indexStart + (this.isRange ? this.indexEnd : 0));
                }
                isCutCopyPaste(ctrlKey, key) {
                    return ctrlKey && (key === "x" || key === "c" || key === "v");
                }
                isActionableKey(keyCode) {
                    return keyCode !== Jade.KeyCode.Alt &&
                        keyCode !== Jade.KeyCode.Ctrl &&
                        keyCode !== Jade.KeyCode.Shift;
                }
                getClipboardData(e) {
                    return (e.clipboardData || window.clipboardData).getData("text");
                }
            }
            UI.InputValueHandler = InputValueHandler;
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            let KeyCodes;
            (function (KeyCodes) {
                KeyCodes[KeyCodes["Backspace"] = 8] = "Backspace";
                KeyCodes[KeyCodes["Tab"] = 9] = "Tab";
                KeyCodes[KeyCodes["Return"] = 13] = "Return";
                KeyCodes[KeyCodes["Space"] = 32] = "Space";
                KeyCodes[KeyCodes["End"] = 35] = "End";
                KeyCodes[KeyCodes["Home"] = 36] = "Home";
                KeyCodes[KeyCodes["ArrowLeft"] = 37] = "ArrowLeft";
                KeyCodes[KeyCodes["ArrowUp"] = 38] = "ArrowUp";
                KeyCodes[KeyCodes["ArrowRight"] = 39] = "ArrowRight";
                KeyCodes[KeyCodes["ArrowDown"] = 40] = "ArrowDown";
                KeyCodes[KeyCodes["Delete"] = 46] = "Delete";
            })(KeyCodes = UI.KeyCodes || (UI.KeyCodes = {}));
            class KeyCode {
                static get actionKeys() {
                    return [
                        KeyCodes.ArrowDown,
                        KeyCodes.ArrowLeft,
                        KeyCodes.ArrowRight,
                        KeyCodes.ArrowUp,
                        KeyCodes.Backspace,
                        KeyCodes.Delete,
                        KeyCodes.End,
                        KeyCodes.Home,
                        KeyCodes.Return,
                        KeyCodes.Space,
                        KeyCodes.Tab,
                    ];
                }
                static get navigationKeys() {
                    return [
                        KeyCodes.ArrowDown,
                        KeyCodes.ArrowLeft,
                        KeyCodes.ArrowRight,
                        KeyCodes.ArrowUp,
                        KeyCodes.End,
                        KeyCodes.Home
                    ];
                }
                static isActionKey(keyCode, ...exclude) {
                    let keys = this.actionKeys.slice(0);
                    if (_.isArray(exclude)) {
                        keys = _.difference(keys, exclude);
                    }
                    return keys.indexOf(keyCode) > 0;
                }
                static isNavigationKey(keyCode, ...exclude) {
                    let keys = this.navigationKeys.slice(0);
                    if (_.isArray(exclude)) {
                        keys = _.difference(keys, exclude);
                    }
                    return keys.indexOf(keyCode) > 0;
                }
            }
            UI.KeyCode = KeyCode;
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            class StateBindingBase {
                constructor(options) {
                    this.m_state = options.state;
                    this.m_map = options.map;
                    this.defaults = options.defaults;
                }
                get defaults() {
                    return this.m_defaults || this.getDefaults();
                }
                set defaults(value) {
                    this.m_defaults = value;
                }
                get map() {
                    return _.extend(this.defaults, this.m_map);
                }
                set map(value) {
                    this.m_map = value;
                }
                get state() {
                    return this.m_state;
                }
                set state(value) {
                    this.m_state = value;
                }
                resolve(name) {
                    return this.map[name];
                }
                getValue(name, defaultValue = null) {
                    let id = this.resolve(name);
                    return !Jade.String.isNullOrWhiteSpace(id) ?
                        this.state.get(id, defaultValue) : null;
                }
                setValue(name, value) {
                    let id = this.resolve(name);
                    return !Jade.String.isNullOrWhiteSpace(id) ?
                        this.state.set(id, value) : null;
                }
                getDefaults() {
                    return {};
                }
            }
            UI.StateBindingBase = StateBindingBase;
            class StateBinding extends StateBindingBase {
                get defaults() {
                    return super.defaults || {};
                }
                set defaults(value) {
                    super.defaults = value;
                }
                get map() {
                    return _.extend(this.defaults, super.map);
                }
                set map(value) {
                    super.map = value;
                }
                getDefaults() {
                    return {};
                }
            }
            UI.StateBinding = StateBinding;
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            class StyleInjector {
                constructor(options) {
                    this.m_id = options.id;
                    this.m_idEscaped = this.id.replace(/\-+/g, "_");
                    this.m_styles = {};
                }
                get id() {
                    return this.m_id;
                }
                get idEscaped() {
                    return this.m_idEscaped;
                }
                get idStyleTag() {
                    return `${this.idEscaped}-style`;
                }
                get rootClass() {
                    return `_${this.idEscaped}`;
                }
                get styles() {
                    return this.m_styles;
                }
                set styles(value) {
                    this.m_styles = value;
                }
                addStyle(selector, style, options) {
                    options = options || { useRootClass: true };
                    if (options.useRootClass) {
                        this.m_styles[`.${this.rootClass} ${selector}`] = style;
                    }
                    else {
                        this.m_styles[selector] = style;
                    }
                    return this;
                }
                inject(control) {
                    this.remove();
                    let styles = [];
                    let keys = Object.keys(this.m_styles);
                    keys.forEach(name => {
                        if (this.styles[name] != null) {
                            let style = this.getStyle(name, this.styles[name]);
                            if (style != null) {
                                styles[styles.length] = style;
                            }
                        }
                    });
                    if (styles.length === 0) {
                        return;
                    }
                    let content = `<style id="${this.idStyleTag}">${styles.join(" ")}</style>`;
                    if (control) {
                        control.node.addClass(this.rootClass);
                        control.node.append(content);
                    }
                    else {
                        $(document.head).append(content);
                    }
                }
                remove() {
                    $(`#${this.idStyleTag}`).remove();
                }
                clear() {
                    this.styles = {};
                }
                getStyle(name, style) {
                    let result = [];
                    let hasStyles = false;
                    Object.keys(style).forEach(name => {
                        if (style[name] != null) {
                            hasStyles = true;
                            result[result.length] = `${this.getFormattedAttributeName(name)}:${style[name]}`;
                        }
                    });
                    return hasStyles ? `${name} {${result.join(";")}}` : null;
                }
                getFormattedAttributeName(name) {
                    return name.replace(/([a-z]*)([A-Z])([a-z]*)/g, (match, $1, $2, $3) => {
                        return `${$1}${"-" + $2.toLowerCase()}${$3}`;
                    });
                }
            }
            UI.StyleInjector = StyleInjector;
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let CssClass;
                (function (CssClass) {
                    CssClass["ACTIVE"] = "-pdjs-active";
                    CssClass["MaskedTextBox"] = "-pd-masked-textbox";
                    CssClass["ComboBox"] = "-pdjs-combo-box";
                })(CssClass = Controls.CssClass || (Controls.CssClass = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let DataAttributes;
                (function (DataAttributes) {
                    DataAttributes["triggerDefaultButtonOnCarriageReturn"] = "triggerDefaultButtonOnCarriageReturn";
                })(DataAttributes = Controls.DataAttributes || (Controls.DataAttributes = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldChangeEvent {
                }
                Controls.BatchFieldChangeEvent = BatchFieldChangeEvent;
                class BatchField extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get list() {
                        return this.m_list;
                    }
                    get button() {
                        return this.m_button;
                    }
                    get filter() {
                        return this.m_filter;
                    }
                    get dialogViewStateId() {
                        return this.state.get("dialogViewStateId");
                    }
                    get dialogMapId() {
                        return this.state.get("dialogMapId");
                    }
                    get dialogMapLabel() {
                        return this.state.get("dialogMapLabel");
                    }
                    get dialogMapIcon() {
                        return this.state.get("dialogMapIcon");
                    }
                    get dialogTitle() {
                        return this.state.get("dialogTitle");
                    }
                    get dialogHeight() {
                        return this.state.get("dialogHeight");
                    }
                    get dialogWidth() {
                        return this.state.get("dialogWidth");
                    }
                    get dialogFilters() {
                        return this.state.get("dialogFilters", []);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get items() {
                        return this.state.get("items");
                    }
                    set items(value) {
                        this.state.set("items", value);
                    }
                    get noItemsMessage() {
                        return this.state.get("noItemsMessage");
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", false);
                    }
                    set showCheckboxes(value) {
                        this.state.set("showCheckboxes", value);
                    }
                    template() {
                        return `<div></div>`;
                    }
                    focus() {
                        this.filter.focus();
                    }
                    reload(items, filterTerm) {
                        this.items.splice(0, this.items.length);
                        items.forEach((item) => {
                            this.items[this.items.length] = item;
                        });
                        this.list.refresh();
                        this.list.filter(filterTerm);
                        this.filter.setTerm(filterTerm);
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.items = [];
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                        this.button_init();
                        this.filter_init();
                        this.node.addClass("-pdjs-batch-field");
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.list.showCheckboxes = this.showCheckboxes;
                        this.button.enabled = this.enabled;
                        this.filter.enabled = this.enabled;
                        this.list.enabled = this.enabled;
                    }
                    list_init() {
                        this.m_list = new Controls.BatchFieldList({
                            items: this.items,
                            showCheckboxes: this.showCheckboxes,
                            noItemsMessage: this.noItemsMessage,
                            parent: this,
                            change: () => {
                                this.changeCallback(this.items);
                            }
                        });
                        this.controls.add(this.list);
                    }
                    button_init() {
                        this.m_button = new Controls.BatchFieldButton({
                            openDialog: _.bind(this.dialog_open, this),
                            list: this.list,
                            showCheckboxes: this.showCheckboxes,
                            tabIndex: this.tabIndex
                        });
                        this.controls.add(this.button);
                    }
                    filter_init() {
                        this.m_filter = new Controls.BatchFieldFilter({
                            list: this.list,
                            tabIndex: this.tabIndex,
                            change: (term) => {
                                this.list.filter(term);
                                this.changeCallback(this.items);
                            }
                        });
                        this.controls.add(this.filter);
                    }
                    dialog_open() {
                        Controls.BatchFieldDialog.open({
                            title: this.dialogTitle,
                            viewStateId: this.dialogViewStateId,
                            mapId: this.dialogMapId,
                            mapLabel: this.dialogMapLabel,
                            mapIcon: this.dialogMapIcon,
                            filters: this.dialogFilters,
                            height: this.dialogHeight,
                            width: this.dialogWidth,
                            select: {
                                ok: (sender, e) => {
                                    sender.close();
                                    _.each(this.items, (item) => {
                                        item.selected = false;
                                    });
                                    e.forEach(item => {
                                        if (_.findIndex(this.items, { id: item.id }) < 0) {
                                            this.items.push(item);
                                        }
                                    });
                                    this.items = _.sortBy(this.items, ["label"]);
                                    this.list.refresh();
                                }
                            }
                        });
                    }
                }
                Controls.BatchField = BatchField;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldButton extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get popUp() {
                        return this.m_popUp;
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get openDialogCallback() {
                        return this.state.get("openDialog", () => { });
                    }
                    get commandCallback() {
                        return this.state.get("command", () => { });
                    }
                    get dialogButtonNode() {
                        return this.node.find("button[role=dialog]");
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get popUpButtonNode() {
                        return this.node.find("button[role=popup]");
                    }
                    get list() {
                        return this.state.get("list");
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", false);
                    }
                    template() {
                        return `<div role="deck" class="-pdjs-batch-field-button">
                        <button role="dialog" tabIndex="${this.tabIndex}">
                            Select...
                        </button>
                        <button role="popup" tabIndex="${this.tabIndex}">
                            <i class="icofont-caret-down"></i>
                        </button>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.dialogButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.dialogButton_onClick, this));
                        this.popUpButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.popUpButton_onClick, this));
                        this.popUp_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.list.showCheckboxes = this.showCheckboxes;
                        this.dialogButtonNode.prop("disabled", !this.enabled);
                        this.popUpButtonNode.prop("disabled", !this.enabled);
                    }
                    popUp_init() {
                        this.m_popUp =
                            new PDJS.Shared.UI.Controls.PopUp({
                                anchor: this.popUpButtonNode,
                                width: 150,
                                tipped: {
                                    skin: "themed",
                                    position: "topright",
                                    offset: {
                                        x: 1,
                                        y: -3
                                    }
                                }
                            });
                        this.controls.add(this.m_popUp);
                        if (this.showCheckboxes) {
                            this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                                data: {
                                    id: "activateAll",
                                    label: "Activate All"
                                },
                                click: () => {
                                    this.popUp.hide();
                                    this.list.activateAll();
                                }
                            }));
                            this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                                data: {
                                    id: "deactivateAll",
                                    label: "Deactivate All"
                                },
                                click: () => {
                                    this.popUp.hide();
                                    this.list.deactivateAll();
                                }
                            }));
                        }
                        this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: {
                                id: "selectAll",
                                label: "Select All"
                            },
                            click: () => {
                                this.popUp.hide();
                                this.list.selectAll();
                            }
                        }));
                        this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: {
                                id: "deselectAll",
                                label: "Deselect All"
                            },
                            click: () => {
                                this.m_popUp.hide();
                                this.list.deselectAll();
                            }
                        }));
                        this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: {
                                id: "removeAll",
                                label: "Remove All"
                            },
                            click: () => {
                                this.popUp.hide();
                                this.list.removeAll();
                            }
                        }));
                        this.popUp.controls.add(new PDJS.Shared.UI.Controls.PopUpItem({
                            data: {
                                id: "removeSelected",
                                label: "Remove Selected"
                            },
                            click: () => {
                                this.popUp.hide();
                                this.list.removeSelected();
                            }
                        }));
                    }
                    dialogButton_onClick(e) {
                        this.openDialogCallback();
                    }
                    popUpButton_onClick(e) {
                        if (this.popUp.visible) {
                            this.popUp.hide();
                        }
                        else {
                            this.popUp.show();
                        }
                    }
                }
                Controls.BatchFieldButton = BatchFieldButton;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get filters() {
                        return this.state.get("filters", []);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId", null);
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get okButtonNode() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButtonNode() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get selections() {
                        return this.m_grid.getSelections().toArray();
                    }
                    get mapId() {
                        return this.state.get("mapId", "ObjectId");
                    }
                    get mapLabel() {
                        return this.state.get("mapName", "ObjectName");
                    }
                    get mapIcon() {
                        return this.state.get("mapIcon", null);
                    }
                    template() {
                        return super.template(`
            <div style="position:absolute;inset:0;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;">

                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                    <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                </div>
            </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.grid_init();
                        this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                        this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_onClick, this));
                    }
                    static open(options) {
                        return new BatchFieldDialog(options);
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: this.node.find("[data-role=grid]"),
                            selectionMode: "multiple",
                            viewStateId: this.viewStateId,
                            selectOnRightClick: false,
                            defaultSelectionEnabled: true,
                            selection: {
                                map: (e) => {
                                    return _.map(e.selections.toArray(), (item, index) => {
                                        return {
                                            id: item[this.mapId],
                                            label: item[this.mapLabel],
                                            icon: item[this.mapIcon],
                                            active: true,
                                            selected: true
                                        };
                                    });
                                }
                            },
                            dblclick: (e) => {
                                this.closeAndReturn();
                            },
                            needContext: (e) => {
                                e.filters = this.filters;
                            }
                        });
                    }
                    okButton_onClick(e) {
                        this.closeAndReturn();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    closeAndReturn() {
                        if (this.selections.length > -1) {
                            this.close({
                                name: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.Dialogs.MessageDialog.open({
                                dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                                title: "No Item Selected",
                                message: "No item has been selected. Select an item and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                }
                Controls.BatchFieldDialog = BatchFieldDialog;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldFilter extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get hasValue() {
                        return this.mask != null &&
                            !Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    get mask() {
                        return this.m_mask;
                    }
                    get value() {
                        return this.mask.textValue;
                    }
                    template() {
                        return `<div role="filter"></div>`;
                    }
                    focus() {
                        this.mask.focus();
                    }
                    setTerm(term) {
                        this.mask.textValue = term;
                        if (this.hasValue) {
                            this.mask.showText();
                        }
                        else {
                            this.mask.showMask();
                        }
                        this.changeCallback(this.value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.filter_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.mask.enabled = this.enabled;
                    }
                    filter_init() {
                        this.m_mask = new PDJS.Shared.UI.Controls.MaskedTextBox({
                            defaultMaskText: "Filter...",
                            onMaskFocus: (e) => {
                                this.mask.showText();
                                this.mask.focusText();
                            },
                            onTextFocus: (e) => {
                                this.mask.focusText();
                            },
                            onTextBlur: (e) => {
                                if (this.hasValue) {
                                    this.mask.showText();
                                }
                                else {
                                    this.mask.showMask();
                                }
                            },
                            onTextKeyUp: (e) => {
                                this.changeCallback(this.value);
                            }
                        });
                        this.controls.add(this.mask);
                        this.mask.maskNode.css({
                            fontStyle: "italic"
                        });
                    }
                }
                Controls.BatchFieldFilter = BatchFieldFilter;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get items() {
                        return this.parent.items;
                    }
                    get parent() {
                        return this.state.get("parent");
                    }
                    get batchFieldListItems() {
                        return this.controls.getByType(Controls.BatchFieldListItem);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get noItemsMessage() {
                        return this.state.get("noItemsMessage", "No items in list.");
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", false);
                    }
                    set showCheckboxes(value) {
                        this.state.set("showCheckboxes", value);
                    }
                    template() {
                        return `<div role="list"></div>`;
                    }
                    filter(term) {
                        let isFiltered = !Jade.String.isNullOrWhiteSpace(term);
                        let countOfMatches = 0;
                        let countOfItems = this.batchFieldListItems.count;
                        if (countOfItems == 0) {
                            return;
                        }
                        this.batchFieldListItems
                            .each((item) => {
                            let isMatch = !isFiltered ||
                                (isFiltered && item.label.toLowerCase().indexOf(term) > -1);
                            item.visible = isMatch;
                            countOfMatches += isMatch ? 1 : 0;
                        });
                        if (countOfMatches == 0) {
                            this.addMessage(`No items matched "${term}".`);
                        }
                        else {
                            this.removeMessage();
                        }
                        this.changeCallback();
                    }
                    selectAll() {
                        this.batchFieldListItems
                            .each((item) => {
                            item.selected = true;
                        });
                        this.items.forEach((item) => {
                            item.selected = false;
                        });
                        this.changeCallback();
                    }
                    deselectAll() {
                        this.batchFieldListItems
                            .each((item) => {
                            item.selected = false;
                        });
                        this.items.forEach((item) => {
                            item.selected = false;
                        });
                        this.changeCallback();
                    }
                    activateAll() {
                        this.batchFieldListItems
                            .each((item) => {
                            item.active = true;
                        });
                        this.items.forEach((item) => {
                            item.active = true;
                        });
                        this.changeCallback();
                    }
                    deactivateAll() {
                        this.batchFieldListItems
                            .each((item) => {
                            item.active = false;
                        });
                        this.items.forEach((item) => {
                            item.active = false;
                        });
                        this.changeCallback();
                    }
                    removeAll() {
                        this.controls.clear();
                        this.items.splice(0, this.items.length);
                        if (this.batchFieldListItems.count == 0) {
                            this.addNoItemsMessage();
                        }
                        this.changeCallback();
                    }
                    removeSelected() {
                        let removeItems = [];
                        let removeIds = [];
                        this.batchFieldListItems.each((item) => {
                            if (item.selected) {
                                removeItems[removeItems.length] = item;
                                removeIds[removeIds.length] = item.itemId;
                            }
                        });
                        removeItems.forEach((item) => {
                            this.controls.remove(item);
                        });
                        _.remove(this.items, (item) => {
                            return removeIds.indexOf(item.id) > -1;
                        });
                        this.changeCallback();
                        if (this.batchFieldListItems.count == 0) {
                            this.addNoItemsMessage();
                        }
                    }
                    refresh() {
                        this.controls.clear();
                        this.node.hide();
                        this.items.forEach((item) => {
                            this.controls.add(new Controls.BatchFieldListItem({
                                data: item,
                                showCheckbox: this.showCheckboxes,
                                tabIndex: this.tabIndex,
                                remove: (e) => {
                                    this.removeItem(e);
                                },
                                select: (e, isMultiSelect) => {
                                    this.items.forEach((item) => {
                                        if (isMultiSelect) {
                                            if (item.id == e.itemId) {
                                                item.selected = e.selected;
                                            }
                                        }
                                        else {
                                            item.selected = item.id == e.itemId;
                                        }
                                    });
                                    this.batchFieldListItems.each((item) => {
                                        if (isMultiSelect) {
                                            if (item.itemId == e.itemId) {
                                                item.selected = e.selected;
                                            }
                                        }
                                        else {
                                            item.selected = item.itemId == e.itemId;
                                        }
                                    });
                                    this.changeCallback();
                                },
                                check: (e) => {
                                    this.items.forEach((item) => {
                                        if (item.id == e.itemId) {
                                            item.active = e.active;
                                        }
                                    });
                                    this.changeCallback();
                                }
                            }));
                        });
                        this.node.show();
                        this.changeCallback();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addNoItemsMessage();
                        this.node.addClass(PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled ?
                            this.node.removeClass("-pdjs-disabled") :
                            this.node.addClass("-pdjs-disabled");
                    }
                    removeItem(item) {
                        _.remove(this.items, (record) => {
                            return record.id == item.itemId;
                        });
                        this.controls.remove(item);
                        this.changeCallback();
                    }
                    removeMessage() {
                        let message = this.controls
                            .getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message != null) {
                            this.controls.remove(message);
                        }
                    }
                    addMessage(text) {
                        let message = new PDJS.Shared.UI.Controls.Message({
                            message: text
                        });
                        this.removeMessage();
                        this.controls.add(message);
                        message.messageNode.css({
                            color: "var(--visiv-theme-input-inactive-text-color)",
                        });
                    }
                    addNoItemsMessage() {
                        this.addMessage(this.noItemsMessage);
                    }
                }
                Controls.BatchFieldList = BatchFieldList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class BatchFieldListItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get itemId() {
                        return this.state.get("data.id", "");
                    }
                    get label() {
                        return this.state.get("data.label", "");
                    }
                    get icon() {
                        return this.state.get("data.icon", "");
                    }
                    get active() {
                        return this.state.get("data.active", true);
                    }
                    set active(value) {
                        this.state.set("data.active", value);
                    }
                    get selected() {
                        return this.state.get("data.selected", true);
                    }
                    set selected(value) {
                        this.state.set("data.selected", value);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get checkBoxNode() {
                        return this.node.children("input[type=checkbox]");
                    }
                    get labelNode() {
                        return this.node.children("span");
                    }
                    get imgNode() {
                        return this.node.children("i");
                    }
                    get showCheckbox() {
                        return this.state.get("showCheckbox", false);
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    get removeCallback() {
                        return this.state.get("remove", () => { });
                    }
                    get checkCallback() {
                        return this.state.get("check", () => { });
                    }
                    get selectCallback() {
                        return this.state.get("select", () => { });
                    }
                    template() {
                        return `<div role="item" data-id="${this.itemId}" data-selected="${this.selected ? "true" : "false"}" 
                        class="-pdjs-batch-field-item ${this.showCheckbox ? "-pdjs-batch-field-item-checkbox" : ""}" 
                        style="display:${this.visible ? "none" : ""}">
                            <input type="checkbox" tabIndex="${this.tabIndex}" ${this.active ? "checked" : ""} />
                            <span>${this.label}</span>
                            <i class="icofont-close-squared"></i>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.imgNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onRemove, this));
                        this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.onSelect, this));
                        this.checkBoxNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onCheck, this));
                    }
                    onLoad(e) {
                        super.onLoad(e);
                        this.m_iconPath = Jade.IconSet.get("pd")
                            .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16);
                    }
                    onStateChanged() {
                        if (this.icon != null) {
                            this.labelNode.css({
                                backgroundImage: `url(${this.m_iconPath})`
                            });
                        }
                        if (this.visible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                        this.node.attr("data-selected", this.selected ? "true" : "false");
                        this.checkBoxNode.prop("checked", this.active);
                    }
                    onRemove(e) {
                        this.removeCallback(this);
                    }
                    onCheck(e) {
                        e.stopPropagation();
                        this.active = this.checkBoxNode.prop("checked");
                        this.checkCallback(this);
                    }
                    onSelect(e) {
                        let isCurrentlySelected = this.node.data("selected");
                        this.selected = !isCurrentlySelected;
                        this.node.attr("data-selected", !isCurrentlySelected ? "true" : "false");
                        this.selectCallback(this, e.ctrlKey);
                    }
                }
                Controls.BatchFieldListItem = BatchFieldListItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class Button extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get checked() {
                        return Jade.String.isNullOrWhiteSpace(this.node.attr("checked"));
                    }
                    set checked(value) {
                        value == true ?
                            this.node.attr("checked", "checked") :
                            this.node.removeAttr("checked");
                    }
                    get clickCallback() {
                        return this.state.get("click", () => { });
                    }
                    get enabled() {
                        return Jade.String.isNullOrWhiteSpace(this.node.attr("disabled"));
                    }
                    set enabled(value) {
                        this.node.prop("disabled", !value);
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    set icon(value) {
                        this.state.set("icon", value);
                    }
                    get iconSet() {
                        return this.state.get("iconSet", "pdjs");
                    }
                    set iconSet(value) {
                        this.state.set("iconSet");
                    }
                    get iconVisible() {
                        return this.imageNode.is(":visible");
                    }
                    set iconVisible(value) {
                        value ? this.imageNode.show() :
                            this.imageNode.hide();
                    }
                    get iconNode() {
                        return this.node.children("div[role=icon]");
                    }
                    get imageNode() {
                        return this.iconNode.children("img");
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get labelNode() {
                        return this.node.children("div[role=label]");
                    }
                    get labelVisible() {
                        return this.labelNode.is(":visible");
                    }
                    set labelVisible(value) {
                        value ?
                            this.labelNode.show() :
                            this.labelNode.hide();
                    }
                    get visible() {
                        return this.node.is(":visible");
                    }
                    set visible(value) {
                        value == true ?
                            this.node.show() :
                            this.node.hide();
                    }
                    template() {
                        return `<button class="-pdjs-shared-ui-controls-command-button">
                        <div role="icon">
                            <img />
                        </div>
                        <div role="label"></div>
                    </button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.hideTooltip();
                            this.onClick(e);
                        });
                    }
                    onClick(e) {
                        this.clickCallback(e);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.onPropertiesChanged();
                    }
                    onPropertiesChanged() {
                        this.imageNode.attr("src", this.getResolvedIcon());
                        this.iconVisible = this.isIconVisible();
                        this.labelVisible = this.isLabelVisible();
                        this.labelNode.html(this.label);
                        this.node.css({
                            gridGap: this.hasGridGap() ? "5px" : "0",
                            padding: this.isLabelVisible() ? "0 15px" : "0 7px",
                            display: this.visible ? "inline-grid" : "none"
                        });
                        this.createTooltip();
                    }
                    hasGridGap() {
                        return this.isIconVisible()
                            && this.isLabelVisible();
                    }
                    isIconVisible() {
                        return !Jade.String.isNullOrWhiteSpace(this.icon);
                    }
                    isLabelVisible() {
                        return !Jade.String.isNullOrWhiteSpace(this.label);
                    }
                    getResolvedIcon() {
                        return Jade.IconSet.get(this.iconSet)
                            .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16);
                    }
                    getTooltip() {
                        return ``;
                    }
                    createTooltip() {
                        PDJS.Shared.PopOver.remove(this.node);
                        let shouldCreate = this.enabled &&
                            this.visible;
                        if (!shouldCreate) {
                            return;
                        }
                        let content = `
                <div style="font-size:13px;line-height:20px;">
                    <b>${this.label}</b><br/>
                    ${this.getTooltip()}
                </div>`;
                        PDJS.Shared.PopOver.tooltip(this.node, content, {
                            position: "bottommiddle"
                        });
                    }
                    hideTooltip() {
                        PDJS.Shared.PopOver.hide(this.node);
                    }
                }
                Controls.Button = Button;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditor extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get allowInlineColors() {
                        return this.state.get("allowInlineColors", false);
                    }
                    get allowThemeColors() {
                        return this.state.get("allowThemeColors", false);
                    }
                    get allowTransparent() {
                        return this.state.get("allowTransparent", false);
                    }
                    get buttonCell() {
                        return this.node.find("div[data-button]");
                    }
                    get buttonNode() {
                        return this.node.find("[role=button]");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get default() {
                        return this.state.get("default");
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get input() {
                        return this.m_input;
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    get value() {
                        return this.state.get("value", "");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-color-editor">
                        <div data-swatch></div>
                        <div data-controls></div>
                        <div data-button>
                            <button role="button">
                                ...
                            </button>
                        </div>
                    </div>`;
                    }
                    focus() {
                        this.input.focusMask();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.input_init();
                        this.swatch_init();
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.button_click, this));
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.m_swatch.enabled = this.enabled;
                        this.m_input.enabled = this.enabled;
                    }
                    button_click(e) {
                        let panels = "both";
                        if (this.allowThemeColors && !this.allowInlineColors) {
                            panels = "themes";
                        }
                        if (!this.allowThemeColors && this.allowInlineColors) {
                            panels = "inline";
                        }
                        PDJS.Shared.UI.Controls.ColorsDialog.open({
                            color: this.value,
                            availablePanels: panels,
                            targetTheme: this.targetTheme,
                            select: {
                                ok: (sender, e) => {
                                    this.value = e.color;
                                    this.m_swatch.setColor(this.value);
                                    this.m_input.commitColor(this.value);
                                    this.changeCallback(this.value);
                                }
                            }
                        });
                    }
                    input_init() {
                        this.m_input = new Controls.ColorEditorInput({
                            default: this.default,
                            allowTransparent: this.allowTransparent,
                            allowThemeColors: this.allowThemeColors,
                            change: (e) => {
                                this.value = e.color;
                                if (this.m_swatch) {
                                    this.m_swatch.setColor(this.value);
                                }
                                this.changeCallback(this.value);
                            }
                        });
                        this.controls.add(this.m_input);
                        this.m_input.commitColor(this.value);
                    }
                    swatch_init() {
                        this.m_swatch = new Controls.ColorEditorSwatch({
                            insertAt: "div[data-swatch]",
                            allowInlineColors: this.allowInlineColors,
                            allowThemeColors: this.allowThemeColors,
                            allowTransparent: this.allowTransparent,
                            targetTheme: this.targetTheme,
                            change: (e) => {
                                this.value = e.color;
                                if (this.m_input) {
                                    this.m_input.commitColor(this.value);
                                }
                                this.changeCallback(this.value);
                            }
                        });
                        this.controls.add(this.m_swatch);
                        this.m_swatch.setColor(this.value);
                    }
                }
                Controls.ColorEditor = ColorEditor;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                function isValidHexColor(value, allowTransparency) {
                    let regex = allowTransparency ?
                        new RegExp("^#[a-fA-F0-9]{3,8}|transparent$", "gi") :
                        new RegExp("^#[a-fA-F0-9]{3,8}$", "gi");
                    let isNull = Jade.String.isNullOrWhiteSpace(value);
                    let isMatch = regex.test(value || "");
                    return (isNull && allowTransparency) || isMatch;
                }
                Controls.isValidHexColor = isValidHexColor;
                function isValidThemeColor(value) {
                    return value.startsWith("var(--") && value.endsWith(")");
                }
                Controls.isValidThemeColor = isValidThemeColor;
                function getSafeHexColor(value) {
                    return (/^#[a-fA-F0-9]{3,8}$/gi).test(value) ? value : "#FFFFFF";
                }
                Controls.getSafeHexColor = getSafeHexColor;
                function getThemeColorByVarRef(varRef) {
                    return _.first(PDJS.Shared.Themes.Theme.colors.filter((color) => {
                        return color.varRef.toLowerCase() === varRef.toLowerCase();
                    }));
                }
                Controls.getThemeColorByVarRef = getThemeColorByVarRef;
                function colorToHex(color) {
                    var ctx = document.createElement("canvas").getContext("2d");
                    ctx.fillStyle = color;
                    return ctx.fillStyle;
                }
                Controls.colorToHex = colorToHex;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let MaskedTextBoxEventNames;
                (function (MaskedTextBoxEventNames) {
                    MaskedTextBoxEventNames["onTextFocus"] = "onTextFocus";
                    MaskedTextBoxEventNames["onTextBlur"] = "onTextBlur";
                    MaskedTextBoxEventNames["onTextKeyDown"] = "onTextKeyDown";
                    MaskedTextBoxEventNames["onTextKeyPress"] = "onTextKeyPress";
                    MaskedTextBoxEventNames["onTextKeyUp"] = "onTextKeyUp";
                    MaskedTextBoxEventNames["onTextDoubleClick"] = "onTextDoubleClick";
                    MaskedTextBoxEventNames["onMaskFocus"] = "onMaskFocus";
                    MaskedTextBoxEventNames["onMaskBlur"] = "onMaskBlur";
                    MaskedTextBoxEventNames["onMaskKeyDown"] = "onMaskKeyDown";
                    MaskedTextBoxEventNames["onMaskKeyPress"] = "onMaskKeyPress";
                    MaskedTextBoxEventNames["onMaskKeyUp"] = "onMaskKeyUp";
                    MaskedTextBoxEventNames["onMaskDoubleClick"] = "onMaskDoubleClick";
                })(MaskedTextBoxEventNames || (MaskedTextBoxEventNames = {}));
                class MaskedTextBox extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get maskValue() {
                        return this.maskNode.val();
                    }
                    set maskValue(value) {
                        this.maskNode.val(value == null ? "" : value);
                    }
                    get textValue() {
                        return this.textNode.val();
                    }
                    set textValue(value) {
                        this.textNode.val(value == null ? "" : value);
                    }
                    get textNode() {
                        return this.node.find("input[role=text]");
                    }
                    get maskNode() {
                        return this.node.find("input[role=mask]");
                    }
                    get isInputVisible() {
                        return this.textNode.is(":visible");
                    }
                    get isMaskVisible() {
                        return this.maskNode.is(":visible");
                    }
                    get isTextFocused() {
                        return this.textNode.is(":focus");
                    }
                    get isMaskFocused() {
                        return this.maskNode.is(":focus");
                    }
                    get defaultMaskText() {
                        return this.state.get("defaultMaskText");
                    }
                    set defaultMaskText(value) {
                        this.state.set("defaultMaskText", value);
                    }
                    get textAndMaskNode() {
                        return this.node.find("div[data-role=input-and-mask]");
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    get autoTabIndex() {
                        return this.state.get("autoTabIndex", false);
                    }
                    onTextBlur(e) {
                    }
                    onTextFocus(e) {
                    }
                    onTextKeyDown(e) {
                    }
                    onTextKeyPress(e) {
                    }
                    onTextKeyUp(e) {
                    }
                    onTextDoubleClick(e) {
                    }
                    onTextShow() {
                    }
                    onTextHide() {
                    }
                    onMaskBlur(e) {
                    }
                    onMaskFocus(e) {
                    }
                    onMaskKeyDown(e) {
                    }
                    onMaskKeyPress(e) {
                    }
                    onMaskKeyUp(e) {
                    }
                    onMaskDoubleClick(e) {
                    }
                    onMaskShow() {
                    }
                    onMaskHide() {
                    }
                    onActivate(e) {
                        this.textNode.on(Jade.BrowserEvent.BLUR, _.bind((e) => {
                            this.onTextBlur(e);
                            this.state.get(MaskedTextBoxEventNames.onTextBlur, () => { })(e);
                        }, this));
                        this.textNode.on(Jade.BrowserEvent.FOCUS, _.bind((e) => {
                            this.onTextFocus(e);
                            this.state.get(MaskedTextBoxEventNames.onTextFocus, () => { })(e);
                        }, this));
                        this.textNode.on(Jade.BrowserEvent.KEYDOWN, _.bind((e) => {
                            this.onTextKeyDown(e);
                            this.state.get(MaskedTextBoxEventNames.onTextKeyDown, () => { })(e);
                        }, this));
                        this.textNode.on(Jade.BrowserEvent.KEYPRESS, _.bind((e) => {
                            this.onTextKeyPress(e);
                            this.state.get(MaskedTextBoxEventNames.onTextKeyPress, () => { })(e);
                        }, this));
                        this.textNode.on(Jade.BrowserEvent.KEYUP, _.bind((e) => {
                            this.onTextKeyUp(e);
                            this.state.get(MaskedTextBoxEventNames.onTextKeyUp, () => { })(e);
                        }, this));
                        this.textNode.on(Jade.BrowserEvent.DOUBLECLICK, _.bind((e) => {
                            this.onTextDoubleClick(e);
                            this.state.get(MaskedTextBoxEventNames.onTextDoubleClick, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.BLUR, _.bind((e) => {
                            this.onMaskBlur(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskBlur, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.FOCUS, _.bind((e) => {
                            this.focusMask();
                            this.onMaskFocus(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskFocus, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.KEYDOWN, _.bind((e) => {
                            this.onMaskKeyDown(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskKeyDown, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.KEYPRESS, _.bind((e) => {
                            this.onMaskKeyPress(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskKeyPress, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.KEYUP, _.bind((e) => {
                            this.onMaskKeyUp(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskKeyUp, () => { })(e);
                        }, this));
                        this.maskNode.on(Jade.BrowserEvent.DOUBLECLICK, _.bind((e) => {
                            this.onMaskDoubleClick(e);
                            this.state.get(MaskedTextBoxEventNames.onMaskDoubleClick, () => { })(e);
                        }, this));
                    }
                    showMask() {
                        this.textNode.hide();
                        this.onTextHide();
                        this.maskNode.show();
                        if (Jade.String.isNullOrWhiteSpace(this.maskValue)) {
                            this.maskValue = this.defaultMaskText;
                        }
                        this.onMaskShow();
                    }
                    showText() {
                        this.maskNode.hide();
                        this.onMaskHide();
                        this.textNode.show();
                        this.onTextShow();
                    }
                    focusMask() {
                        if (!this.isMaskFocused) {
                            this.maskNode.get(0).focus();
                        }
                        this.maskNode.get(0).select();
                    }
                    focusText() {
                        if (!this.isTextFocused) {
                            this.textNode.get(0).focus();
                        }
                        this.textNode.get(0).select();
                    }
                    focus() {
                        this.showText();
                        this.focusText();
                    }
                    template() {
                        return `<div class="${Controls.CssClass.MaskedTextBox}">   
                        <div data-role="input-and-mask">
                            <input 
                                type="text" 
                                role="text"
                                tabIndex="-1"
                                class="${PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget}" />
                            <input 
                                type="text" 
                                role="mask"
                                readonly
                                class="${PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget}"/>
                        </div>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (Jade.String.isNullOrWhiteSpace(this.maskValue)) {
                            this.maskValue = this.defaultMaskText;
                        }
                        this.maskNode.prop("disabled", !this.enabled);
                        this.textNode.prop("disabled", !this.enabled);
                        if (!this.autoTabIndex) {
                            this.maskNode.attr("tabIndex", this.tabIndex);
                        }
                        if (!this.enabled) {
                            this.node.addClass(Shared.UI.CssClass.Disabled);
                        }
                        else {
                            this.node.removeClass(Shared.UI.CssClass.Disabled);
                        }
                    }
                }
                Controls.MaskedTextBox = MaskedTextBox;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditorInput extends PDJS.Shared.UI.Controls.MaskedTextBox {
                    constructor(options) {
                        super(_.extend({ autoTabIndex: true }, options));
                    }
                    get allowInlineColors() {
                        return this.state.get("allowInlineColors", false);
                    }
                    get allowTransparent() {
                        return this.state.get("allowTransparent", false);
                    }
                    get allowThemeColors() {
                        return this.state.get("allowThemeColors", false);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get default() {
                        return this.state.get("default");
                    }
                    get hexColor() {
                        return this.state.get("hexColor");
                    }
                    set hexColor(value) {
                        this.state.set("hexColor", value);
                    }
                    get themeColorName() {
                        return this.state.get("themeColorName");
                    }
                    set themeColorName(value) {
                        this.state.set("themeColorName", value);
                    }
                    get themeColorVarRef() {
                        return this.state.get("themeColorVarRef");
                    }
                    set themeColorVarRef(value) {
                        this.state.set("themeColorVarRef", value);
                    }
                    setColor(color) {
                        this.setIsValidThemeStyle(false);
                        this.hexColor = null;
                        this.themeColorName = null;
                        this.themeColorVarRef = null;
                        let isValidHex = Controls.isValidHexColor(color, this.allowTransparent);
                        if (isValidHex) {
                            this.hexColor = color;
                            return;
                        }
                        if (!this.allowThemeColors) {
                            return;
                        }
                        let isValidTheme = Controls.isValidThemeColor(color);
                        this.themeColorName = null;
                        this.themeColorVarRef = null;
                        if (isValidTheme) {
                            let themeColor = Controls.getThemeColorByVarRef(color);
                            if (themeColor != null) {
                                this.themeColorVarRef = themeColor.varRef;
                                this.themeColorName = themeColor.uniqueName;
                                this.setIsValidThemeStyle(true);
                            }
                            return;
                        }
                        this.validThemeColorNameCheck(color, () => {
                            this.setIsValidThemeStyle(false);
                        });
                    }
                    commitColor(color) {
                        this.node.removeClass("-is-watermark");
                        this.node.removeClass("-is-watermark");
                        if (this.default != null && (this.default == (color === null || color === void 0 ? void 0 : color.toLowerCase()) || Jade.String.isNullOrWhiteSpace(color))) {
                            color = this.default;
                            this.node.addClass("-is-watermark");
                            this.node.addClass("-is-watermark");
                        }
                        this.setColor(color);
                        if (this.themeColorName) {
                            this.maskValue = this.themeColorName;
                            this.textValue = this.themeColorName;
                            return;
                        }
                        if (this.hexColor) {
                            this.maskValue = this.hexColor;
                            this.textValue = this.hexColor;
                            return;
                        }
                        this.maskValue = color;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-color-editor-input");
                    }
                    onMaskFocus(e) {
                        super.onMaskFocus(e);
                        this.showText();
                        this.focusText();
                    }
                    onTextKeyUp(e) {
                        super.onTextKeyUp(e);
                        let ignore = e.keyCode == Jade.KeyCode.Tab ||
                            e.keyCode == Jade.KeyCode.Enter ||
                            e.keyCode == Jade.KeyCode.Shift ||
                            e.keyCode == Jade.KeyCode.ArrowDown ||
                            e.keyCode == Jade.KeyCode.ArrowLeft ||
                            e.keyCode == Jade.KeyCode.ArrowRight ||
                            e.keyCode == Jade.KeyCode.ArrowUp;
                        if (ignore) {
                            return;
                        }
                        if (e.keyCode == Jade.KeyCode.Delete || e.keyCode == Jade.KeyCode.Backspace) {
                            if (this.allowTransparent && Jade.String.isNullOrWhiteSpace(this.textValue)) {
                                this.maskValue = this.default || "";
                                this.textValue = this.default || "";
                                this.focusText();
                            }
                        }
                        this.setColor(this.textValue);
                        this.invokeChangeCallback();
                    }
                    onTextBlur(e) {
                        super.onTextBlur(e);
                        this.showMask();
                        this.setColor(this.textValue);
                        this.commitColor(this.textValue);
                        this.invokeChangeCallback();
                    }
                    invokeChangeCallback() {
                        if (this.themeColorName) {
                            this.changeCallback({
                                color: this.themeColorVarRef,
                                colorName: this.themeColorName,
                            });
                            return;
                        }
                        if (this.hexColor) {
                            this.changeCallback({
                                color: this.hexColor
                            });
                            return;
                        }
                        this.changeCallback({
                            color: this.textValue
                        });
                    }
                    validThemeColorNameCheck(colorName, noMatchFn = (() => { })) {
                        let themeColor = _.first(Shared.Themes.Theme.colors.filter((color) => {
                            var _a, _b;
                            return color.uniqueName.toLowerCase() == colorName.toLowerCase() &&
                                (color.isAssignable === true || color.uniqueName.toLowerCase() == ((_a = this.default) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || color.id.toLowerCase() == ((_b = this.default) === null || _b === void 0 ? void 0 : _b.toLowerCase()));
                        }));
                        if (themeColor == null) {
                            noMatchFn();
                            return;
                        }
                        this.themeColorName = themeColor.uniqueName;
                        this.themeColorVarRef = themeColor.varRef;
                        this.commitColor(themeColor.varRef);
                        this.invokeChangeCallback();
                    }
                    setIsValidThemeStyle(enabled) {
                        var cssClass = "-is-valid-theme-color";
                        enabled ?
                            this.node.addClass(cssClass) :
                            this.node.removeClass(cssClass);
                    }
                }
                Controls.ColorEditorInput = ColorEditorInput;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PopUp extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_popUpCreated = false;
                    }
                    get anchor() {
                        return this.state.get("anchor");
                    }
                    get height() {
                        return this.state.get("height", null);
                    }
                    get width() {
                        return this.state.get("width", 200);
                    }
                    get visible() {
                        return !!Tipped.visible(this.anchor);
                    }
                    get tipped() {
                        return this.state.get("tipped", {});
                    }
                    get onCreateCallback() {
                        return this.state.get("onCreate", () => { });
                    }
                    template() {
                        let maxHeight = this.tipped.maxHeight != null ?
                            (this.tipped.maxHeight === 0 ? null : this.tipped.maxHeight) : 200;
                        return `<div style="height:${this.height}px;width:${this.width}px;display:none;${maxHeight !== null ? `max-height:${maxHeight};` : ""}"></div>`;
                    }
                    show() {
                        this.ensureTippedPopUp();
                        PDJS.Shared.PopOver.show(this.anchor);
                    }
                    hide() {
                        PDJS.Shared.PopOver.hide(this.anchor);
                    }
                    destroy() {
                        PDJS.Shared.PopOver.remove(this.anchor.get(0));
                        super.destroy();
                    }
                    popUp_onCreate() {
                        this.onCreateCallback();
                    }
                    ensureTippedPopUp() {
                        if (this.m_popUpCreated == false) {
                            this.node.detach();
                            PDJS.Shared.PopOver.menu(this.anchor, this.node, this.getPopUpOptions());
                            this.node.show();
                            this.popUp_onCreate();
                            this.m_popUpCreated = true;
                        }
                    }
                    getPopUpOptions(options) {
                        return _.merge({
                            maxWidth: this.width,
                            detach: true,
                        }, options || {}, this.tipped);
                    }
                }
                Controls.PopUp = PopUp;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditorList extends PDJS.Shared.UI.Controls.PopUp {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    template() {
                        return `<div class="-fb-color-editor-list" style="display:none;">
                        <div role="list"></div>
                        <div role="search"></div>
                    </div>`;
                    }
                    show() {
                        if (!this.enabled) {
                            return;
                        }
                        setTimeout(() => {
                            this.node.css({ display: "grid" });
                        }, 100);
                        this.node.css({
                            display: "grid",
                            width: "325px"
                        });
                        this.list_init();
                        this.search_init();
                        super.show();
                    }
                    hide() {
                        super.hide();
                        this.filterItems("");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled ? this.node.show() : this.node.hide();
                    }
                    getPopUpOptions(options) {
                        return super.getPopUpOptions({
                            position: {
                                target: "bottomright",
                                tooltip: "topright"
                            },
                            offset: {
                                y: 4,
                                x: 5
                            }
                        });
                    }
                    list_init() {
                        if (this.m_list != null) {
                            return;
                        }
                        this.m_list = new PDJS.Shared.UI.Controls.ListView({
                            insertAt: "div[role=list]",
                            data: [],
                            binding: {
                                label: "name",
                                value: "varRef"
                            },
                            allowRemove: false,
                            height: "200px",
                            change: (e) => {
                                let item = e.selected.first();
                                if (item != null) {
                                    this.changeCallback({
                                        color: item.data.value,
                                        colorName: item.data.label
                                    });
                                }
                                this.hide();
                            },
                            createItem: (e) => {
                                return new Controls.ColorEditorListItem(e);
                            }
                        });
                        this.controls.add(this.m_list);
                        this.m_list.node.addClass("-feature-blend-style");
                        PDJS.Shared.Themes.Theme.colors.forEach((color) => {
                            color.targetTheme = this.targetTheme;
                            this.m_list.addItem(color);
                        });
                    }
                    search_init() {
                        if (this.m_search != null) {
                            return;
                        }
                        this.m_search = new PDJS.Shared.UI.Controls.SearchBox({
                            insertAt: "div[role=search]",
                            defaultMaskText: "Filter colors...",
                            onSearch: (e) => {
                                this.filterItems(e.term);
                            }
                        });
                        this.controls.add(this.m_search);
                    }
                    filterItems(term) {
                        term = term.toLowerCase();
                        let termHasValue = !Jade.String.isNullOrWhiteSpace(term);
                        this.m_list.items.each((item) => {
                            let isMatch = termHasValue ?
                                item.data.label.toLowerCase().includes(term) : true;
                            isMatch ? item.node.show() : item.node.hide();
                        });
                    }
                }
                Controls.ColorEditorList = ColorEditorList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditorListItem extends PDJS.Shared.UI.Controls.ListViewItemBase {
                    constructor(options) {
                        super(options);
                        options;
                    }
                    get colorNode() {
                        return this.swatchNode.children("div[role=color]");
                    }
                    get color() {
                        return this.value;
                    }
                    get isColorTransparent() {
                        return Jade.String.isNullOrWhiteSpace(this.color);
                    }
                    get swatchNode() {
                        return this.templateNode.find("div[role=swatch]");
                    }
                    get targetTheme() {
                        return this.data.get("targetTheme");
                    }
                    get colorUniqueName() {
                        return this.data.get("uniqueName", "");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.setColor();
                        this.setTheme();
                    }
                    templateContent() {
                        return `<div class="-pdjs-fb-color-editor-list-item">
                        <div role="swatch">
                            <div role="color"></div>
                        </div>
                        <div role="label">${this.colorUniqueName}</div>
                    </div>`;
                    }
                    setColor() {
                        if (this.isColorTransparent) {
                            return;
                        }
                        this.colorNode.css({
                            backgroundColor: this.color
                        });
                    }
                    setTheme() {
                        switch (this.targetTheme) {
                            case PDJS.Services.Themes.ThemeScope.Hub:
                                this.colorNode.addClass("-theme-hub");
                            case PDJS.Services.Themes.ThemeScope.Canvas:
                                this.colorNode.addClass("-theme-canvas");
                                break;
                            case PDJS.Services.Themes.ThemeScope.Designer:
                                this.colorNode.addClass("-theme-designer");
                                break;
                        }
                    }
                }
                Controls.ColorEditorListItem = ColorEditorListItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditorSwatch extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get allowInlineColors() {
                        return this.state.get("allowInlineColors", false);
                    }
                    get allowThemeColors() {
                        return this.state.get("allowThemeColors", false);
                    }
                    get allowTransparent() {
                        return this.state.get("allowTransparent", false);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get colorNode() {
                        return this.node.children("div[role=color]");
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    template() {
                        return `<div class="-fb-color-editor-swatch">
                        <div role="color"></div>
                    </div>`;
                    }
                    getColor() {
                        let result = this.colorNode.get(0).style.backgroundColor;
                        if (result.startsWith("var(")) {
                            result = result.replace("var(", "").replace(")", "");
                            result = getComputedStyle(this.colorNode.get(0))
                                .getPropertyValue(result);
                        }
                        result = Controls.colorToHex(result);
                        return result;
                    }
                    setColor(color) {
                        let isValidHex = Controls.isValidHexColor(color, this.allowTransparent);
                        this.setInvalidSwatch(false);
                        if (isValidHex) {
                            this.colorNode.get(0).style.backgroundColor = color;
                            return;
                        }
                        if (!this.allowThemeColors) {
                            this.setInvalidSwatch(true);
                            return;
                        }
                        let isValidTheme = Controls.isValidThemeColor(color);
                        if (isValidTheme) {
                            this.colorNode.get(0).style.backgroundColor = color;
                            return;
                        }
                        this.setInvalidSwatch(true);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.init_popup();
                        switch (this.targetTheme) {
                            case PDJS.Services.Themes.ThemeScope.Canvas:
                                this.node.addClass("-theme-canvas");
                                break;
                            case PDJS.Services.Themes.ThemeScope.Designer:
                                this.node.addClass("-theme-designer");
                                break;
                        }
                        if (this.allowTransparent) {
                            this.node.addClass("-is-transparent");
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled && this.allowInlineColors ?
                            this.node.on(Jade.BrowserEvent.CLICK, () => {
                                this.m_popup.show();
                            }) :
                            this.node.off(Jade.BrowserEvent.CLICK);
                    }
                    init_popup() {
                        this.m_popup = new Controls.ColorEditorSwatchPopUp({
                            anchor: this.node,
                            swatch: this,
                            change: (e) => {
                                this.setColor(e.color);
                                this.changeCallback(e);
                            }
                        });
                        this.controls.add(this.m_popup);
                    }
                    setInvalidSwatch(enabled) {
                        let cssClass = "-fb-swatch-error";
                        enabled ?
                            this.colorNode.addClass(cssClass) :
                            this.colorNode.removeClass(cssClass);
                    }
                }
                Controls.ColorEditorSwatch = ColorEditorSwatch;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorEditorSwatchPopUp extends PDJS.Shared.UI.Controls.PopUp {
                    constructor(options) {
                        super(options);
                        this.m_anchor = options.anchor;
                        this.m_swatch = options.swatch;
                    }
                    get swatch() {
                        return this.m_swatch;
                    }
                    get colorPickerNode() {
                        return this.node.find("[role=picker]");
                    }
                    get colorPicker() {
                        return this.colorPickerNode
                            .data("kendoFlatColorPicker");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    show() {
                        super.show();
                        setTimeout(() => {
                            this.colorpicker_init();
                        }, 100);
                    }
                    template() {
                        return `<div class="-fb-color-editor-swatch-popup" style="display:none;">
                        <div role="picker" class="-fb-color-editor-swatch-popup-picker"></div>
                    </div>`;
                    }
                    getPopUpOptions(options) {
                        return super.getPopUpOptions({
                            position: {
                                target: "bottomleft",
                                tooltip: "topleft"
                            },
                            offset: {
                                y: 3
                            },
                            onShow: (content, element) => {
                                if (this.colorPicker != null) {
                                    this.colorPicker.value(Controls.getSafeHexColor(this.swatch.getColor()));
                                }
                            }
                        });
                    }
                    colorpicker_init() {
                        if (this.colorPicker != null) {
                            return;
                        }
                        this.colorPickerNode.kendoFlatColorPicker({
                            preview: false,
                            value: Controls.getSafeHexColor(this.swatch.getColor()),
                            change: (e) => {
                                this.changeCallback({
                                    color: (e.value || "#FFFFFF").toUpperCase()
                                });
                            }
                        }).data("kendoFlatColorPicker");
                    }
                }
                Controls.ColorEditorSwatchPopUp = ColorEditorSwatchPopUp;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ThemeColorsList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get dblclickCallback() {
                        return this.state.get("dblclick", () => { });
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get height() {
                        return this.state.get("height", "200px");
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    filter(term) {
                        this.m_list.filter((item) => {
                            return Jade.String.isNullOrWhiteSpace(term) ? true :
                                item.data.label.toLowerCase().indexOf(term.toLowerCase()) > -1;
                        });
                    }
                    select(color) {
                        this.m_list.deselectAll();
                        this.m_list.select([color]);
                        this.m_list.scrollIntoView(color);
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-theme-colors-list"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled ? this.node.show() : this.node.hide();
                    }
                    list_init() {
                        if (this.m_list != null) {
                            return;
                        }
                        this.m_list = new PDJS.Shared.UI.Controls.ListView({
                            data: [],
                            binding: {
                                label: "uniqueName",
                                value: "varRef"
                            },
                            allowRemove: false,
                            height: this.height,
                            dblClick: (e) => {
                                let item = e.selected.first();
                                if (item != null) {
                                    this.dblclickCallback({
                                        color: item.data.value,
                                        colorName: item.data.label
                                    });
                                }
                            },
                            change: (e) => {
                                let item = e.selected.first();
                                if (item != null) {
                                    this.changeCallback({
                                        color: item.data.value,
                                        colorName: item.data.label
                                    });
                                }
                            },
                            createItem: (e) => {
                                e.targetTheme = this.targetTheme;
                                return new Controls.ColorEditorListItem(e);
                            }
                        });
                        this.controls.add(this.m_list);
                        this.m_list.node.addClass("-feature-blend-style");
                        PDJS.Shared.Themes.Theme.colors.forEach((color) => {
                            if (color.isAssignable) {
                                color.targetTheme = this.targetTheme;
                                this.m_list.addItem(color);
                            }
                        });
                    }
                }
                Controls.ThemeColorsList = ThemeColorsList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorsDialog extends Jade.UI.Dialogs.DialogOf {
                    constructor(options) {
                        super(options);
                    }
                    get availablePanels() {
                        return this.state.get("availablePanels", "both");
                    }
                    get color() {
                        return this.state.get("color", "#FFFFFF");
                    }
                    set color(value) {
                        this.state.set("color", value);
                    }
                    get customButton() {
                        return this.node.find("button[value=custom]");
                    }
                    get tabsNode() {
                        return this.node.find(".-pdjs-shared-ui-controls-colors-dialog-tabs");
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    get themeButton() {
                        return this.node.find("button[value=theme]");
                    }
                    get selectedPanel() {
                        return this.m_themesPanel.node.css("display") == "none" ? "inline" : "themes";
                    }
                    get rootNode() {
                        return this.node.find(".-pdjs-shared-ui-controls-colors-dialog-content");
                    }
                    template() {
                        return super.template(`
                    <div class="-pdjs-shared-ui-controls-colors-dialog-content">
                        <div class="-pdjs-shared-ui-controls-colors-dialog-tabs">
                            <div>
                                <button value="theme">Theme Color</button>
                            </div>
                            <div>
                                <button value="custom">Inline Color</button>
                            </div>
                        </div>
                        <div class="-pdjs-shared-ui-controls-colors-dialog-body" data-controls></div>
                    </div>`);
                    }
                    static open(options) {
                        return new ColorsDialog(options);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.customPanel_init();
                        this.themesPanel_init();
                        this.dialog_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.loadColor();
                    }
                    onDialogSelect(e, data) {
                        e.handled = true;
                        e.name == "ok" ?
                            this.okAndClose() :
                            this.close();
                    }
                    getDefaultOptions() {
                        return {
                            title: "Select | Color",
                            height: 384,
                            width: 420,
                            resizable: false
                        };
                    }
                    dialog_init() {
                        this.node.addClass("-pdjs-shared-ui-controls-colors-dialog");
                        this.customButton.on(Jade.BrowserEvent.CLICK, () => { this.showCustom(); });
                        this.themeButton.on(Jade.BrowserEvent.CLICK, () => { this.showThemes(); });
                        this.buttonsDeck.addAutoButtons("ok", "cancel");
                        switch (this.availablePanels) {
                            case "inline":
                                this.tabsVisible(false);
                                this.showCustom();
                                break;
                            case "themes":
                                this.tabsVisible(false);
                                this.showThemes();
                                break;
                            default:
                                this.showThemes();
                                break;
                        }
                    }
                    customPanel_init() {
                        this.m_customPanel = new PDJS.Shared.UI.Controls.ColorPanelCustom({
                            color: this.color
                        });
                        this.controls.add(this.m_customPanel);
                    }
                    themesPanel_init() {
                        this.m_themesPanel = new PDJS.Shared.UI.Controls.ColorPanelThemes({
                            color: this.color,
                            targetTheme: this.targetTheme,
                            dblclick: (e) => {
                                this.okAndClose();
                            }
                        });
                        this.controls.add(this.m_themesPanel);
                    }
                    showThemes() {
                        this.m_customPanel.hide();
                        this.m_themesPanel.show();
                        this.customButton.removeClass("-pdjs-selected");
                        this.themeButton.addClass("-pdjs-selected");
                    }
                    showCustom() {
                        this.m_themesPanel.hide();
                        this.m_customPanel.show();
                        this.customButton.addClass("-pdjs-selected");
                        this.themeButton.removeClass("-pdjs-selected");
                    }
                    okAndClose() {
                        let color = null;
                        switch (this.selectedPanel) {
                            case "inline":
                                color = this.m_customPanel.value;
                                break;
                            case "themes":
                                color = this.m_themesPanel.value;
                                break;
                        }
                        this.close({
                            name: "ok",
                            data: { color: color }
                        });
                    }
                    loadColor() {
                        if (PDJS.Shared.Colors.Color.isThemeColor(this.color) && this.availablePanels !== "inline") {
                            this.showThemes();
                            return;
                        }
                        if (PDJS.Shared.Colors.Color.isHexColor(this.color) && this.availablePanels !== "themes") {
                            this.showCustom();
                            return;
                        }
                        this.showThemes();
                    }
                    tabsVisible(visible) {
                        visible ?
                            this.tabsNode.show() :
                            this.tabsNode.hide();
                        this.rootNode.css({
                            gridTemplateRows: visible ? "max-content auto" : "auto"
                        });
                        if (!visible) {
                            this.setWindowOptions({
                                height: 348
                            });
                        }
                    }
                }
                Controls.ColorsDialog = ColorsDialog;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorPanelCustom extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get color() {
                        return this.state.get("color");
                    }
                    get inputs() {
                        return this.m_inputs;
                    }
                    set inputs(value) {
                        this.m_inputs = value;
                    }
                    get picker() {
                        return this.m_picker;
                    }
                    set picker(value) {
                        this.m_picker = value;
                    }
                    get pickerNode() {
                        return this.node.children("div[role=picker]");
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    hide() {
                        this.node.hide();
                    }
                    show() {
                        this.node.css({
                            display: "grid"
                        });
                        this.picker_init();
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-colors-dialog-custom-panel">
                        <div role="picker"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.picker_init();
                        this.inputs_init();
                    }
                    picker_init() {
                        if (this.picker != null) {
                            this.picker.destroy();
                            this.pickerNode.empty();
                        }
                        this.picker = this.pickerNode.kendoFlatColorPicker({
                            preview: false,
                            value: Controls.getSafeHexColor(this.color),
                            change: (e) => {
                                let nextColor = tinycolor(e.value);
                                let prevColor = this.inputs.getColor();
                                nextColor.setAlpha(prevColor.getAlpha());
                                this.inputs.setColor(nextColor.toHex8String());
                            }
                        }).data("kendoFlatColorPicker");
                        this.picker.value(this.value || "#FFFFFF");
                    }
                    inputs_init() {
                        this.inputs = new Controls.ColorPanelCustomValues({
                            value: this.color,
                            change: (color) => {
                                this.value = color;
                                this.picker.value(color);
                            }
                        });
                        this.controls.add(this.inputs);
                    }
                }
                Controls.ColorPanelCustom = ColorPanelCustom;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorPanelCustomValues extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_sliderChangeEventHandler = _.bind(this.slide_change, this);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get color() {
                        return this.m_color;
                    }
                    set color(value) {
                        this.m_color = value;
                    }
                    get colorNode() {
                        return this.node.find(".-pdjs-shared-colors-picker-values-color-swatch-color");
                    }
                    get hex() {
                        return this.hexNode.val();
                    }
                    set hex(value) {
                        this.hexNode.val(value);
                    }
                    get hexNode() {
                        return this.node.find(".-pdjs-shared-colors-picker-values-color-hex");
                    }
                    get inputsNode() {
                        return this.node.find(".-pdjs-shared-colors-picker-values-inputs");
                    }
                    get type() {
                        return this.typeNode.val();
                    }
                    get typeNode() {
                        return this.node.find("select");
                    }
                    get value1() {
                        return this.getValueNode(1).val();
                    }
                    set value1(value) {
                        this.getValueNode(1).val(value);
                    }
                    get value1Node() {
                        return this.getValueNode(1);
                    }
                    get slide1() {
                        return this.getSlideNode(1).val();
                    }
                    set slide1(value) {
                        this.getSlideNode(1).val(value);
                    }
                    get slide1Node() {
                        return this.getSlideNode(1);
                    }
                    get value2() {
                        return this.getValueNode(2).val();
                    }
                    set value2(value) {
                        this.getValueNode(2).val(value);
                    }
                    get value2Node() {
                        return this.getValueNode(2);
                    }
                    get slide2() {
                        return this.getSlideNode(2).val();
                    }
                    set slide2(value) {
                        this.getSlideNode(2).val(value);
                    }
                    get slide2Node() {
                        return this.getSlideNode(2);
                    }
                    get value3() {
                        return this.getValueNode(3).val();
                    }
                    set value3(value) {
                        this.getValueNode(3).val(value);
                    }
                    get value3Node() {
                        return this.getValueNode(3);
                    }
                    get slide3() {
                        return this.getSlideNode(3).val();
                    }
                    set slide3(value) {
                        this.getSlideNode(3).val(value);
                    }
                    get slide3Node() {
                        return this.getSlideNode(3);
                    }
                    get value4() {
                        return this.getValueNode(4).val();
                    }
                    set value4(value) {
                        this.getValueNode(4).val(value);
                    }
                    get value4Node() {
                        return this.getValueNode(4);
                    }
                    get slide4() {
                        return this.getSlideNode(4).val();
                    }
                    set slide4(value) {
                        this.getSlideNode(4).val(value);
                    }
                    get slide4Node() {
                        return this.getSlideNode(4);
                    }
                    get value() {
                        return this.state.get("value", "#FFFFFFFF");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    setColor(value) {
                        this.setColorValue(value);
                    }
                    getColor() {
                        return this.color;
                    }
                    template() {
                        return `<div class="-pdjs-shared-colors-picker-values">
                        <div class="-pdjs-shared-colors-picker-values-color">
                            <div class="-pdjs-shared-colors-picker-values-color-type">
                                <select>
                                    <option value="hsla">HSLA</option>
                                    <option value="rgba">RGBA</option>
                                </select>
                            </div>
                            <div class="-pdjs-shared-colors-picker-values-color-swatch">
                                <div class="-pdjs-shared-colors-picker-values-color-swatch-color"></div>
                            </div>
                            <div>
                                <input type="text" class="-pdjs-shared-colors-picker-values-color-hex" />
                            </div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.renderInputs();
                        this.typeNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.type_change, this));
                        this.node.on(Jade.BrowserEvent.CHANGE, "input[role=value]", _.bind(this.input_change, this));
                        this.hexNode.on(Jade.BrowserEvent.KEYUP, () => {
                            this.setColorValue(this.hex, "hex");
                        });
                        this.hexNode.on(Jade.BrowserEvent.FOCUS, () => {
                            this.hexNode.select();
                        });
                        if (PDJS.Shared.Colors.Color.isHexColor(this.value)) {
                            this.setColor(this.value);
                        }
                    }
                    renderInputs() {
                        this.node.get(0).querySelectorAll("input[role=slide]").forEach(el => {
                            el.removeEventListener("input", this.m_sliderChangeEventHandler);
                        });
                        let result = null;
                        switch (this.type) {
                            case "hsla":
                                result = this.renderHSL();
                                break;
                            case "rgba":
                                result = this.renderRGB();
                                break;
                        }
                        if (this.inputsNode.length > 0) {
                            this.inputsNode.remove();
                        }
                        this.node.append($(result));
                        this.node.get(0).querySelectorAll("input[role=slide]").forEach(el => {
                            el.addEventListener("input", this.m_sliderChangeEventHandler);
                        });
                        if (this.color == null) {
                            this.color = tinycolor(this.value);
                        }
                        this.setColor(this.color.toHex8String());
                    }
                    renderHSL() {
                        return `<div class="-pdjs-shared-colors-picker-values-inputs">
                        ${this.renderSlider(1, "H", 0, 359, "Hue")}
                        ${this.renderSlider(2, "S", 0, 100, "Saturation")}
                        ${this.renderSlider(3, "L", 0, 100, "Lightness")}
                        ${this.renderSlider(4, "A", 0, 100, "Alpha / Opactiy")}
                    </div>`;
                    }
                    renderRGB() {
                        return `<div class="-pdjs-shared-colors-picker-values-inputs">
                        ${this.renderSlider(1, "R", 0, 255, "Red Channel")}
                        ${this.renderSlider(2, "G", 0, 255, "Green Channel")}
                        ${this.renderSlider(3, "B", 0, 255, "Blue Channel")}
                        ${this.renderSlider(4, "A", 0, 100, "Alpha / Opactiy")}
                    </div>`;
                    }
                    renderSlider(id, label, min, max, tooltip) {
                        return `<div class="-pdjs-shared-colors-picker-values-input">
                        <div class="-pdjs-shared-colors-picker-values-input-label" title="${tooltip}">${label}</div>
                        <div class="-pdjs-shared-colors-picker-values-input-value">
                            <input role="value" data-id="${id}" type="number" min="${min}" max="${max}" title="${tooltip}" />
                        </div>
                        <div class="-pdjs-shared-colors-picker-values-input-slide">
                            <input role="slide" data-id="${id}" type="range" min="${min}" max="${max}">
                        </div>
                    </div>`;
                    }
                    type_change(e) {
                        this.renderInputs();
                    }
                    input_change(e) {
                        let input = $(e.currentTarget);
                        let slide = this.node.find(`input[role=slide][data-id=${input.data("id")}]`);
                        slide.val(input.val());
                        this.setColorValue(this.getColorValue(), "value");
                    }
                    slide_change(e) {
                        let slide = $(e.currentTarget);
                        let input = this.node.find(`input[role=value][data-id=${slide.data("id")}]`);
                        input.val(slide.val());
                        this.setColorValue(this.getColorValue(), "slide");
                    }
                    getColorValue() {
                        switch (this.type) {
                            case "hsla":
                                return this.getHSLA();
                            case "rgba":
                                return this.getRGBA();
                        }
                    }
                    setColorValue(value, source = "none") {
                        this.color = tinycolor(value);
                        if (source != "hex") {
                            this.hex = this.color.toHex8String();
                        }
                        switch (this.type) {
                            case "hsla":
                                this.setHSLA(this.color.toHsl(), source);
                                break;
                            case "rgba":
                                this.setRGBA(this.color.toRgb(), source);
                                break;
                        }
                        this.colorNode.css({
                            backgroundColor: this.getColorValue()
                        });
                        this.changeCallback(this.hex);
                    }
                    getHSLA() {
                        return `hsla(${this.value1}, ${this.value2}%, ${this.value3}%, ${this.getAlpha()})`;
                    }
                    getRGBA() {
                        return `rgba(${this.value1}, ${this.value2}, ${this.value3}, ${this.getAlpha()})`;
                    }
                    getAlpha() {
                        return parseInt(this.value4) * .01;
                    }
                    setHSLA(value, source, skip = null) {
                        this.setValues([
                            Math.round(value.h),
                            Math.round(value.s * 100),
                            Math.round(value.l * 100),
                            Math.round(value.a * 100)
                        ], source, skip);
                        this.value1Node.prop("disabled", value.l == 0 || value.s == 0);
                        this.slide1Node.prop("disabled", value.l == 0 || value.s == 0);
                        this.value2Node.prop("disabled", value.l == 0);
                        this.slide2Node.prop("disabled", value.l == 0);
                        this.setOpacity(this.value1Node);
                        this.setOpacity(this.slide1Node);
                        this.setOpacity(this.value2Node);
                        this.setOpacity(this.slide2Node);
                    }
                    setRGBA(value, source, skip = null) {
                        this.setValues([
                            Math.round(value.r),
                            Math.round(value.g),
                            Math.round(value.b),
                            Math.round(value.a * 100)
                        ], source, skip);
                    }
                    getValueNode(id) {
                        return this.node.find(`input[role=value][data-id=${id}]`);
                    }
                    getSlideNode(id) {
                        return this.node.find(`input[role=slide][data-id=${id}]`);
                    }
                    setValues(values, source, skip = null) {
                        for (let i = 0; i < 4; i++) {
                            if (source != "value" || skip != i) {
                                this[`value${i + 1}`] = values[i].toString();
                            }
                        }
                        for (let i = 0; i < 4; i++) {
                            if (source != "slide" || skip != i) {
                                this[`slide${i + 1}`] = values[i].toString();
                            }
                        }
                    }
                    setOpacity(node) {
                        node.prop("disabled") === true ?
                            node.css({ opacity: .3 }) :
                            node.css({ opacity: 1 });
                    }
                }
                Controls.ColorPanelCustomValues = ColorPanelCustomValues;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ColorPanelThemes extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get color() {
                        return this.state.get("color");
                    }
                    get dblclickCallback() {
                        return this.state.get("dblclick", () => { });
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get search() {
                        return this.m_search;
                    }
                    set search(value) {
                        this.m_search = value;
                    }
                    get targetTheme() {
                        return this.state.get("targetTheme");
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    hide() {
                        this.node.hide();
                    }
                    show() {
                        this.node.show();
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-colors-dialog-list">
                        <div class="-pdjs-shared-ui-controls-colors-dialog-list-filter"></div>
                        <div class="-pdjs-shared-ui-controls-colors-dialog-list-control"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.search_init();
                        this.list_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (PDJS.Shared.Colors.Color.isThemeColor(this.color)) {
                            this.list.select(this.color);
                        }
                    }
                    list_init() {
                        this.list = new PDJS.Shared.UI.Controls.ThemeColorsList({
                            insertAt: ".-pdjs-shared-ui-controls-colors-dialog-list-control",
                            targetTheme: this.targetTheme,
                            height: "100%",
                            dblclick: (e) => {
                                this.dblclickCallback({
                                    color: e.color
                                });
                            },
                            change: (e) => {
                                this.value = e.color;
                            }
                        });
                        this.controls.add(this.list);
                    }
                    search_init() {
                        this.search = new PDJS.Shared.UI.Controls.SearchBox({
                            insertAt: ".-pdjs-shared-ui-controls-colors-dialog-list-filter",
                            defaultMaskText: "Filter colors...",
                            onSearch: (e) => {
                                this.m_list.filter(e.term);
                            }
                        });
                        this.controls.add(this.search);
                    }
                }
                Controls.ColorPanelThemes = ColorPanelThemes;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxButton extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get mode() {
                        return this.state.get("mode");
                    }
                    get onShowDialogCallback() {
                        return this.state.get("onShowDialog", () => { });
                    }
                    get onShowListCallback() {
                        return this.state.get("onShowList", () => { });
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    template() {
                        return `<button role="${this.mode == Controls.ComboBoxMode.List ? "list" : "dialog"}">
                        <span></span>
                    </button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            width: "21px",
                            bottom: 0,
                            boxSizing: "border-box",
                            padding: 0
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let isList = this.mode === Controls.ComboBoxMode.List;
                        let span = this.node.children("span");
                        span.removeClass("icofont-simple-down");
                        span.empty();
                        isList ?
                            span.addClass("icofont-simple-down") :
                            span.text("...");
                        this.node.css({
                            cursor: this.enabled ? "pointer" : "default",
                            fontFamily: isList ? "IcoFont" : "inherit",
                            backgroundColor: isList ? "transparent" : null,
                            borderWidth: isList ? "0" : "1px",
                            fontSize: "16px"
                        });
                        if (this.visible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                        this.enableClickHandlers(this.enabled);
                        this.node.attr("tabIndex", this.tabIndex);
                    }
                    enableClickHandlers(enabled) {
                        this.node.prop("disabled", !this.enabled);
                        if (this.enabled) {
                            if (this.mode == Controls.ComboBoxMode.List) {
                                this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.onShowListCallback, this));
                            }
                            else {
                                this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.onShowDialogCallback, this));
                            }
                        }
                        else {
                            this.node.off(Jade.BrowserEvent.CLICK);
                        }
                    }
                }
                Controls.ComboBoxButton = ComboBoxButton;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxDataSourceFilterEvent {
                    constructor(options) {
                        this.m_term = options.term;
                        this.m_result = new Jade.Collection();
                        this.m_callback = options.callback;
                    }
                    get term() {
                        return this.m_term;
                    }
                    get result() {
                        return this.m_result;
                    }
                    complete() {
                        if (_.isFunction(this.m_callback)) {
                            this.m_callback(this.result);
                        }
                    }
                }
                Controls.ComboBoxDataSourceFilterEvent = ComboBoxDataSourceFilterEvent;
                class ComboBoxDataSource extends Jade.ObservableCollection {
                    constructor(options) {
                        super(options.data, {
                            onAfterAdd: (e) => {
                                this.onChangeCallback(this);
                            },
                            onAfterRemove: (e) => {
                                this.onChangeCallback(this);
                            }
                        });
                        this.m_key = options.key;
                    }
                    get key() {
                        return this.m_key || "id";
                    }
                    get label() {
                        return this.m_label || "label";
                    }
                    get onChangeCallback() {
                        return this.m_onChange || (() => { });
                    }
                    set onChangeCallback(value) {
                        this.m_onChange = value;
                    }
                    get onFilterCallback() {
                        return this.m_onFilter || (() => { });
                    }
                    set onFilterCallback(value) {
                        this.m_onFilter = value;
                    }
                    onFilter(e) {
                        if (this.m_throttledFilterFunction == null) {
                            this.m_throttledFilterFunction =
                                _.throttle(_.bind((e) => { this.onFilterCallback(e); }, this), 500);
                        }
                        this.m_throttledFilterFunction(e);
                    }
                    filter(term) {
                        let args = new ComboBoxDataSourceFilterEvent({
                            term: term,
                            callback: (data) => {
                                this.onChangeCallback(data);
                            }
                        });
                        this.onFilter(args);
                    }
                    bind() {
                        this.onChangeCallback(this);
                    }
                }
                Controls.ComboBoxDataSource = ComboBoxDataSource;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxEvent {
                    constructor(options) {
                        this.m_comboBox = options.comboBox;
                    }
                    get comboBox() {
                        return this.m_comboBox;
                    }
                }
                Controls.ComboBoxEvent = ComboBoxEvent;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxIcon extends Jade.UI.Control {
                    constructor(options) {
                        super(options || {});
                    }
                    get path() {
                        return this.state.get("path");
                    }
                    set path(value) {
                        this.state.set("path", value);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get title() {
                        return this.state.get("title", "");
                    }
                    set title(value) {
                        this.state.set("title", value);
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    template() {
                        return `<div role="icon">&nbsp;</div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            width: "21px",
                            bottom: 0,
                            backgroundPosition: "5px center",
                            backgroundRepeat: "no-repeat",
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.setIconPath();
                        let isVisible = !Jade.String.isNullOrWhiteSpace(this.path) && this.visible;
                        if (isVisible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                        this.node.attr("title", this.title);
                    }
                    setIconPath() {
                        if (Jade.String.isNullOrWhiteSpace(this.path)) {
                            this.node.css({
                                backgroundImage: ""
                            });
                            return;
                        }
                        let path;
                        if (!Jade.Path.isVirtual(this.path)) {
                            path = Jade.IconSet.get("pd").resolve(this.path, Jade.IconSetSizeSpecificDirectory.x16);
                        }
                        this.node.css({
                            backgroundImage: `url(${path})`
                        });
                    }
                }
                Controls.ComboBoxIcon = ComboBoxIcon;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let ComboBoxInputEventSource;
                (function (ComboBoxInputEventSource) {
                    ComboBoxInputEventSource[ComboBoxInputEventSource["mask"] = 0] = "mask";
                    ComboBoxInputEventSource[ComboBoxInputEventSource["text"] = 1] = "text";
                })(ComboBoxInputEventSource = Controls.ComboBoxInputEventSource || (Controls.ComboBoxInputEventSource = {}));
                class ComboBoxInputEvent extends Controls.ComboBoxEvent {
                    constructor(options) {
                        super(options);
                        this.m_event = options.event;
                        this.m_eventType = options.eventType;
                        this.m_source = options.source;
                    }
                    get input() {
                        return this.comboBox.input;
                    }
                    get list() {
                        return this.comboBox.list;
                    }
                    get source() {
                        return this.m_source;
                    }
                    get event() {
                        return this.m_event;
                    }
                    get eventType() {
                        return this.m_eventType;
                    }
                    get isFilterKey() {
                        return [
                            Jade.KeyCode.Enter,
                            Jade.KeyCode.Tab,
                            Jade.KeyCode.Home,
                            Jade.KeyCode.End,
                            Jade.KeyCode.ArrowLeft,
                            Jade.KeyCode.ArrowUp,
                            Jade.KeyCode.ArrowRight,
                            Jade.KeyCode.ArrowDown,
                            Jade.KeyCode.Shift
                        ].indexOf(this.keyCode) == -1;
                    }
                    get isNavigateUpCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.KEYDOWN)
                            && this.isKeyCode(Jade.KeyCode.ArrowUp);
                    }
                    get isNavigateDownCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.KEYDOWN)
                            && this.isKeyCode(Jade.KeyCode.ArrowDown);
                    }
                    get isSelectCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.KEYUP)
                            && this.isKeyCode(Jade.KeyCode.Enter)
                            && this.comboBox.list.visible;
                    }
                    get isDeleteCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.KEYUP)
                            && this.isKeyCode(Jade.KeyCode.Backspace, Jade.KeyCode.Delete);
                    }
                    get isFilterCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.KEYUP)
                            && this.isFilterKey;
                    }
                    get isTabOutCommand() {
                        return (this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.KEYDOWN)
                            || this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.KEYDOWN))
                            && this.isKeyCode(Jade.KeyCode.Tab)
                            && this.comboBox.list.visible;
                    }
                    get isShowListCommand() {
                        return this.source === ComboBoxInputEventSource.mask
                            && this.eventType === Jade.BrowserEvent.KEYDOWN
                            && this.isKeyCode(Jade.KeyCode.ArrowUp, Jade.KeyCode.ArrowDown, Jade.KeyCode.Space);
                    }
                    get isSwitchToTextCommand() {
                        return this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.KEYDOWN)
                            && !this.isKeyCode(Jade.KeyCode.Backspace, Jade.KeyCode.Delete, Jade.KeyCode.Shift)
                            && !this.isShowListCommand
                            && !this.isTabOutCommand
                            && !this.isKeyCode(Jade.KeyCode.Tab, Jade.KeyCode.Enter);
                    }
                    get isMaskIgnoreEnterKey() {
                        return this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.KEYPRESS)
                            && this.isKeyCode(Jade.KeyCode.Enter)
                            && this.comboBox.list.visible;
                    }
                    get isMaskDoubleClick() {
                        return this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.DOUBLECLICK);
                    }
                    get isTextBlur() {
                        return this.isSourceEventType(ComboBoxInputEventSource.text, Jade.BrowserEvent.BLUR);
                    }
                    get isMaskFocus() {
                        return this.isSourceEventType(ComboBoxInputEventSource.mask, Jade.BrowserEvent.FOCUS);
                    }
                    get keyCode() {
                        return this.event.which;
                    }
                    get filterTerm() {
                        return this.input.textValue;
                    }
                    get hasFilterTerm() {
                        return !Jade.String.isNullOrWhiteSpace(this.filterTerm);
                    }
                    execute() {
                        switch (true) {
                            case this.isTextBlur:
                                this.comboBox.showMask();
                                this.input.textValue = "";
                                break;
                            case this.isMaskDoubleClick:
                                this.comboBox.showList();
                                break;
                            case this.isDeleteCommand:
                                this.event.stopPropagation();
                                this.comboBox.selection = null;
                                this.comboBox.focusMask();
                                this.comboBox.data.filter(this.filterTerm);
                                this.comboBox.hideList();
                                break;
                            case this.isSelectCommand:
                                this.event.preventDefault();
                                this.event.stopPropagation();
                                this.list.selectActiveItem();
                                this.comboBox.showMask();
                                this.comboBox.focusMask();
                                this.comboBox.hideList();
                                break;
                            case this.isSwitchToTextCommand:
                                this.comboBox.showList();
                                this.comboBox.showText();
                                this.comboBox.focusText();
                                break;
                            case this.isFilterCommand:
                                if (this.hasFilterTerm) {
                                    this.comboBox.showList();
                                }
                                else {
                                    this.comboBox.hideList();
                                }
                                this.comboBox.data.filter(this.filterTerm);
                                break;
                            case this.isNavigateUpCommand:
                                this.comboBox.showList();
                                this.list.navigateUp();
                                break;
                            case this.isNavigateDownCommand:
                                this.comboBox.showList();
                                this.list.navigateDown();
                                break;
                            case this.isShowListCommand:
                                this.comboBox.showList();
                                this.comboBox.showText();
                                this.comboBox.focusText();
                                this.comboBox.data.filter(this.filterTerm);
                                this.event.returnValue = false;
                                break;
                            case this.isTabOutCommand:
                                this.input.textValue = "";
                                this.comboBox.showMask();
                                this.comboBox.hideList();
                                break;
                            case this.isMaskIgnoreEnterKey:
                                this.event.stopPropagation();
                                break;
                        }
                    }
                    isKeyCode(...keyCodes) {
                        return keyCodes.indexOf(this.keyCode) > -1;
                    }
                    isSourceEventType(source, eventType) {
                        return this.source === source && this.eventType === eventType;
                    }
                }
                Controls.ComboBoxInputEvent = ComboBoxInputEvent;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ComboBoxList extends Controls.PopUp {
                    constructor(options) {
                        super(options);
                        this.ITEM_SELECTOR = "div[data-role=item]";
                        this.m_comboBox = options.comboBox;
                        this.state.unset("comboBox");
                    }
                    get comboBox() {
                        return this.m_comboBox;
                    }
                    get activeItem() {
                        return this.m_activeItem;
                    }
                    set activeItem(value) {
                        this.m_activeItem = value;
                    }
                    get items() {
                        return this.controls.getByType(Controls.ComboBoxListItem);
                    }
                    get message() {
                        return this.controls.getByType(Controls.Message).first();
                    }
                    destroy() {
                        this.hide();
                        super.destroy();
                    }
                    toggle() {
                        if (this.visible) {
                            this.hide();
                        }
                        else {
                            this.show();
                        }
                    }
                    hide() {
                        super.hide();
                    }
                    show() {
                        if (!this.visible) {
                            this.comboBox.data.bind();
                        }
                        this.node.css({
                            width: `${this.comboBox.node.outerWidth(true) - 2}px`
                        });
                        super.show();
                    }
                    clear() {
                        this.activeItem = null;
                        this.controls.clear();
                    }
                    navigateUp() {
                        let items = this.items;
                        let prev = this.activeItem;
                        let nextIndex = null;
                        let result = null;
                        if (items.count > 0) {
                            if (prev == null) {
                                result = items.first();
                            }
                            else {
                                nextIndex = this.items.indexOf(prev) - 1;
                                if (nextIndex >= 0) {
                                    result = items.item(nextIndex);
                                }
                                else {
                                    result = items.last();
                                }
                            }
                        }
                        if (result != null) {
                            this.setActiveItem(result);
                        }
                        return result;
                    }
                    navigateDown() {
                        let items = this.items;
                        let prev = this.activeItem;
                        let nextIndex = null;
                        let result = null;
                        if (items.count > 0) {
                            if (prev == null) {
                                result = items.first();
                            }
                            else {
                                nextIndex = items.indexOf(prev) + 1;
                                if (nextIndex < items.count) {
                                    result = items.item(nextIndex);
                                }
                                else {
                                    result = items.first();
                                }
                            }
                        }
                        if (result != null) {
                            this.setActiveItem(result);
                        }
                        return result;
                    }
                    selectActiveItem() {
                        if (this.activeItem != null) {
                            this.comboBox.selection = this.activeItem.data;
                        }
                        else {
                            this.comboBox.selection = null;
                        }
                    }
                    resize(height) {
                        if (this.node.length > 0) {
                            let tpdTooltip = this.node.closest(".tpd-tooltip");
                            tpdTooltip.height(height);
                            let tpdSkin = tpdTooltip.children(".tpd-skin");
                            tpdSkin.height(height);
                            tpdSkin.find(".tpd-frames, .tpd-frame, .tpd-background-shadow, .tpd-background, .tpd-background-border-hack").height(height);
                            tpdSkin.find(".tpd-backgrounds").height(height + 2);
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, this.ITEM_SELECTOR, (e) => {
                            let selectedListItem = this.controls.getById($(e.currentTarget).attr("id"));
                            if (selectedListItem != null) {
                                this.selectActiveItem();
                                this.hide();
                            }
                        });
                        this.node.on(Jade.BrowserEvent.MOUSEENTER, this.ITEM_SELECTOR, (e) => {
                            let activeListItem = this.controls.getById($(e.currentTarget).attr("id"));
                            this.setActiveItem(activeListItem);
                        });
                        this.node.on(Jade.BrowserEvent.MOUSELEAVE, this.ITEM_SELECTOR, (e) => {
                            let activeListItem = this.controls.getById($(e.currentTarget).attr("id"));
                            this.setActiveItem(activeListItem);
                        });
                        this.node.css({
                            overflowY: "auto",
                            backgroundColor: "var(--visiv-theme-input-back-color)"
                        });
                    }
                    showMessage(text) {
                        if (this.message != null) {
                            this.message.message = text;
                        }
                        this.controls.add(new Controls.Message({
                            message: text
                        }));
                    }
                    setActiveItem(item) {
                        this.node.find(`.${Controls.CssClass.ACTIVE}`).removeClass(Controls.CssClass.ACTIVE);
                        if (item != null) {
                            item.node.addClass(Controls.CssClass.ACTIVE);
                        }
                        this.activeItem = item;
                    }
                    getPopUpOptions() {
                        return _.extend(super.getPopUpOptions(), {
                            skin: "themed",
                            position: "bottomright",
                            offset: { x: 0, y: 1 },
                            afterHide: () => {
                                this.m_activeItem = null;
                            }
                        });
                    }
                }
                Controls.ComboBoxList = ComboBoxList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class CommandButton extends Controls.Button {
                    constructor(options) {
                        super(options);
                    }
                    get commandId() {
                        return this.state.get("commandId");
                    }
                    get commander() {
                        return this.m_commander;
                    }
                    set commander(value) {
                        this.m_commander = value;
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    getResolvedIcon() {
                        return this.commander.getResolvedIcon();
                    }
                    getTooltip() {
                        return this.commander.tooltip;
                    }
                    isIconVisible() {
                        return this.commander.isIconVisible;
                    }
                    isLabelVisible() {
                        return this.commander.isLabelVisible;
                    }
                    onClick(e) {
                        super.onClick(e);
                        this.hideTooltip();
                        if (this.commander && this.commander.enabled && this.commander.visible) {
                            this.commander.execute(this.value);
                        }
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.node.attr("command", this.commandId);
                        this.onPropertiesChanged();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.commander = new UI.ControlCommander({
                            commandId: this.commandId,
                            change: () => {
                                this.onPropertiesChanged();
                            }
                        });
                    }
                    onPropertiesChanged() {
                        this.icon = this.commander.icon;
                        this.label = this.commander.label;
                        this.enabled = this.commander.enabled;
                        this.checked = this.commander.checked;
                        this.visible = this.commander.visible;
                        this.node.attr("command-id", this.commander.commandUid);
                        super.onPropertiesChanged();
                    }
                }
                Controls.CommandButton = CommandButton;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContentPageHeader extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get title() {
                        return this.state.get("title");
                    }
                    set title(value) {
                        this.state.set("title", value);
                    }
                    get subTitle() {
                        return this.state.get("subTitle");
                    }
                    set subTitle(value) {
                        this.state.set("subTitle", value);
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    set icon(value) {
                        this.state.set("icon", value);
                    }
                    get titleNode() {
                        return this.node.find("div[role=title]");
                    }
                    get subTitleNode() {
                        return this.node.find("span[role=sub-title]");
                    }
                    get iconNode() {
                        return this.node.find("img[role=icon]");
                    }
                    template() {
                        return `
            <div class="-pdjs-explorer-content-header">
                <div>
                    <img role="icon" src="${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x32)}"/>
                </div>
                <div role="title">${this.title}</div>
                <div>
                    <span role="sub-title">
                        ${this.subTitle}
                    </span>
                </div>
            </div>
            `;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.titleNode.empty();
                        this.titleNode.html(this.title);
                        this.subTitleNode.empty();
                        Jade.String.isNullOrWhiteSpace(this.subTitle) ?
                            this.subTitleNode.html("No Description") :
                            this.subTitleNode.html(this.subTitle);
                        let iconPath = Jade.IconSet.get("pd")
                            .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x32);
                        this.iconNode.attr("src", iconPath);
                    }
                }
                Controls.ContentPageHeader = ContentPageHeader;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenu extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get anchor() {
                        this.ensureAnchor();
                        return this.m_anchor;
                    }
                    set anchor(value) {
                        this.m_anchor = value;
                    }
                    get createdCallback() {
                        return this.state.get("created", () => { });
                    }
                    get height() {
                        return this.state.get("height");
                    }
                    get isMenuCreated() {
                        return this.m_isMenuCreated;
                    }
                    set isMenuCreated(value) {
                        this.m_isMenuCreated = value;
                    }
                    get items() {
                        return this.controls.getByType(Controls.ContextMenuItemBase).toArray();
                    }
                    get options() {
                        return this.state.get("options");
                    }
                    get rightClick() {
                        return this.state.get("rightClick", {});
                    }
                    get segments() {
                        return this.state.get("segments", []);
                    }
                    get selectCallback() {
                        return this.state.get("select", () => { });
                    }
                    get showCallback() {
                        return this.state.get("show", () => { return {}; });
                    }
                    get width() {
                        return this.state.get("width");
                    }
                    hide() {
                        PDJS.Shared.PopOver.hide(this.anchor);
                    }
                    show() {
                        this.ensureMenu();
                        PDJS.Shared.PopOver.show(this.anchor);
                    }
                    template() {
                        return `<div class="-pdjs-context-menu"></div>`;
                    }
                    getDefaultMenuOptions() {
                        return _.merge({
                            onShow: (content, element) => {
                                this.segments.forEach(segment => {
                                    segment.show({
                                        data: this.showCallback({ target: $(PDJS.Shared.PopOver.findElement(this.node.get(0))) })
                                    });
                                });
                                PDJS.Shared.PopOver.refresh(this.node.get(0));
                            }
                        }, this.options);
                    }
                    onActivate(e) {
                        var _a;
                        super.onActivate(e);
                        this.node.css({
                            display: "none",
                            height: this.height,
                            width: this.width
                        });
                        this.segments.forEach(segment => {
                            segment.mount({
                                menu: this,
                                select: (item) => {
                                    this.selectCallback(item);
                                }
                            });
                        });
                        if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.showOn) != null || this.rightClick != null) {
                            this.show();
                            this.hide();
                        }
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        setTimeout(() => {
                            this.rightClick_init();
                        }, 250);
                    }
                    onDestroy(e) {
                        PDJS.Shared.PopOver.remove(this.anchor);
                        super.onDestroy(e);
                    }
                    onMenuCreated() {
                        this.createdCallback();
                    }
                    ensureAnchor() {
                        if (this.m_anchor == null) {
                            this.m_anchor = this.state.get("anchor");
                            this.state.unset("anchor");
                        }
                    }
                    ensureMenu() {
                        if (!this.isMenuCreated) {
                            this.node.detach();
                            PDJS.Shared.PopOver.menu(this.anchor, this.node, this.getDefaultMenuOptions());
                            this.segments.forEach(segment => {
                                segment.onAddMenuItems(new Controls.ContextMenuAddItemsEventArgs({
                                    menu: this,
                                    segment: segment,
                                    select: this.selectCallback
                                }));
                            });
                            this.node.show();
                            this.onMenuCreated();
                            this.isMenuCreated = true;
                        }
                    }
                    rightClick_init() {
                        let container = this.rightClickContainer();
                        if (container == null) {
                            return;
                        }
                        container.on("contextmenu", this.rightClick.target, (e) => {
                            if (e.which === 3) {
                                e.returnValue = false;
                                e.preventDefault();
                                this.rightClickRender($(e.currentTarget));
                            }
                        });
                    }
                    rightClickContainer() {
                        var _a;
                        let container = (_a = this.rightClick) === null || _a === void 0 ? void 0 : _a.container;
                        if (container == null) {
                            return;
                        }
                        switch (true) {
                            case _.isString(container):
                                return $(container);
                            case container instanceof jQuery:
                                return container;
                            case container instanceof Element:
                                return $(container);
                        }
                    }
                    rightClickRender(target) {
                        this.node.detach();
                        let anchorElement = PDJS.Shared.PopOver.findElement(this.node.get(0));
                        PDJS.Shared.PopOver.remove(this.anchor);
                        PDJS.Shared.PopOver.remove(anchorElement);
                        this.anchor = target;
                        PDJS.Shared.PopOver.menu(this.anchor, this.node, this.getDefaultMenuOptions());
                        this.node.show();
                        this.onMenuCreated();
                        this.isMenuCreated = true;
                        PDJS.Shared.PopOver.show(this.anchor);
                    }
                }
                Controls.ContextMenu = ContextMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuAddItemsEventArgs {
                    constructor(options) {
                        this.m_menu = options.menu;
                        this.m_segment = options.segment;
                        this.m_selectCallback = options.select || ((e) => { });
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    get segment() {
                        return this.m_segment;
                    }
                    get selectCallback() {
                        return this.m_selectCallback;
                    }
                    addItem(item) {
                        item.mount({
                            menu: this.menu,
                            select: this.selectCallback
                        });
                        this.menu.controls.add(item);
                    }
                    addSeparator(options = {}) {
                        let item = new Controls.ContextMenuSeparator(options);
                        item.mount({
                            menu: this.menu
                        });
                        this.menu.controls.add(item);
                    }
                }
                Controls.ContextMenuAddItemsEventArgs = ContextMenuAddItemsEventArgs;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuItem extends Controls.ContextMenuItemBase {
                    constructor(options) {
                        super(options);
                    }
                    get contentNode() {
                        return this.node.children(".-pdjs-context-menu-item");
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    set icon(value) {
                        this.state.set("icon", value);
                    }
                    get iconSet() {
                        return this.state.get("iconSet", "pd");
                    }
                    set iconSet(value) {
                        this.state.set("iconSet", value);
                    }
                    get iconNode() {
                        return this.contentNode
                            .children("div[role=icon]");
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get labelNode() {
                        return this.contentNode
                            .children("div[role=label]");
                    }
                    get select() {
                        return this.state.get("select", (() => { }));
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-context-menu-item">
                    <div role="gap"></div>
                    <div role="icon"></div>
                    <div role="gap"></div>
                    <div role="label">${this.label}</div>
                    <div role="shortcut"></div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.insertImage();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.enabled ?
                            this.node.removeClass("-pdjs-disabled") :
                            this.node.addClass("-pdjs-disabled");
                        this.visible ?
                            this.node.removeClass("-pdjs-hidden") :
                            this.node.addClass("-pdjs-hidden");
                        if (this.state.hasChanged("icon")) {
                            this.insertImage();
                        }
                        if (this.state.hasChanged("label")) {
                            this.labelNode.text(this.label);
                        }
                    }
                    insertImage() {
                        if (Jade.String.isNullOrWhiteSpace(this.icon)) {
                            return;
                        }
                        let icon = Jade.IconSet.get(this.iconSet).resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16);
                        this.iconNode.empty();
                        this.iconNode.append(`<img src="${Jade.Path.resolve(icon)}" />`);
                    }
                }
                Controls.ContextMenuItem = ContextMenuItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuItemCollection {
                    constructor(options) {
                        this.m_menu = options.menu;
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    get items() {
                        return this.m_menu;
                    }
                    each() {
                    }
                }
                Controls.ContextMenuItemCollection = ContextMenuItemCollection;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ContextMenuSeparator extends Jade.UI.Control {
                    constructor(options = {}) {
                        super(options);
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    set menu(value) {
                        this.m_menu = value;
                    }
                    get showCallback() {
                        return this.state.get("show");
                    }
                    get visible() {
                        return this.state.get("visible", true);
                    }
                    set visible(value) {
                        this.state.set("visible", value);
                    }
                    show() {
                        if (this.showCallback != null) {
                            this.showCallback({
                                item: this
                            });
                            this.onStateChanged();
                            return;
                        }
                    }
                    mount(args) {
                        this.menu = args.menu;
                    }
                    template() {
                        return `<div class="-pdjs-context-menu-separator">
                        <div role="gap"></div>
                        <div role="gap"></div>
                        <div role="gap"></div>
                        <div role="label">
                            <div role="divider"></div>
                        </div>
                    </div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.visible ?
                            this.node.removeClass("-pdjs-hidden") :
                            this.node.addClass("-pdjs-hidden");
                    }
                }
                Controls.ContextMenuSeparator = ContextMenuSeparator;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class LoadingMessageControl extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-base-1-back-color)");
                    }
                    get foregroundColor() {
                        return this.state.get("foregroundColor", "var(--visiv-theme-base-1-text-color)");
                    }
                    get message() {
                        return this.state.get("message", null);
                    }
                    set message(value) {
                        this.state.set("message", value);
                    }
                    get margin() {
                        return this.state.get("margin", 0);
                    }
                    get showLoadingIcon() {
                        return this.state.get("showLoadingIcon", true);
                    }
                    template() {
                        return `<div></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            display: "flex",
                            position: "absolute",
                            inset: 0,
                            margin: `${this.margin}px`,
                            backgroundColor: this.backgroundColor,
                            justifyContent: "center",
                            alignItems: "center"
                        });
                        let content = PDJS.Shared.Spinner.toHtml({
                            size: 36,
                            color: this.foregroundColor,
                            text: this.message
                        });
                        this.node.append(content);
                    }
                }
                Controls.LoadingMessageControl = LoadingMessageControl;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class SearchBox extends Controls.MaskedTextBox {
                    constructor(options) {
                        super(options);
                        this.defaultMaskText = options.defaultMaskText || "Search...";
                    }
                    get buttonNode() {
                        return this.node.find("button[role=search]");
                    }
                    get onBlurCallback() {
                        return this.state.get("onBlur", () => { });
                    }
                    get onFocusCallback() {
                        return this.state.get("onFocus", () => { });
                    }
                    get onSearchCallback() {
                        return this.state.get("onSearch", () => { });
                    }
                    get searchOnEnter() {
                        return this.state.get("searchOnEnter", true);
                    }
                    clear() {
                        this.m_searchSubmitted = false;
                        this.textValue = "";
                        this.showMask();
                        this.focusMask();
                        this.buttonMode(false);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.append(`<button role="search"><i class="icofont-search-1"></i></button>`);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.searchButton_onClick, this));
                        this.buttonNode.css({
                            position: "absolute",
                            top: "4px",
                            right: "4px",
                            height: "16px",
                            width: "16px",
                            minHeight: "16px",
                            maxHeight: "16px",
                            minWidth: "16px",
                            maxWidth: "16px",
                            padding: 0,
                            border: "0 none transparent",
                            background: "none",
                            backgroundColor: "transparent",
                            fontFamily: "IcoFont",
                            fontSize: "12px"
                        });
                    }
                    onMaskFocus(e) {
                        this.showText();
                        this.focusText();
                    }
                    onTextFocus(e) {
                        this.onFocusCallback();
                    }
                    onTextBlur(e) {
                        this.onBlurCallback();
                        if (Jade.String.isNullOrWhiteSpace(this.textValue)) {
                            this.textValue = "";
                            this.buttonMode(false);
                            this.showMask();
                        }
                    }
                    onTextKeyPress(e) {
                        if (e.keyCode == UI.KeyCodes.Return && this.searchOnEnter) {
                            if (!Jade.String.isNullOrWhiteSpace(this.textValue)) {
                                this.submitSearch(e);
                            }
                            else {
                                this.clearSearch(e);
                            }
                        }
                    }
                    onTextKeyUp(e) {
                        if (this.searchOnEnter === false) {
                            if (!Jade.String.isNullOrWhiteSpace(this.textValue)) {
                                this.submitSearch(e);
                            }
                            else {
                                this.clearSearch(e);
                            }
                            return;
                        }
                        this.preventEventBubbling(e);
                    }
                    submitSearch(e) {
                        this.preventEventBubbling(e);
                        this.m_searchSubmitted = true;
                        this.m_searchSubmittedTerm = this.textValue;
                        this.buttonMode(true);
                        this.onSearchCallback({
                            term: this.textValue
                        });
                    }
                    clearSearch(e) {
                        this.preventEventBubbling(e);
                        this.m_searchSubmitted = false;
                        this.textValue = "";
                        this.showMask();
                        this.focusMask();
                        this.buttonMode(false);
                        this.onSearchCallback({
                            term: this.textValue
                        });
                    }
                    searchButton_onClick(e) {
                        if (this.m_searchSubmitted || Jade.String.isNullOrWhiteSpace(this.textValue)) {
                            this.clearSearch(e);
                        }
                        else {
                            this.submitSearch(e);
                        }
                    }
                    preventEventBubbling(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        e.cancelBubble = true;
                        e.returnValue = false;
                    }
                    buttonMode(isSearchMode) {
                        let icoFontNode = this.buttonNode.children("i");
                        icoFontNode.removeClass("icofont-close");
                        icoFontNode.removeClass("icofont-search-1");
                        isSearchMode ?
                            icoFontNode.addClass("icofont-close") :
                            icoFontNode.addClass("icofont-search-1");
                        icoFontNode.css({
                            fontSize: isSearchMode ? "16px" : "12px"
                        });
                    }
                }
                Controls.SearchBox = SearchBox;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class DateTextBox extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_popUp = null;
                    }
                    get popUp() {
                        return this.m_popUp;
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    set format(value) {
                        this.state.get("format", value);
                    }
                    get defaultMask() {
                        return this.state.get("defaultMask", "");
                    }
                    get mask() {
                        return this.maskNode.val();
                    }
                    set mask(value) {
                        this.maskNode.val(value);
                    }
                    get value() {
                        return this.inputNode.val();
                    }
                    set value(value) {
                        this.inputNode.val(value);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get inputNode() {
                        return this.node.find("input[role=text]");
                    }
                    get buttonNode() {
                        return this.node.find("input[type=button]");
                    }
                    get maskNode() {
                        return this.node.find("input[role=mask]");
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    get onChangeCallback() {
                        return this.state.get("onChange", (e) => { });
                    }
                    input_onBlur(e) {
                        this.onChangeCallback({ isValid: this.isValid(), value: this.value });
                        this.setValue(this.value);
                        this.maskNode.show();
                        this.setDefaultMask();
                        this.inputNode.removeClass(PDJS.Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                    input_onFocus(e) {
                        this.maskNode.hide();
                        this.inputNode.addClass(PDJS.Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                    mask_onFocus(e) {
                        this.maskNode.hide();
                        this.inputNode.focus();
                        this.inputNode.select();
                    }
                    button_onClick(e) {
                        this.popUp.show();
                    }
                    onActivate(e) {
                        this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.input_onBlur, this));
                        this.inputNode.on(Jade.BrowserEvent.FOCUS, _.bind(this.input_onFocus, this));
                        this.inputNode.on(Jade.BrowserEvent.DOUBLECLICK, () => {
                            this.popUp.show();
                        });
                        this.maskNode.on(Jade.BrowserEvent.FOCUS, _.bind(this.mask_onFocus, this));
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.button_onClick, this));
                        this.setValue(this.value);
                        this.setDefaultMask();
                        this.m_popUp = new Controls.PopUpCalendar({
                            skin: "themed",
                            anchor: this.buttonNode,
                            height: 204,
                            width: 200,
                            position: {
                                target: "bottomright",
                                tooltip: "topright"
                            },
                            offsetX: 4,
                            offsetY: 4,
                            onChange: (e) => {
                                this.onChangeCallback({ isValid: this.isValid(), value: e.formattedValue });
                                this.setValue(e.formattedValue);
                                this.setDefaultMask();
                                this.popUp.hide();
                            }
                        });
                        this.controls.add(this.popUp);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.maskNode.prop("disabled", !this.enabled);
                        this.inputNode.prop("disabled", !this.enabled);
                        this.buttonNode.prop("disabled", !this.enabled);
                        if (!this.enabled) {
                            this.node.addClass(Shared.UI.CssClass.Disabled);
                        }
                        else {
                            this.node.removeClass(Shared.UI.CssClass.Disabled);
                        }
                        this.maskNode.attr("tabIndex", this.tabIndex);
                        this.inputNode.attr("tabIndex", this.tabIndex);
                        this.buttonNode.attr("tabIndex", this.tabIndex);
                    }
                    destroy() {
                        if (this.popUp != null) {
                            this.popUp.destroy();
                        }
                        super.destroy();
                    }
                    isValid() {
                        let result = true;
                        let regex = /^((0|1)?\d{1})\/((0|1|2|3)?\d{1})\/((19|20)\d{2})$/g;
                        if (!this.isNull()) {
                            result = regex.test(this.value);
                        }
                        return result;
                    }
                    getValue() {
                        let result = null;
                        if (!this.isNull()) {
                            result = kendo.parseDate(this.value);
                        }
                        return result;
                    }
                    setValue(value) {
                        this.value = value;
                        if (this.isValid()) {
                            this.maskNode.val(kendo.toString(kendo.parseDate(this.value), this.format));
                        }
                        else {
                            this.maskNode.val(value || "");
                        }
                    }
                    template() {
                        return `<div class="-pd-date-textbox">   
                        <input
                            type="text"
                            role="text"
                            class="${PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget}"
                            style="height:22px;" />
                        <input 
                            type="text" 
                            role="mask"
                            readonly
                            class="${PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget}"
                            style="height:22px;" />
                        <input 
                            type="button" 
                            value="..." tabIndex="0" />
                    </div>`;
                    }
                    setFormat(format) {
                        this.format = format;
                        this.maskNode.val(kendo.toString(kendo.parseDate(this.value), this.format));
                    }
                    isNull() {
                        return Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    setDefaultMask() {
                        let hasNoValue = Jade.String.isNullOrWhiteSpace(this.value);
                        if (hasNoValue) {
                            this.mask = this.defaultMask;
                        }
                        hasNoValue ?
                            this.maskNode.addClass("-pdjs-no-value") :
                            this.maskNode.removeClass("-pdjs-no-value");
                    }
                }
                Controls.DateTextBox = DateTextBox;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PopUpCalendar extends Controls.PopUp {
                    constructor(options) {
                        super(options);
                        this.m_resized = false;
                    }
                    get value() {
                        return this.state.get("value", null);
                    }
                    get calendar() {
                        return this.calendarNode.data("kendoCalendar");
                    }
                    get calendarNode() {
                        return this.node.find("[role=calendar]");
                    }
                    get onChangeCallback() {
                        return this.state.get("onChange", () => { });
                    }
                    popUp_onCreate() {
                        this.calendarNode.kendoCalendar({
                            change: (e) => {
                                this.onChangeCallback({
                                    value: this.calendar.value(),
                                    formattedValue: kendo.toString(this.calendar.value(), "M/d/yyyy")
                                });
                            }
                        });
                        if (this.value != null) {
                            this.setValue(this.value);
                        }
                        this.addIcoFontPagerIcons();
                    }
                    getPopUpOptions() {
                        return _.extend(super.getPopUpOptions(), {
                            skin: "themed",
                            position: "bottomright",
                            offset: { x: 4, y: 3 },
                            hideAfter: 500,
                            hideDelay: 500,
                            hideOn: false,
                        });
                    }
                    show() {
                        super.show();
                        if (this.m_resized !== true) {
                            this.m_resized = true;
                            let container = PDJS.Shared.PopOver.get(this.anchor.get(0));
                            $(container.tooltips[0].content).parent().css({
                                height: "204px"
                            });
                            this.hide();
                            super.show();
                        }
                    }
                    template() {
                        return `<div class="-pdjs-control-popup-calendar">
                        <div role="calendar" style="height:${this.height}px;width:${this.width}px;"></div>
                    </div>`;
                    }
                    setValue(value) {
                        this.calendar.value(value);
                    }
                    addIcoFontPagerIcons() {
                        let pageEastIcon = this.calendarNode.find(".k-header .k-i-arrow-e");
                        let pageWestIcon = this.calendarNode.find(".k-header .k-i-arrow-w");
                        pageEastIcon.append(`<i class="icofont-caret-right"></i>`);
                        pageWestIcon.append(`<i class="icofont-caret-left"></i>`);
                    }
                }
                Controls.PopUpCalendar = PopUpCalendar;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class GridColumnFormat {
                    static Date(column, format) {
                        let fixedLocalDate = null;
                        if (column != null) {
                            fixedLocalDate = this.getFixedLocalDate(column);
                            return kendo.toString(fixedLocalDate, format);
                        }
                        return "";
                    }
                    static Icon(value, virtualDirectory) {
                        var result = "";
                        if (value != null) {
                            value.indexOf("~") === 0 ?
                                result = `<img src="${Jade.Path.resolve(value)}"/><br/>` :
                                result = `<img src="/${virtualDirectory}/application/icons/16x16/${value}"/><br/>`;
                        }
                        return result;
                    }
                    static BytesToUnits(column) {
                        return Jade.Convert.BytesToUnits(column);
                    }
                    static getFixedLocalDate(time) {
                        let matches = null;
                        let result = new Date(time);
                        if (time != null) {
                            matches = GridColumnFormat.DATE_EXTRACTION_REGEX.exec(time);
                            result.setFullYear(matches[1], matches[2] - 1, matches[3]);
                            result.setHours(matches[4], matches[5], matches[6]);
                        }
                        return result;
                    }
                    ;
                    static Tags(column, data) {
                        let result = column;
                        if (column != null) {
                            column = column.split(", ");
                            column = column.map((i) => {
                                return `<div class="-visiv-rule-script-tag-${i}">${i}</div>`;
                            });
                            result = column.join(" ");
                        }
                        return result !== null && result !== void 0 ? result : "";
                    }
                }
                GridColumnFormat.DATE_EXTRACTION_REGEX = new RegExp("([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})");
                Controls.GridColumnFormat = GridColumnFormat;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class GridContextMenu extends Jade.UI.ContextMenu {
                    constructor(options) {
                        super({
                            target: `div[id=${options.grid.get_id()}]`,
                            container: `div[id=${options.grid.get_id()}]`,
                            filter: `TR[role=row][data-uid] td[role=gridcell]:not(.-pd-noevent)`,
                            segments: options.segments
                        });
                    }
                }
                Controls.GridContextMenu = GridContextMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let ListViewSelectMode;
                (function (ListViewSelectMode) {
                    ListViewSelectMode["none"] = "none";
                    ListViewSelectMode["single"] = "single";
                    ListViewSelectMode["multiple"] = "multiple";
                })(ListViewSelectMode = Controls.ListViewSelectMode || (Controls.ListViewSelectMode = {}));
                class ListViewBase extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get binding() {
                        return this.state.get("binding", {
                            icon: "icon",
                            label: "label",
                            value: "value"
                        });
                    }
                    set binding(value) {
                        this.state.set("binding", value);
                    }
                    get items() {
                        return new Controls.ListViewItemCollectionBase({
                            list: this,
                            items: this.controls
                        });
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", false);
                    }
                    set showCheckboxes(value) {
                        this.state.set("showCheckboxes", value);
                    }
                    get selected() {
                        return this.items.selected;
                    }
                    get checked() {
                        return this.items.checked;
                    }
                    get allowRemove() {
                        return this.state.get("allowRemove", false);
                    }
                    get checkOnSelect() {
                        return this.state.set("checkOnSelect", false);
                    }
                    get data() {
                        return this.state.get("data", []);
                    }
                    get height() {
                        return this.state.get("height");
                    }
                    get iconSet() {
                        return this.state.get("iconSet");
                    }
                    get noItemsMessage() {
                        return this.state.get("noItemsMessage", "No items in list.");
                    }
                    get selectMode() {
                        return this.state.get("selectMode", ListViewSelectMode.single);
                    }
                    get selectOnCheck() {
                        return this.state.set("selectOnCheck", false);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get removeCallback() {
                        return this.state.get("remove", () => { });
                    }
                    get dblClickCallback() {
                        return this.state.get("dblClick", () => { });
                    }
                    get createItemCallback() {
                        return this.state.get("createItem", (item) => {
                            return new Controls.ListViewItem(item);
                        });
                    }
                    filter(comparer) {
                        this.items.each((item) => {
                            item.visible = comparer(item);
                        });
                        let hasSearchResults = this.items.filter(item => {
                            return item.visible;
                        }).count > 0;
                        if (!hasSearchResults) {
                            this.addNoItemsMessage();
                        }
                    }
                    template() {
                        return `<div class="-pdjs-list-view"></div>`;
                    }
                    select(ids, options) {
                        this.items
                            .each((item) => {
                            item.selected = ids.indexOf(item.data.value) > -1;
                        });
                        if ((options === null || options === void 0 ? void 0 : options.silent) !== false) {
                            this.invokeChangeCallback();
                        }
                    }
                    selectAll() {
                        this.items
                            .each((item) => {
                            item.selected = true;
                        });
                        this.invokeChangeCallback();
                    }
                    deselectAll() {
                        this.items
                            .each((item) => {
                            item.selected = false;
                        });
                        this.invokeChangeCallback();
                    }
                    checkAll() {
                        this.items
                            .each((item) => {
                            item.checked = true;
                        });
                        this.invokeChangeCallback();
                    }
                    uncheckAll() {
                        this.items
                            .each((item) => {
                            item.checked = false;
                        });
                        this.invokeChangeCallback();
                    }
                    removeAll(silent = false) {
                        this.controls.clear();
                        if (this.items.count == 0) {
                            this.addNoItemsMessage();
                        }
                        if (!silent) {
                            this.invokeChangeCallback();
                        }
                    }
                    removeSelected() {
                        let items = [];
                        this.items.each(item => {
                            if (item.selected) {
                                items.push(item);
                            }
                        });
                        items.forEach(item => {
                            this.controls.remove(item);
                        });
                        this.invokeChangeCallback();
                        if (this.items.count == 0) {
                            this.addNoItemsMessage();
                        }
                    }
                    refresh() {
                        this.controls.clear();
                        this.node.hide();
                        this.data.forEach((item) => {
                            this.createItem({
                                data: item
                            });
                        });
                        this.node.show();
                        this.invokeChangeCallback();
                    }
                    addItem(item) {
                        this.removeMessage();
                        let control = this.createItem({
                            data: item
                        });
                        return control;
                    }
                    removeItem(value) {
                        let items = this.items
                            .filter(i => i.data.value == value).toArray();
                        let invokeChange = false;
                        items.forEach(item => {
                            this.controls.remove(item);
                            this.removeCallback(item);
                            invokeChange === false && item.selected ?
                                invokeChange = true : null;
                        });
                        if (invokeChange) {
                            this.invokeChangeCallback();
                        }
                        if (this.items.count == 0) {
                            this.addNoItemsMessage();
                        }
                    }
                    scrollIntoView(value) {
                        let item = this.items.getItemByValue(value);
                        if (item == null) {
                            return;
                        }
                        item.node.get(0).scrollIntoView();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.data.length > 0) {
                            this.refresh();
                        }
                        this.node.addClass(PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget);
                        this.node.on(Jade.BrowserEvent.DOUBLECLICK, ".-pdjs-list-view-item-base", (e) => {
                            this.dblClickCallback(this.selected);
                        });
                        this.height != null ?
                            this.node.css({ height: this.height }) :
                            this.node.attr("data-minimal", "true");
                        if (this.items.count == 0) {
                            this.addNoItemsMessage();
                        }
                    }
                    removeMessage() {
                        let message = this.controls
                            .getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message != null) {
                            this.controls.remove(message);
                        }
                    }
                    addMessage(text) {
                        let message = new PDJS.Shared.UI.Controls.Message({
                            message: text
                        });
                        this.removeMessage();
                        this.controls.add(message);
                        message.messageNode.css({
                            color: "var(--visiv-theme-base-3-text-color)"
                        });
                    }
                    addNoItemsMessage() {
                        if (_.isFunction(this.noItemsMessage)) {
                            this.addMessage(this.noItemsMessage());
                        }
                        else {
                            this.addMessage(this.noItemsMessage);
                        }
                    }
                    invokeChangeCallback() {
                        this.changeCallback(this.selected);
                    }
                    createItem(item) {
                        item = _.extend({
                            removeVisible: this.allowRemove,
                            checkVisible: this.showCheckboxes,
                            binding: this.binding
                        }, item);
                        let control = this.createItemCallback(item);
                        if (control != null) {
                            control.state.set({
                                iconSet: this.iconSet,
                                showCheckbox: this.showCheckboxes,
                                tabIndex: this.tabIndex,
                                selectMode: this.selectMode,
                                checkOnSelect: this.checkOnSelect,
                                selectOnCheck: this.selectOnCheck,
                                remove: (e) => {
                                    this.removeItem(e.data.value);
                                },
                                select: (e, isMultiSelect) => {
                                    this.item_select(e, isMultiSelect);
                                },
                                check: (e) => {
                                    this.item_check(e);
                                }
                            });
                            this.controls.add(control);
                        }
                        return control;
                    }
                    item_select(e, isCtrlKey) {
                        let isMultipleSelect = this.selectMode == ListViewSelectMode.multiple;
                        let isSingleSelect = this.selectMode == ListViewSelectMode.single;
                        this.items.each(item => {
                            let isTargetItem = item.value == e.data.value;
                            if (isMultipleSelect && isCtrlKey && isTargetItem) {
                                item.selected = !item.selected;
                            }
                            if (isSingleSelect || (isMultipleSelect && !isCtrlKey)) {
                                item.selected = isTargetItem;
                            }
                        });
                        this.invokeChangeCallback();
                    }
                    item_check(e) {
                        this.invokeChangeCallback();
                    }
                }
                Controls.ListViewBase = ListViewBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListView extends Controls.ListViewBase {
                }
                Controls.ListView = ListView;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListViewContextMenu extends Jade.UI.ContextMenu {
                    constructor(options) {
                        let root = `div[id="${options.list.ID}"]`;
                        super({
                            container: root,
                            filter: `${root} ${options.filter}`,
                            segments: options.segments,
                            show: options.show,
                            close: options.close
                        });
                        this.m_list = options.list;
                    }
                    get list() {
                        return this.m_list;
                    }
                    get discriminatorId() {
                        return this.state.get("discriminatorId");
                    }
                    get showCallback() {
                        return this.state.get("show", () => { });
                    }
                    onOpen(e) {
                        super.onOpen(e);
                        this.list.items.each((item) => {
                            if (item.ID == e.target.id) {
                                this.showCallback(item);
                            }
                        });
                    }
                }
                Controls.ListViewContextMenu = ListViewContextMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListViewItemCollectionBase extends Jade.Collection {
                    constructor(options) {
                        super([]);
                        this.m_list = options.list;
                        if (options.items != null) {
                            options.items.getByType(Controls.ListViewItemBase)
                                .each(item => {
                                this.add(item);
                            });
                        }
                    }
                    get list() {
                        return this.m_list;
                    }
                    set list(value) {
                        this.m_list = value;
                    }
                    get selected() {
                        return this.getSelected();
                    }
                    get checked() {
                        return this.getChecked();
                    }
                    filter(fn) {
                        let result = new ListViewItemCollectionBase({
                            list: this.list
                        });
                        this.each(item => {
                            fn(item) ? result.add(item) : null;
                        });
                        return result;
                    }
                    getItemByValue(value) {
                        let result = null;
                        this.each(item => {
                            if (item.data.value == value) {
                                result = item;
                            }
                        });
                        return result;
                    }
                    getItemById(id) {
                        let result = null;
                        this.each(item => {
                            if (item.ID == id) {
                                result = item;
                            }
                        });
                        return result;
                    }
                    getSelected() {
                        let result = new ListViewItemCollectionBase({
                            list: this.list
                        });
                        ;
                        this.each(item => {
                            item.selected ?
                                result.add(item) : null;
                        });
                        return result;
                    }
                    getChecked() {
                        let result = new ListViewItemCollectionBase({
                            list: this.list
                        });
                        ;
                        this.each(item => {
                            item.checked ?
                                result.add(item) : null;
                        });
                        return result;
                    }
                }
                Controls.ListViewItemCollectionBase = ListViewItemCollectionBase;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ListViewItemData extends PDJS.Core.Model {
                    constructor(options) {
                        super(options);
                    }
                    get binding() {
                        return this.state.get("$binding", {
                            value: "value",
                            label: "label",
                            icon: "icon"
                        });
                    }
                    get iconSet() {
                        return this.state.get("$iconSet");
                    }
                    get icon() {
                        return this.getUsingBinding("icon");
                    }
                    get label() {
                        return this.getUsingBinding("label");
                    }
                    get state() {
                        return super.state;
                    }
                    get value() {
                        return this.getUsingBinding("value");
                    }
                    get(name, defaultValue = null) {
                        return this.getUsingBinding(name, defaultValue);
                    }
                    set(name, value) {
                        return this.setUsingBinding(name, value);
                    }
                    toJSON() {
                        let result = super.toJSON();
                        delete result["$binding"];
                        delete result["$iconSet"];
                        delete result["$stateChanged"];
                        return result;
                    }
                    getUsingBinding(name, defaultValue = null) {
                        return this.binding != null && this.binding[name] != null ?
                            this.state.get(this.binding[name]) :
                            this.state.get(name, defaultValue);
                    }
                    setUsingBinding(name, value = null) {
                        return this.binding != null && this.binding[name] != null ?
                            this.state.set(this.binding[name], value) :
                            this.state.set(name, value);
                    }
                }
                Controls.ListViewItemData = ListViewItemData;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class MultiSelect extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get items() {
                        let result = new Jade.Collection();
                        this.controls.each((control) => {
                            if (control instanceof Controls.MultiSelectItem) {
                                result.add(control);
                            }
                        });
                        return result;
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get onItemCheckedCallback() {
                        return this.state.get("onItemChecked", () => { });
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CHANGE, "label input[type=checkbox]", _.bind(this.item_onChecked, this));
                    }
                    onStateChanged() {
                        if (this.node) {
                            this.node.prop("disabled", !this.enabled);
                        }
                        this.items.each((item) => {
                            item.enabled = this.enabled;
                            item.tabIndex = this.tabIndex;
                        });
                    }
                    focus() {
                        let item = this.items.first();
                        if (item != null) {
                            item.focus();
                        }
                    }
                    template() {
                        return `<div class="-pdjs-control-msl"></div>`;
                    }
                    item_onChecked(e) {
                        let controlId = $(e.target).parent().attr("id");
                        let control = this.controls.getById(controlId);
                        if (control != null && control instanceof Controls.MultiSelectItem) {
                            this.onItemCheckedCallback({
                                itemId: control.itemId,
                                checked: control.checked,
                                item: control
                            });
                        }
                    }
                }
                Controls.MultiSelect = MultiSelect;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class MultiSelectItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get itemId() {
                        return this.state.get("itemId");
                    }
                    get icon() {
                        return this.state.get("icon");
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    get checked() {
                        return this.checkBoxNode.is(":checked");
                    }
                    set checked(value) {
                        this.checkBoxNode.prop("checked", value);
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get checkBoxNode() {
                        return this.node.find("input[type=checkbox]");
                    }
                    get labeNode() {
                        return this.node.find("span");
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    focus() {
                        this.checkBoxNode.focus();
                    }
                    template() {
                        if (this.icon != null) {
                            let url = Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16);
                            return `<label role="item">
                            <input type="checkbox" data-id="${this.itemId}" tabIndex="${this.tabIndex}" />
                            <span style="background-image:url(${url});">${this.label}</span>
                        </label>`;
                        }
                        return `<label role="item">
                        <input type="checkbox" data-id="${this.itemId}" tabIndex="${this.tabIndex}" />
                        <span style="padding-left:2px;">${this.label}</span>
                    </label>`;
                    }
                    onStateChanged() {
                        if (this.node) {
                            this.node.prop("disabled", !this.enabled);
                            this.checkBoxNode.prop("disabled", !this.enabled);
                            this.checkBoxNode.attr("tabIndex", this.tabIndex);
                            this.labeNode.css({
                                opacity: this.enabled ? 1 : .5
                            });
                        }
                    }
                }
                Controls.MultiSelectItem = MultiSelectItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let NumericTextBoxType;
                (function (NumericTextBoxType) {
                    NumericTextBoxType[NumericTextBoxType["integer"] = 1] = "integer";
                    NumericTextBoxType[NumericTextBoxType["decimal"] = 2] = "decimal";
                })(NumericTextBoxType = Controls.NumericTextBoxType || (Controls.NumericTextBoxType = {}));
                class NumericTextBox extends Controls.MaskedTextBox {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    get numericType() {
                        return this.state.get("numericType");
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", value);
                    }
                    get value() {
                        return this.textNode.val();
                    }
                    set value(value) {
                        this.textNode.val(value);
                    }
                    get onValidateCallback() {
                        return this.state.get("onValidate", (isValid) => { });
                    }
                    input_onBlur(e) {
                        this.onValidateCallback(this.isValid());
                        this.setValue(this.value);
                        this.maskNode.show();
                        this.textNode.removeClass(PDJS.Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                    input_onFocus(e) {
                        this.onValidateCallback(this.isValid());
                        this.maskNode.hide();
                        this.textNode.addClass(PDJS.Canvas.Shared.CanvasCss.FormFieldFocus);
                    }
                    input_onChange(e) {
                        this.changeCallback(this.value);
                    }
                    mask_onFocus(e) {
                        this.onValidateCallback(this.isValid());
                        this.maskNode.hide();
                        this.textNode.focus();
                        this.textNode.select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.textNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.input_onChange, this));
                        this.textNode.on(Jade.BrowserEvent.BLUR, _.bind(this.input_onBlur, this));
                        this.textNode.on(Jade.BrowserEvent.FOCUS, _.bind(this.input_onFocus, this));
                        this.maskNode.on(Jade.BrowserEvent.FOCUS, _.bind(this.mask_onFocus, this));
                        this.setValue(this.value);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.maskNode.prop("disabled", !this.enabled);
                        this.textNode.prop("disabled", !this.enabled);
                        this.maskNode.attr("tabIndex", this.tabIndex);
                        this.textNode.attr("tabIndex", this.tabIndex);
                    }
                    isValid() {
                        let result = true;
                        let regex = null;
                        switch (this.numericType) {
                            case NumericTextBoxType.integer:
                                regex = /^[^a-zA-Z\.]+$/;
                                break;
                            case NumericTextBoxType.decimal:
                                regex = /^[^a-zA-Z]+$/;
                                break;
                        }
                        if (!this.isNull()) {
                            result = regex.test(this.value);
                        }
                        return result;
                    }
                    getValue() {
                        let result = null;
                        if (!this.isNull()) {
                            switch (this.numericType) {
                                case NumericTextBoxType.decimal:
                                    result = this.value;
                                    break;
                                case NumericTextBoxType.integer:
                                    result = this.value;
                                    break;
                            }
                        }
                        return result;
                    }
                    setValue(value) {
                        this.value = value == null ? "" : value;
                        if (this.isValid()) {
                            this.maskNode.val(kendo.toString(kendo.parseFloat(this.value), this.format));
                        }
                        else {
                            this.maskNode.val(this.value);
                        }
                    }
                    isNull() {
                        return this.value == null || this.value == "";
                    }
                }
                Controls.NumericTextBox = NumericTextBox;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuAction extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get description() {
                        return this.state.get("description", "");
                    }
                    get descriptionNode() {
                        return this.node.find("div[role=description]");
                    }
                    get icon() {
                        return this.state.get("icon", null);
                    }
                    get iconSet() {
                        return this.state.get("iconSet", "pd");
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    get labelNode() {
                        return this.node.find("div[role=label]");
                    }
                    get url() {
                        return this.state.get("url", "#");
                    }
                    get hasUrl() {
                        return this.url != "#";
                    }
                    get clickCallback() {
                        return this.state.get("click");
                    }
                    template() {
                        return `<a href="${this.url}" class="-pdjs-ui-panel-menu-action">
                        <div role="label">${this.label}</div>
                        <div role="description">
                            ${this.description}
                        </div>
                    </a>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.hasUrl == false && this.clickCallback != null) {
                            this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                                this.clickCallback(e);
                            });
                        }
                        this.descriptionNode.css({
                            display: Jade.String.isNullOrWhiteSpace(this.description) ? "none" : ""
                        });
                        if (!Jade.String.isNullOrWhiteSpace(this.icon)) {
                            this.node.css({
                                backgroundImage: `url(${Jade.IconSet.get(this.iconSet)
                                    .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x24)})`,
                                paddingLeft: this.icon != null ? "40px" : "10px"
                            });
                        }
                    }
                }
                Controls.PanelMenuAction = PanelMenuAction;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuHeading extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-heading">${this.label}</div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.html(this.label);
                    }
                }
                Controls.PanelMenuHeading = PanelMenuHeading;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                }
                Controls.PanelMenuItem = PanelMenuItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuLabel extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-label">${this.label}</div>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.html(this.label);
                    }
                }
                Controls.PanelMenuLabel = PanelMenuLabel;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuSeperator extends Jade.UI.Control {
                    constructor() {
                        super({});
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-separator"></div>`;
                    }
                }
                Controls.PanelMenuSeperator = PanelMenuSeperator;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuTitle extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-title">${this.label}</div>`;
                    }
                }
                Controls.PanelMenuTitle = PanelMenuTitle;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class Panes extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get startPaneId() {
                        return "start";
                    }
                    get innerPaneId() {
                        return "inner";
                    }
                    get trailPaneId() {
                        return "trail";
                    }
                    get readyCallback() {
                        return "trail";
                    }
                    get splitter() {
                        return this.m_splitter;
                    }
                    set splitter(value) {
                        this.m_splitter = value;
                    }
                    startPaneVisible(visible) {
                        visible ?
                            this.splitter.expand(this.startPaneId) :
                            this.splitter.collapse(this.startPaneId);
                    }
                    innerPaneVisible(visible) {
                        visible ?
                            this.splitter.expand(this.innerPaneId) :
                            this.splitter.collapse(this.innerPaneId);
                    }
                    trailPaneVisible(visible) {
                        visible ?
                            this.splitter.expand(this.trailPaneId) :
                            this.splitter.collapse(this.trailPaneId);
                    }
                    template() {
                        return `
                <div>
                    <div role="start"></div>
                    <div role="inner"></div>
                    <div role="trail"></div>
                </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                }
                Controls.Panes = Panes;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PopUpItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get data() {
                        return this.state.get("data", {});
                    }
                    get uid() {
                        return this.resolveMap(this.uidMap);
                    }
                    get uidMap() {
                        return this.state.get("uidMap", "uid");
                    }
                    get label() {
                        return this.resolveMap(this.labelMap);
                    }
                    get labelMap() {
                        return this.state.get("labelMap", "label");
                    }
                    get icon() {
                        return this.resolveMap(this.iconMap);
                    }
                    get iconMap() {
                        return this.state.get("iconMap", "icon");
                    }
                    get clickCallback() {
                        return this.state.get("click", null);
                    }
                    template() {
                        let result = $(`<div data-role="item" data-id="${this.uid}" title="${this.label}" class="-pdjs-pop-up-item">${this.label}</div>`);
                        if (this.icon != null) {
                            result.css({
                                paddingLeft: "25px",
                                backgroundImage: `url(${Jade.IconSet.get("pd").resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                        }
                        return result;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (_.isFunction(this.clickCallback)) {
                            this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.clickCallback, this));
                        }
                    }
                    resolveMap(id, defaultValue) {
                        return this.state.get(`data.${id}`, defaultValue);
                    }
                }
                Controls.PopUpItem = PopUpItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PopUpTextBox extends Jade.UI.Control {
                    get clearButtonNode() {
                        return this.node.find(".-pdjs-pup-txtbx-btn-clear");
                    }
                    get clearButtonVisible() {
                        return this.clearButtonNode.is(":visible");
                    }
                    set clearButtonVisible(value) {
                        value ? this.clearButtonNode.show()
                            : this.clearButtonNode.hide();
                    }
                    get defaultText() {
                        return this.state.get("defaultText", "");
                    }
                    get defaultTextEnabled() {
                        return !Jade.String.isNullOrWhiteSpace(this.defaultText);
                    }
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    get hasValue() {
                        return !Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    get imageNode() {
                        return this.node.find(".-pdjs-pup-txtbx-img");
                    }
                    get imageVisible() {
                        return this.imageNode.is(":visible");
                    }
                    set imageVisible(value) {
                        value ? this.imageNode.show()
                            : this.imageNode.hide();
                    }
                    get input() {
                        return this.m_input;
                    }
                    get editButtonNode() {
                        return this.node.find(".-pdjs-pup-txtbx-btn-edit");
                    }
                    get editButtonVisible() {
                        return this.editButtonNode.is(":visible");
                    }
                    set editButtonVisible(value) {
                        value ? this.editButtonNode.show()
                            : this.editButtonNode.hide();
                    }
                    get readOnly() {
                        return this.state.get("readOnly", false);
                    }
                    get shouldShowDefaultText() {
                        return this.defaultTextEnabled &&
                            Jade.String.isNullOrWhiteSpace(this.text) &&
                            Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    get text() {
                        return this.state.get("text", "");
                    }
                    set text(value) {
                        this.state.set("text", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.state.get("value", value);
                    }
                    template() {
                        return `<div class="-pdjs-pup-txtbx">
                        <div class="-pdjs-pup-txtbx-img-bx">
                            <img src="" class="-pdjs-pup-txtbx-img" />
                        </div>
                        <div class="-pdjs-pup-txtbx-ctrl-bx" data-controls></div>
                        <div class="-pdjs-pup-txtbx-btns">
                            <div class="-pdjs-pup-txtbx-btns-grid">
                                <button ${this.readOnly ? "disabled" : ""} class="-pdjs-pup-txtbx-btn-clear" title="Clear">
                                    <i class="icofont-close" />
                                </button>
                                <button ${this.readOnly ? "disabled" : ""} class="-pdjs-pup-txtbx-btn-edit" title="Edit">...</button>
                            </div>
                        </div>
                    </div>`;
                    }
                    focus() {
                        this.input.focusText();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.imageVisible = false;
                        this.clearButtonVisible = false;
                        this.clearButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.clearButton_onClick();
                        });
                        this.editButtonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.popupButton_onClick();
                        });
                        this.m_input = this.createInput();
                        this.controls.add(this.m_input);
                        this.input.enabled = this.enabled;
                        this.refreshUserInterface();
                    }
                    popupButton_onClick() {
                    }
                    clearButton_onClick() {
                        this.clearValueAndText();
                        this.refreshUserInterface();
                    }
                    input_onBlur() {
                    }
                    createInput() {
                        return new PDJS.Shared.UI.Controls.MaskedTextBox({
                            onTextBlur: (e) => {
                                this.input_onBlur();
                            },
                            defaultMaskText: this.defaultText || ""
                        });
                    }
                    refreshUserInterface() {
                        this.input.maskValue = this.text || this.value || this.defaultText || "";
                        this.input.textValue = this.value || "";
                        this.editButtonVisible = this.enabled;
                        this.clearButtonVisible = this.hasValue;
                        this.imageVisible = this.hasValue || this.shouldShowDefaultText;
                        this.setIcon();
                        this.shouldShowDefaultText ?
                            this.input.maskNode.addClass("-pdjs-no-value") :
                            this.input.maskNode.removeClass("-pdjs-no-value");
                        if (Jade.String.isNullOrWhiteSpace(this.imageNode.attr("src"))) {
                            this.imageNode.remove();
                        }
                    }
                    clearValueAndText() {
                        this.text = null;
                        this.value = null;
                        this.input.maskValue = "";
                        this.input.textValue = "";
                    }
                    setIcon() {
                    }
                }
                Controls.PopUpTextBox = PopUpTextBox;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ProgressBar extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "var(--visiv-theme-input-back-color)");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "var(--visiv-theme-input-border-color)");
                    }
                    set borderColor(value) {
                        this.state.set("borderColor", value);
                    }
                    get borderWidth() {
                        return this.state.get("borderWidth", "1px");
                    }
                    set borderWidth(value) {
                        this.state.set("borderWidth", value);
                    }
                    get color() {
                        return this.state.get("color", "var(--visiv-theme-input-text-color)");
                    }
                    set color(value) {
                        this.state.set("color", value);
                    }
                    get height() {
                        return this.state.get("height", "25px");
                    }
                    get width() {
                        return this.state.get("width", "100%");
                    }
                    get showMessage() {
                        return this.state.get("showMessage", false);
                    }
                    get message() {
                        return this.state.get("message", null);
                    }
                    set message(value) {
                        this.state.set("message", value);
                    }
                    get percent() {
                        return this.state.get("percent", null);
                    }
                    set percent(value) {
                        this.state.set("percent", value);
                    }
                    get labelNode() {
                        return this.node.children("div[role=label]");
                    }
                    get barNode() {
                        return this.node.children("div[role=bar]");
                    }
                    template() {
                        return `
            <div class="-pdjs-progress-bar" style="height:${this.height};width:${this.width};">
                <div role="bar">&nbsp;</div>
                <div role="label" style="line-height:${this.height};">Label</div>
            </div>`;
                    }
                    update(args) {
                        if (args.backgroundColor != undefined) {
                            this.backgroundColor = args.backgroundColor;
                        }
                        if (args.color != undefined) {
                            this.color = args.color;
                        }
                        if (args.message != undefined) {
                            this.message = args.message;
                        }
                        if (args.percent != undefined) {
                            this.percent = args.percent;
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.labelNode.html(this.message);
                        this.node.css({
                            backgroundColor: "var(--visiv-theme-input-back-color)",
                            borderColor: this.borderColor,
                            borderWidth: this.borderWidth
                        });
                        this.labelNode.css({
                            color: this.color,
                            backgroundColor: "transparent"
                        });
                        this.barNode.css({
                            width: `${this.percent}%`,
                            color: this.color,
                            backgroundColor: this.backgroundColor
                        });
                    }
                }
                Controls.ProgressBar = ProgressBar;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                ;
                class RichText extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get ace() {
                        return this.m_ace;
                    }
                    get changeCallback() {
                        return this.state.get("change", false);
                    }
                    get content() {
                        return this.state.get("content");
                    }
                    get editorNode() {
                        return this.node.find("div[role=editor]");
                    }
                    get mce() {
                        return this.m_mce;
                    }
                    get mode() {
                        return this.state.get("mode", "html");
                    }
                    get readOnly() {
                        return this.state.get("readOnly");
                    }
                    set readOnly(value) {
                        this.state.set("readOnly", value);
                    }
                    get htmlTheme() {
                        return this.state.get("htmlTheme");
                    }
                    get textStyle() {
                        return this.state.get("textStyle", 0);
                    }
                    get textTheme() {
                        return this.state.get("textTheme");
                    }
                    get view() {
                        return this.state.get("view", "text");
                    }
                    set view(value) {
                        this.state.set("view", value);
                    }
                    get views() {
                        return this.state.get("views");
                    }
                    template() {
                        return `<div class="-pdjs-rich-text">
                        <div role="editors"></div>
                    </div>`;
                    }
                    destroy() {
                        super.destroy();
                        if (this.ace != null) {
                            this.ace.destroy();
                        }
                        if (this.mce != null) {
                            this.mce.destroy();
                        }
                        this.observer_destroy();
                    }
                    switchToHtml() {
                        this.view = "html";
                        this.ace.visible = true;
                        this.mce.visible = false;
                        this.ace.value = this.mce.value;
                    }
                    switchToText() {
                        this.view = "text";
                        this.ace.visible = false;
                        this.mce.visible = true;
                        this.mce.value = this.ace.value;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.mce_init();
                        this.ace_init();
                        this.observer_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.view == "text" ?
                            this.switchToText() :
                            this.switchToHtml();
                        this.ace.value = this.content;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let editorsExist = this.ace != null && this.mce != null;
                        if (!editorsExist) {
                            return;
                        }
                        this.ace.readOnly = this.readOnly;
                        this.mce.readOnly = this.readOnly;
                    }
                    ace_init() {
                        this.m_ace = new Controls.RichTextAce({
                            insertAt: "div[role=editors]",
                            content: this.content,
                            mode: this.mode,
                            theme: this.htmlTheme,
                            switch: () => {
                                this.switchToText();
                            },
                            change: (e) => {
                                this.mce.value = e.value;
                                this.changeCallback(e);
                            }
                        });
                        this.controls.add(this.m_ace);
                    }
                    mce_init() {
                        this.m_mce = new Controls.RichTextMce({
                            insertAt: "div[role=editors]",
                            content: this.content,
                            theme: this.textTheme,
                            style: this.textStyle,
                            views: this.views,
                            switch: () => {
                                this.switchToHtml();
                            },
                            change: (e) => {
                                this.ace.value = e.value;
                                this.changeCallback(e);
                            }
                        });
                        this.controls.add(this.m_mce);
                    }
                    observer_init() {
                        this.m_observer = new ResizeObserver(() => {
                            this.ace != null ? this.ace.resize() : null;
                            this.mce != null ? this.mce.resize() : null;
                        });
                        this.m_observer.observe(this.node.get(0));
                    }
                    observer_destroy() {
                        if (this.m_observer != null) {
                            this.m_observer.unobserve(this.node.get(0));
                        }
                    }
                }
                Controls.RichText = RichText;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class RichTextAce extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", false);
                    }
                    get content() {
                        return this.state.get("content");
                    }
                    get editor() {
                        return this.m_editor;
                    }
                    get mode() {
                        return this.state.get("mode");
                    }
                    get readOnly() {
                        return this.state.get("readOnly", false);
                    }
                    set readOnly(value) {
                        this.state.set("readOnly", value);
                    }
                    get switchCallback() {
                        return this.state.get("switch", false);
                    }
                    get theme() {
                        return this.state.get("theme");
                    }
                    get toggleButtonNode() {
                        return this.node.find("button[role=switch]");
                    }
                    get value() {
                        return this.editor.value;
                    }
                    set value(value) {
                        this.editor.value = value;
                    }
                    get visible() {
                        return this.node.is(":visible");
                    }
                    set visible(value) {
                        value ? this.node.show() :
                            this.node.hide();
                    }
                    template() {
                        return `<div class="-pdjs-rich-text-ace">
                        <div class="-pdjs-rich-text-ace-body">
                            <div class="-pdjs-rich-text-ace-toolbar">
                                <button role="switch" title="Show Text"><i class="icofont-arrow-left"></i></button>
                            </div>
                            <div class="-pdjs-rich-text-ace-editor"></div>
                        </div>
                    </div>`;
                    }
                    resize() {
                        if (this.editor != null) {
                            this.editor.resize();
                        }
                    }
                    destroy() {
                        super.destroy();
                        if (this.editor != null) {
                            this.editor.destroy();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.editor_init();
                        this.toggleButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.switchCallback();
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.editor.readOnly = this.readOnly;
                    }
                    editor_init() {
                        this.m_editor = new Shared.Ace.AceEditor({
                            insertAt: ".-pdjs-rich-text-ace-editor",
                            mode: this.mode,
                            readOnly: this.readOnly,
                            theme: this.getAceTheme(),
                            change: (e) => {
                                this.changeCallback(e);
                            }
                        });
                        this.controls.add(this.m_editor);
                    }
                    getAceTheme() {
                        switch (this.theme) {
                            case "hub":
                                return PDJS.Application.profile.themes.hubEditor;
                            case "manage":
                                return PDJS.Application.profile.themes.manageEditor;
                            default:
                                return "ace/theme/chrome";
                        }
                    }
                }
                Controls.RichTextAce = RichTextAce;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class RichTextMce extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", false);
                    }
                    get content() {
                        return this.state.get("content");
                    }
                    get editor() {
                        return this.m_editor;
                    }
                    set editor(value) {
                        this.m_editor = value;
                    }
                    get readOnly() {
                        return this.state.get("readOnly", false);
                    }
                    set readOnly(value) {
                        this.state.set("readOnly", value);
                    }
                    get readyCallback() {
                        return this.state.get("ready", () => { });
                    }
                    get switchCallback() {
                        return this.state.get("switch", () => { });
                    }
                    get theme() {
                        return this.state.get("theme", "none");
                    }
                    get style() {
                        return this.state.get("style", 0);
                    }
                    get value() {
                        return this.editor.value;
                    }
                    set value(value) {
                        this.editor.value = value;
                    }
                    get views() {
                        return this.state.get("views");
                    }
                    get visible() {
                        return this.node.is(":visible");
                    }
                    set visible(value) {
                        value ? this.node.show() :
                            this.node.hide();
                        this.editor.resize();
                    }
                    template() {
                        return `<div class="-pdjs-rich-text-mce"></div>`;
                    }
                    resize() {
                        this.editor.resize();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.editor_init();
                    }
                    editor_init() {
                        this.editor = new PDJS.Shared.Mce.MceEditor({
                            change: this.changeCallback,
                            theme: this.theme,
                            style: this.style,
                            setup: (e) => {
                                this.addSwitchToHtmlButton(e.mce);
                            },
                            ready: (e) => {
                                if (this.content != null) {
                                    e.mce.setContent(this.content);
                                    e.mce.undoManager.clear();
                                }
                                this.m_editor.mce.focus();
                            }
                        });
                        this.controls.add(this.editor);
                    }
                    addSwitchToHtmlButton(editor) {
                        if (this.views == "both") {
                            editor.addButton("source", {
                                text: "</>",
                                tooltip: "Show HTML",
                                onclick: () => {
                                    this.switchCallback();
                                }
                            });
                        }
                    }
                }
                Controls.RichTextMce = RichTextMce;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class SingleSelectList extends Controls.ComboBoxOf {
                    constructor(options) {
                        super(options);
                    }
                    onSelectionChange(selection) {
                        super.onSelectionChange(selection);
                        if (this.selection != null) {
                            let item = this.onCreateListItemCallback(selection);
                            this.iconValue = item.icon;
                            this.maskValue = item.label;
                        }
                    }
                    createListItem(data) {
                        return new Controls.SingleSelectListItem({
                            data: data,
                            uidMap: "id",
                            labelMap: "label",
                            iconMap: "icon"
                        });
                    }
                    onFilter(e) {
                        if (!Jade.String.isNullOrWhiteSpace(e.term)) {
                            this.data.each((item) => {
                                if (item["label"].toLowerCase().indexOf(e.term.toLowerCase()) > -1) {
                                    e.result.add(item);
                                }
                            });
                        }
                        else {
                            e.result.insertRange(this.data.toArray());
                        }
                        e.complete();
                    }
                }
                Controls.SingleSelectList = SingleSelectList;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class SingleSelectListField extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get label() {
                        return this.state.get("label");
                    }
                    set label(value) {
                        this.state.set("label", value);
                    }
                    get labelNode() {
                        return this.node.find("div[role=label]");
                    }
                    get width() {
                        return this.state.get("width");
                    }
                    set width(value) {
                        this.state.set("width", value);
                    }
                    get input() {
                        return this.m_input;
                    }
                    get onValueChangedCallback() {
                        return this.state.get("onValueChanged", () => { });
                    }
                    get items() {
                        return this.state.get("items");
                    }
                    template() {
                        return `
                <div style="position:relative;height:50px;">
                    <div role="label" style="height:26px;position:absolute;top:0;right:0;left:0;font-family:arial;font-size:12px;line-height:26px;">${this.label}:</div>
                    <div role="input" style="height:24px;position:absolute;top:26px;right:0;left:0;" data-controls></div>
                </div>
            `;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_input = new Controls.SingleSelectList({
                            insertAt: "div[role=input]",
                            data: this.items,
                            onSelectionChanged: (e) => {
                                let item = this.input.selection;
                                if (item != null) {
                                    this.onValueChangedCallback({
                                        id: item.uid,
                                        label: item.label,
                                        icon: item.icon
                                    });
                                }
                                else {
                                    this.onValueChangedCallback(null);
                                }
                            }
                        });
                        this.controls.add(this.input);
                    }
                }
                Controls.SingleSelectListField = SingleSelectListField;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripItemBinding extends PDJS.Shared.UI.StateBinding {
                    get icon() {
                        return this.getValue("icon");
                    }
                    get text() {
                        return this.getValue("text");
                    }
                    get value() {
                        return this.getValue("value");
                    }
                    getDefaults() {
                        return {
                            icon: "icon",
                            text: "text",
                            value: "value"
                        };
                    }
                }
                Controls.TabStripItemBinding = TabStripItemBinding;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripItemClickEventArgsOf {
                    constructor(item) {
                        this.m_cancel = false;
                        this.m_item = item;
                    }
                    get cancel() {
                        return this.m_cancel;
                    }
                    set cancel(value) {
                        this.m_cancel = value;
                    }
                    get item() {
                        return this.m_item;
                    }
                }
                Controls.TabStripItemClickEventArgsOf = TabStripItemClickEventArgsOf;
                class TabStripItemClickEventArgs extends TabStripItemClickEventArgsOf {
                }
                Controls.TabStripItemClickEventArgs = TabStripItemClickEventArgs;
                class TabStripTabClickEventArgs extends TabStripItemClickEventArgsOf {
                }
                Controls.TabStripTabClickEventArgs = TabStripTabClickEventArgs;
                class TabStripMenuItemClickEventArgs extends TabStripItemClickEventArgsOf {
                }
                Controls.TabStripMenuItemClickEventArgs = TabStripMenuItemClickEventArgs;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripScroller {
                    constructor(options) {
                        this.m_allowScrollButtons = true;
                        this.tabStrip = options.tabStrip;
                        this.changeCallback = options.change;
                        this.allowScrollButtons = options.allowScrollButtons != null ?
                            options.allowScrollButtons : true;
                        this.activate();
                    }
                    get allowScrollButtons() {
                        return this.m_allowScrollButtons;
                    }
                    set allowScrollButtons(value) {
                        this.m_allowScrollButtons = value;
                    }
                    get leftNode() {
                        return this.tabStrip.node.find(".-pdjs-tabstrip-scroll-l");
                    }
                    get leftButtonNode() {
                        return this.leftNode.find(".-pdjs-tabstrip-scroll-button");
                    }
                    get changeCallback() {
                        return this.m_changeCallback || (() => { });
                    }
                    set changeCallback(value) {
                        this.m_changeCallback = value;
                    }
                    get overflowed() {
                        return this.m_overflowed;
                    }
                    set overflowed(value) {
                        this.m_overflowed = value;
                    }
                    get rightNode() {
                        return this.tabStrip.node.find(".-pdjs-tabstrip-scroll-r");
                    }
                    get rightButtonNode() {
                        return this.rightNode.find(".-pdjs-tabstrip-scroll-button");
                    }
                    get tabsNode() {
                        return this.tabStrip.node.find(".-pdjs-tabstrip-tabs");
                    }
                    get tabStrip() {
                        return this.m_tabStrip;
                    }
                    set tabStrip(value) {
                        this.m_tabStrip = value;
                    }
                    activate() {
                        this.leftNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.tabsNode.scrollLeft(this.tabsNode.scrollLeft() - 150);
                        });
                        this.rightNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.tabsNode.scrollLeft(this.tabsNode.scrollLeft() + 150);
                        });
                        this.scrollersVisible(false);
                    }
                    resize() {
                        if (!this.allowScrollButtons) {
                            this.scrollersVisible(false);
                            return;
                        }
                        let isOverflowed = this.calculateOverflow() > 0;
                        if (isOverflowed !== this.overflowed) {
                            this.overflowed = isOverflowed;
                            this.changeCallback(this.overflowed);
                        }
                        this.scrollersVisible(isOverflowed);
                    }
                    scrollToSelectedTab() {
                        setTimeout(() => {
                            let selectedTab = this.tabStrip.tabs.selectedNode;
                            if (selectedTab.length > 0) {
                                selectedTab.parent().scrollLeft(0);
                                selectedTab.parent().scrollLeft(Math.round(selectedTab.position().left));
                            }
                        }, 25);
                    }
                    calculateOverflow() {
                        let contentWidth = 0;
                        let result = 0;
                        this.tabStrip.tabs.all.forEach(tab => {
                            if (tab.visible) {
                                contentWidth += tab.node.outerWidth(true);
                            }
                        });
                        result = contentWidth - this.tabsNode.width();
                        return result > 0 ? result : 0;
                    }
                    scrollersVisible(isOverflowed) {
                        isOverflowed ?
                            this.leftButtonNode.show() :
                            this.leftButtonNode.hide();
                        isOverflowed ?
                            this.rightButtonNode.show() :
                            this.rightButtonNode.hide();
                    }
                }
                Controls.TabStripScroller = TabStripScroller;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripMenuAnchor extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get alwaysVisible() {
                        return this.state.get("alwaysVisible", false);
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    set menu(value) {
                        this.m_menu = value;
                    }
                    get addMenuCallback() {
                        return this.state.get("addMenu", () => { });
                    }
                    get tabStrip() {
                        return this.state.get("$tabStrip");
                    }
                    get iconNode() {
                        return this.node.children("i");
                    }
                    hide() {
                        if (!this.alwaysVisible) {
                            this.node.hide();
                        }
                        this.menu.hide();
                    }
                    show() {
                        this.node.show();
                    }
                    template() {
                        return `<div class="-pdjs-tabstrip-overflow-button" style="display: none;">
                        <i class="icofont-navigation-menu"></i>
                    </div>`;
                    }
                    hideMenu() {
                        this.menu.hide();
                        this.updateIcon();
                    }
                    showMenu() {
                        this.menu.show();
                        this.updateIcon();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.menu.visible ?
                                this.hideMenu() :
                                this.showMenu();
                            this.updateIcon();
                        });
                        this.m_menu = this.addMenuCallback();
                        if (this.alwaysVisible) {
                            this.show();
                        }
                    }
                    updateIcon() {
                        this.iconNode.removeClass("icofont-navigation-menu");
                        this.iconNode.removeClass("icofont-close");
                        this.menu.visible ?
                            this.iconNode.addClass("icofont-close") :
                            this.iconNode.addClass("icofont-navigation-menu");
                    }
                }
                Controls.TabStripMenuAnchor = TabStripMenuAnchor;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripMenuItem extends Controls.TabStripMenuItemBase {
                    constructor(options) {
                        super(options);
                    }
                    get iconNode() {
                        return this.gridNode
                            .children("div[role=icon]");
                    }
                    get gridNode() {
                        return this.node
                            .children("div[role=grid]");
                    }
                    get textNode() {
                        return this.gridNode
                            .children("div[role=text]");
                    }
                    template(content) {
                        return super.template(`
                <div role="grid">
                    <div role="icon"></div>
                    <div role="text">${this.binding.text}</div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-pdjs-tabstrip-menu-item");
                        this.binding.icon != null ?
                            this.addImageNode() : null;
                    }
                    addImageNode() {
                        let iconUrl = Jade.IconSet.get("pd")
                            .resolve(this.binding.icon, Jade.IconSetSizeSpecificDirectory.x16);
                        this.iconNode.append(`<img src="${iconUrl}"/>`);
                    }
                }
                Controls.TabStripMenuItem = TabStripMenuItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripTab extends Controls.TabStripTabBase {
                    constructor(options) {
                        super(options);
                    }
                    get iconNode() {
                        return this.gridNode
                            .children("div[role=icon]");
                    }
                    get gridNode() {
                        return this.node
                            .children("div[role=grid]");
                    }
                    get textNode() {
                        return this.gridNode
                            .children("div[role=text]");
                    }
                    get text() {
                        return this.binding.text;
                    }
                    set text(value) {
                        this.binding.setValue("text", value);
                        this.onStateChanged();
                    }
                    template() {
                        return super.template(` 
                <div role="grid">
                    <div role="icon"></div>
                    <div role="text">${this.binding.text}</div>
                </div>`);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.binding.icon != null ?
                            this.addImageNode() : null;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.textNode.html(this.binding.text);
                    }
                    addImageNode() {
                        let iconUrl = Jade.IconSet.get("pd")
                            .resolve(this.binding.icon, Jade.IconSetSizeSpecificDirectory.x16);
                        this.iconNode.append(`<img src="${iconUrl}"/>`);
                    }
                }
                Controls.TabStripTab = TabStripTab;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripTabCollection {
                    constructor(options) {
                        this.m_tabStrip = options.tabStrip;
                    }
                    get node() {
                        return this.m_tabStrip.tabsNode;
                    }
                    get all() {
                        return this.convertNodesToTabs(this.allNodes);
                    }
                    get allNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab");
                    }
                    get hidden() {
                        return this.convertNodesToTabs(this.hiddenNodes);
                    }
                    get hiddenNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab.-pdjs-hidden");
                    }
                    get pinned() {
                        return this.convertNodesToTabs(this.pinnedNodes);
                    }
                    get pinnedNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab.-pdjs-pinned");
                    }
                    get selected() {
                        return _.first(this.convertNodesToTabs(this.selectedNode));
                    }
                    get selectedIsVisible() {
                        return !this.selectedNode.hasClass("-pdjs-hidden");
                    }
                    get selectedNode() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab.-pdjs-selected");
                    }
                    get tabStrip() {
                        return this.m_tabStrip;
                    }
                    get unpinned() {
                        return this.convertNodesToTabs(this.unpinnedNodes);
                    }
                    get unpinnedNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab:not(.-pdjs-pinned)");
                    }
                    get unselected() {
                        return this.convertNodesToTabs(this.unselectedNodes);
                    }
                    get unselectedNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab:not(.-pdjs-pinned)");
                    }
                    get visible() {
                        return this.convertNodesToTabs(this.visibleNodes);
                    }
                    get visibleNodes() {
                        return this.tabStrip.tabsNode.find(".-pdjs-tabstrip-tab:not(.-pdjs-hidden)");
                    }
                    getVisibleBeforeSelected() {
                        let result = [];
                        this.getVisibleNodesBeforeSelected().forEach(node => {
                            let tabs = this.convertNodesToTabs(node);
                            result.push(...tabs);
                        });
                        return result;
                    }
                    getVisibleNodesBeforeSelected() {
                        let result = [];
                        this.selectedNode.prevAll(":not(.-pdjs-hidden)").each((index, element) => {
                            result.push($(element));
                        });
                        return result;
                    }
                    getAfterSelected() {
                        let result = [];
                        this.getNodesAfterSelected().forEach(node => {
                            result.push(...this.convertNodesToTabs(node));
                        });
                        return result;
                    }
                    getNodesAfterSelected() {
                        let result = [];
                        this.selectedNode.nextAll().each((index, element) => {
                            result.push($(element));
                        });
                        return result;
                    }
                    convertNodesToTabs(nodes) {
                        let result = [];
                        nodes.each((index, element) => {
                            let control = this.tabStrip.controls.getById(element.id);
                            if (control instanceof PDJS.Shared.UI.Controls.TabStripTabBase) {
                                result.push(control);
                            }
                        });
                        return result;
                    }
                }
                Controls.TabStripTabCollection = TabStripTabCollection;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                let TagItemType;
                (function (TagItemType) {
                    TagItemType["add"] = "add";
                    TagItemType["remove"] = "remove";
                })(TagItemType = Controls.TagItemType || (Controls.TagItemType = {}));
                class TagEditorBatch extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get allowWildcards() {
                        return this.state.get("allowWildcards", false);
                    }
                    get tagList() {
                        this.ensureTagList();
                        return this.m_tagList;
                    }
                    get emptyMessage() {
                        return this.state.get("emptyMessage", "No tags have been added.");
                    }
                    get height() {
                        return this.state.get("height", "100%");
                    }
                    get width() {
                        return this.state.get("width", "100%");
                    }
                    get items() {
                        return this.controls.getByType(Controls.TagBatchEditorItem)
                            .transform((item) => {
                            return {
                                text: item.tagText,
                                type: item.tagType
                            };
                        });
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-tag-editor-batch"></div>`;
                    }
                    addTag(tags) {
                        let list = this.items;
                        tags.forEach(tag => {
                            this.addItemToList({
                                text: tag,
                                type: TagItemType.add
                            }, list);
                        });
                        this.renderItems(list);
                    }
                    removeTag(tags) {
                        let list = this.items;
                        tags.forEach(tag => {
                            this.addItemToList({
                                text: tag,
                                type: TagItemType.remove
                            }, list);
                        });
                        this.renderItems(list);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            height: this.height,
                            width: this.width
                        });
                        this.renderItems([]);
                    }
                    ensureTagList() {
                        if (this.m_tagList == null) {
                            this.m_tagList = [];
                        }
                    }
                    renderItems(items) {
                        this.controls.getByType(Controls.TagBatchEditorItem).each(item => {
                            this.controls.remove(item);
                        });
                        items = this.sortItems(items);
                        items.forEach(item => {
                            this.controls.add(new Controls.TagBatchEditorItem({
                                allowWildcards: this.allowWildcards,
                                tagText: item.text,
                                tagType: item.type,
                                dblclick: (e) => {
                                    let isAdd = e.item.tagType == TagItemType.add;
                                    PDJS.Manage.Tags.TagsSelectionDialog.open({
                                        title: isAdd ? "Select | Tags to Add" : "Select | Tags to Remove",
                                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                                        select: {
                                            ok: (sender, e2) => {
                                                isAdd ? this.addTag(e2.tags) : this.removeTag(e2.tags);
                                            }
                                        }
                                    });
                                },
                                remove: (e) => {
                                    this.controls.remove(e.item);
                                    this.renderItems(this.items);
                                }
                            }));
                        });
                        items.length == 0 ?
                            this.addMessage(this.emptyMessage) :
                            this.removeMessage();
                    }
                    sortItems(items) {
                        let result = items;
                        result = items.sort((a, b) => {
                            let aValue = `${a.type}-${a.text}`.toLowerCase();
                            let bValue = `${b.type}-${b.text}`.toLowerCase();
                            return aValue.localeCompare(bValue);
                        });
                        return result;
                    }
                    itemExists(item, list) {
                        return list.filter(target => {
                            var _a, _b;
                            return item.type == target.type &&
                                ((_a = item.text) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == ((_b = target.text) === null || _b === void 0 ? void 0 : _b.toLowerCase());
                        }).length > 0;
                    }
                    addItemToList(item, list) {
                        if (this.itemExists(item, list)) {
                            return;
                        }
                        list.push(item);
                    }
                    removeMessage() {
                        let message = this.controls.getByType(Controls.Message).first();
                        if (message) {
                            this.controls.remove(message);
                        }
                    }
                    addMessage(text) {
                        let message = new Controls.Message({
                            message: text,
                            backgroundColor: "var(--visiv-theme-base-3-back-color)",
                            textColor: "var(--visiv-theme-base-3-text-color)",
                        });
                        this.removeMessage();
                        this.controls.add(message);
                    }
                }
                Controls.TagEditorBatch = TagEditorBatch;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TagBatchEditorItem extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_list = options.list;
                        this.state.unset("list");
                    }
                    get allowWildcards() {
                        return this.state.get("allowWildcards", false);
                    }
                    get dblclickCallback() {
                        return this.state.get("dblclick", () => { });
                    }
                    get hasWildcard() {
                        var _a;
                        return ((_a = this.tagText) === null || _a === void 0 ? void 0 : _a.includes("*")) == true;
                    }
                    get removeCallback() {
                        return this.state.get("remove", () => { });
                    }
                    get removeIcon() {
                        return Jade.IconSet.get("pd")
                            .resolve("cancel_white.png", Jade.IconSetSizeSpecificDirectory.misc);
                    }
                    get tagText() {
                        return this.state.get("tagText");
                    }
                    set tagText(value) {
                        this.state.set("tagText", value);
                    }
                    get tagType() {
                        return this.state.get("tagType");
                    }
                    template() {
                        return `<div title="${this.getTitle()}" class="-pdjs-tag-editor-batch-item ${this.getCssClass()}">
                        <span role="text">${this.tagText}</span>
                        <span role="delete">
                            <img src="${this.removeIcon}"/>
                        </span>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.DOUBLECLICK, "[role=text]", (e) => {
                            this.hasWildcard ?
                                this.showTagPatternDialog() :
                                this.dblclickCallback({
                                    item: this,
                                    text: this.tagText
                                });
                        });
                        this.node.on(Jade.BrowserEvent.CLICK, "img", (e) => {
                            this.removeCallback({
                                item: this,
                                text: this.tagText
                            });
                        });
                    }
                    getTitle() {
                        return this.tagType == Controls.TagItemType.add ?
                            `Add ${this.tagText}` : `Remove ${this.tagText}`;
                    }
                    getCssClass() {
                        let prefix = "";
                        switch (this.tagType) {
                            case Controls.TagItemType.add:
                                prefix = "a";
                                break;
                            case Controls.TagItemType.remove:
                                prefix = "r";
                                break;
                        }
                        switch (true) {
                            case this.allowWildcards && this.tagText == "*":
                                return `${prefix}0`;
                            case this.allowWildcards && this.tagText.includes("*"):
                                return `${prefix}1`;
                            case this.allowWildcards:
                                return `${prefix}2`;
                            default:
                                return `${prefix}0`;
                        }
                    }
                    showTagPatternDialog() {
                        PDJS.Manage.Tags.TagPatternDialog.open({
                            pattern: this.tagText,
                            select: {
                                ok: (sender, e) => {
                                    this.tagText = e.newPattern;
                                }
                            }
                        });
                    }
                }
                Controls.TagBatchEditorItem = TagBatchEditorItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class Toolbar extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_observer = null;
                    }
                    get items() {
                        return this.controls.getByType(Controls.ToolbarItem);
                    }
                    get itemsNode() {
                        return this.node.children("div[role=items]");
                    }
                    get segments() {
                        return this.state.get("segments", []);
                    }
                    get overflowNode() {
                        return this.node.children("div[role=overflow]");
                    }
                    get overflow() {
                        return this.m_overflow;
                    }
                    template() {
                        return `<div class="-pdjs-shared-ui-controls-toolbar">
                        <div role="items" data-controls></div>
                        <div role="overflow"></div>
                    </div>`;
                    }
                    onTemplate(e) {
                        super.onTemplate(e);
                        this.addItems();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.addResizeObserver();
                        this.overflow_init();
                    }
                    onResize(e) {
                        let element = this.itemsNode.get(0);
                        let isOverflowed = element.clientWidth < element.scrollWidth ||
                            element.clientHeight < element.scrollHeight;
                        isOverflowed ?
                            this.overflow.show() :
                            this.overflow.hide();
                        let overflowWidth = this.overflowNode.get(0).clientWidth;
                        let widthMax = element.clientWidth - overflowWidth;
                        let widthSum = 0;
                        this.items.each(item => {
                            widthSum += item.node.get(0).clientWidth;
                            item.overflowed = widthMax < widthSum;
                        });
                        isOverflowed = widthMax < widthSum;
                        isOverflowed ?
                            this.overflow.show() :
                            this.overflow.hide();
                        this.overflow.update(this.items);
                    }
                    showOverflowMenu() {
                        this.overflow.showMenu();
                    }
                    hideOverflowMenu() {
                        this.overflow.hideMenu();
                    }
                    addItems() {
                        this.segments.forEach((segment) => {
                            segment.onAddItems(new Controls.ToolbarSegmentEventArgs({
                                toolbar: this,
                                items: this.items,
                                segment: segment
                            }));
                        });
                    }
                    addResizeObserver() {
                        let debounced = _.debounce((e) => {
                            this.onResize(e);
                        }, 250);
                        this.m_observer = new ResizeObserver((e) => {
                            debounced(e);
                        });
                        this.m_observer.observe(this.node.get(0));
                    }
                    overflow_init() {
                        this.m_overflow = new Controls.ToolbarOverflow({
                            insertAt: "div[role=overflow]"
                        });
                        this.controls.add(this.m_overflow);
                    }
                }
                Controls.Toolbar = Toolbar;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarCommandButton extends Controls.ToolbarCommandItem {
                    get iconNode() {
                        return this.contentNode
                            .children("div[role=icon]");
                    }
                    get imageNode() {
                        return this.iconNode.children("img");
                    }
                    get textNode() {
                        return this.contentNode
                            .children("div[role=text]");
                    }
                    createCopy() {
                        let result = new ToolbarCommandButton(this.state.toJSON());
                        result.toolbar = this.toolbar;
                        return result;
                    }
                    content() {
                        return `<button class="-pdjs-shared-ui-controls-toolbar-button">
                        <div role="icon">
                            ${this.resolvedIcon()}
                        </div>
                        <div role="text">${this.commander.label}</div>
                    </button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.toolbar.hideOverflowMenu();
                            this.hideTooltip();
                            if (this.commander && this.commander.enabled && this.commander.visible) {
                                this.commander.execute(this.value);
                            }
                        });
                        this.node.attr("command-id", this.commander.commandUid);
                        this.onPropertiesChanged();
                    }
                    onPropertiesChanged() {
                        super.onPropertiesChanged();
                        let isBigPadding = this.commander.isLabelVisible || this.overflowed;
                        let hasGridGap = (this.commander.isIconVisible
                            && this.commander.isLabelVisible)
                            || this.overflowed;
                        if (this.commander.enabledChanged) {
                            this.commander.enabled ?
                                this.contentNode.removeAttr("disabled") :
                                this.contentNode.attr("disabled", "disabled");
                        }
                        if (this.commander.checkedChanged) {
                            this.commander.checked ?
                                this.contentNode.attr("checked", "checked") :
                                this.contentNode.removeAttr("checked");
                        }
                        if (this.commander.iconChanged) {
                            this.updateIcon();
                        }
                        if (this.commander.displayChanged) {
                            this.setIconVisibility(this.commander.isIconVisible);
                        }
                        if (this.commander.labelChanged || this.overflowedChanged) {
                            this.commander.isLabelVisible || this.overflowed ?
                                this.textNode.html(this.commander.label) :
                                this.textNode.html("");
                        }
                        this.contentNode.css({
                            gridGap: hasGridGap ? "5px" : "0",
                            padding: isBigPadding ? "0 15px" : "0 7px",
                            display: this.commander.visible ? "grid" : "none"
                        });
                    }
                    resolvedIcon() {
                        var _a;
                        let iconPath = (_a = this.commander) === null || _a === void 0 ? void 0 : _a.icon;
                        let result = null;
                        if (PDJS.Shared.IcoFont.isFontPath(iconPath)) {
                            result = PDJS.Shared.IcoFont.convertPathToFont(iconPath);
                            return result;
                        }
                        return `<img src="${this.commander.getResolvedIcon()}" />`;
                    }
                    updateIcon() {
                        this.iconNode.empty();
                        this.iconNode.append(this.resolvedIcon());
                    }
                    setIconVisibility(visible) {
                        visible ?
                            this.iconNode.children().show() :
                            this.iconNode.children().hide();
                    }
                }
                Controls.ToolbarCommandButton = ToolbarCommandButton;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarOverflow extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get anchor() {
                        return this.state.get("anchor");
                    }
                    get imageNode() {
                        return this.node.children("img");
                    }
                    get menu() {
                        return this.m_menu;
                    }
                    set menu(value) {
                        this.m_menu = value;
                    }
                    template() {
                        return `<button style="display:none;">
                        <img src="${Jade.IconSet.get("pdjs").resolve("ellipsis_vertical.png", Jade.IconSetSizeSpecificDirectory.x16)}"/>
                    </button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        this.createMenu();
                    }
                    update(items) {
                        this.createMenu();
                        items.each(item => {
                            if (item.overflowed) {
                                let overflowItem = new Controls.ToolbarOverflowItem({
                                    item: item.createCopy()
                                });
                                this.menu.controls.add(overflowItem);
                            }
                        });
                    }
                    show() {
                        this.node.show();
                    }
                    hide() {
                        this.node.hide();
                    }
                    showMenu() {
                        this.menu.show();
                    }
                    hideMenu() {
                        this.menu.hide();
                    }
                    createMenu() {
                        if (this.menu) {
                            this.menu.destroy();
                            this.menu = null;
                        }
                        this.menu = new Controls.PopUp({
                            anchor: this.node,
                            width: 250,
                            tipped: {
                                skin: "themed",
                                position: {
                                    target: "bottomright",
                                    tooltip: "topright"
                                },
                                offset: {
                                    y: 4,
                                    x: 2
                                }
                            }
                        });
                        this.controls.add(this.menu);
                        this.menu.node.addClass("-pdjs-shared-ui-controls-toolbar-menu");
                    }
                    onClick(e) {
                        this.menu.visible ?
                            this.menu.hide() :
                            this.menu.show();
                    }
                }
                Controls.ToolbarOverflow = ToolbarOverflow;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarOverflowItem extends PDJS.Shared.UI.Controls.PopUpItem {
                    constructor(options) {
                        super(options);
                        this.m_item = options.item;
                        this.state.unset("item");
                    }
                    get item() {
                        return this.m_item;
                    }
                    template() {
                        return `<div></div>`;
                    }
                    onInit(e) {
                        super.onInit(e);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.controls.add(this.item);
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.node
                            .children("div:first-child")
                            .children("*:first-child").css({
                            width: "100%"
                        });
                    }
                }
                Controls.ToolbarOverflowItem = ToolbarOverflowItem;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarSegmentEventArgs {
                    constructor(options) {
                        this.m_options = options;
                    }
                    get toolbar() {
                        return this.m_options.toolbar;
                    }
                    get items() {
                        return this.m_options.items;
                    }
                    get segment() {
                        return this.m_options.segment;
                    }
                    registerItem(item) {
                        item.toolbar = this.toolbar;
                        this.toolbar.controls.add(item);
                    }
                    addSeparator() {
                        this.toolbar.controls.add(new Controls.ToolbarSeparator());
                    }
                }
                Controls.ToolbarSegmentEventArgs = ToolbarSegmentEventArgs;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class ToolbarSeparator extends Controls.ToolbarItem {
                    constructor(options = {}) {
                        super(options);
                        this.V_STYLE = "-pdjs-shared-ui-controls-toolbar-separator-v";
                        this.H_STYLE = "-pdjs-shared-ui-controls-toolbar-separator-h";
                        this.allowOverflow = false;
                    }
                    createCopy() {
                        return new ToolbarSeparator(this.state.toJSON());
                    }
                    onActivate(e) {
                        super.onActivate(e);
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.overflowed ?
                            this.contentNode.removeClass(this.V_STYLE) :
                            this.contentNode.removeClass(this.H_STYLE);
                        this.overflowed ?
                            this.contentNode.addClass(this.H_STYLE) :
                            this.contentNode.addClass(this.V_STYLE);
                        this.overflowed ?
                            this.node.hide() :
                            this.node.show();
                    }
                    content() {
                        return `<div class="${this.V_STYLE}">
                        <div>&nbsp;</div>
                    </div>`;
                    }
                }
                Controls.ToolbarSeparator = ToolbarSeparator;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class Tooltip {
                    constructor(target, options) {
                    }
                    createControl() {
                        return null;
                    }
                }
                Controls.Tooltip = Tooltip;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TreeContextMenu extends Jade.UI.ContextMenu {
                    constructor(options) {
                        super({
                            open: options.open,
                            target: `${options.target}`,
                            container: `${options.target}`,
                            filter: `li[role=treeitem][data-uid]`,
                            segments: options.segments
                        });
                    }
                }
                Controls.TreeContextMenu = TreeContextMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TreeViewContextMenu extends Jade.UI.ContextMenu {
                    constructor(options) {
                        if (options.tree.element.attr("id") == null) {
                            options.tree.element.attr("id", Jade.Guid.new());
                        }
                        super({
                            container: `div[id="${options.tree.element.attr("id")}"]`,
                            filter: `div[id="${options.tree.element.attr("id")}"] li.k-item[role=treeitem]`,
                            segments: options.segments
                        });
                    }
                }
                Controls.TreeViewContextMenu = TreeViewContextMenu;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class UploadInput extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get browseButtonNode() {
                        return this.node.find(".-pd-upload-input-button");
                    }
                    get labelNode() {
                        return this.node.find(".-pd-upload-input-label");
                    }
                    get mimeTypes() {
                        return this.state.get("mimeTypes", []);
                    }
                    get scaleNode() {
                        return this.node.find(".-pd-upload-input-scale");
                    }
                    get scaleLabelNode() {
                        return this.node.find(".-pd-upload-input-scale-label");
                    }
                    get uploadId() {
                        return this.m_uploadFile != null ? this.m_uploadFile.id : null;
                    }
                    get uploadName() {
                        return this.m_uploadFile != null ? this.m_uploadFile.name : null;
                    }
                    get uploadExtension() {
                        return this.m_uploadFile != null ? Jade.Path.getFileExtension(this.uploadName) : null;
                    }
                    get uploadUniqueName() {
                        return this.uploadId + this.uploadExtension;
                    }
                    get onFileSelectedCallback() {
                        return this.state.get("onFileSelected", () => { });
                    }
                    get onUploadStartCallback() {
                        return this.state.get("onUploadStart", () => { });
                    }
                    get onUploadCompleteCallback() {
                        return this.state.get("onUploadComplete", () => { });
                    }
                    get watermark() {
                        return this.state.get("watermark", "");
                    }
                    focus() {
                        this.browseButtonNode.focus();
                    }
                    template() {
                        return `
                <div class='-pd-upload-input'>
                    <div class='-pd-upload-input-progress'>
                        <div class='-pd-upload-input-background'></div>
                        <div class='-pd-upload-input-scale'>
                        </div>
                        <div class='-pd-upload-input-label'></div>
                        <div class='-pd-upload-input-scale-label'></div>
                    </div>
                    <input type='button' value='...' class='-pd-upload-input-button'/>
                </div>
            `;
                    }
                    setLabelText(value) {
                        this.labelNode.text(value);
                    }
                    onActivate(e) {
                        this.m_upload = new PDJS.Shared.Upload.UploaderBase({
                            containerNode: this.node,
                            selectButtonNode: this.browseButtonNode,
                            mimeTypes: this.mimeTypes,
                            multiSelect: false,
                            onFilesAdded: _.bind(this.upload_onFilesAdded, this),
                            onUploadProgress: _.bind(this.upload_onProgress, this),
                            onUploadComplete: _.bind(this.upload_onComplete, this),
                            onError: _.bind(this.upload_onError, this)
                        });
                        this.labelNode.text(this.watermark);
                    }
                    upload_onFilesAdded(sender, e) {
                        this.m_uploadFile = _.first(e.toArray()).toJSON();
                        this.onFileSelectedCallback(this.m_uploadFile);
                        this.m_upload.startUpload();
                        this.browseButtonNode.prop("disabled", true);
                        this.onUploadStartCallback(this.m_uploadFile);
                    }
                    upload_onProgress(sender, e) {
                        this.setText("Uploading file... " + e.percent + " %");
                        this.scaleNode.css({
                            width: e.percent + "%"
                        });
                        this.scaleLabelNode.css({
                            width: e.percent + "%"
                        });
                    }
                    upload_onComplete(sender, e) {
                        this.setText(this.uploadName);
                        this.scaleNode.css({
                            width: "0"
                        });
                        this.scaleLabelNode.css({
                            width: "0"
                        });
                        this.browseButtonNode.prop("disabled", false);
                        this.onUploadCompleteCallback(this.m_uploadFile);
                        this.scaleNode.text("");
                    }
                    upload_onError(sender, e) {
                        Jade.UI.Dialogs.MessageDialog.open({
                            title: "Upload | Error",
                            message: e.message,
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            select: (e) => {
                                e.close();
                            }
                        });
                        this.browseButtonNode.prop("disabled", false);
                    }
                    setText(text) {
                        this.labelNode.text(text);
                        this.scaleLabelNode.text(text);
                    }
                }
                Controls.UploadInput = UploadInput;
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class Field extends Jade.UI.Control {
                        constructor(options) {
                            super(options);
                            this.m_errors = new Jade.ObservableCollection(null, {
                                onAfterAdd: (e) => {
                                    this.onValidationErrorChange();
                                },
                                onAfterRemove: (e) => {
                                    this.onValidationErrorChange();
                                }
                            });
                            this.m_validators = new Jade.ObservableCollection(null, {
                                onAfterAdd: (e) => {
                                    e.item.field = this;
                                }
                            });
                            if (this.errorCodeMaps.length > 0) {
                                this.validators.add(new Fields.FieldValidatorErrorCodes({
                                    handlesErrorCodes: this.errorCodeMaps
                                }));
                            }
                        }
                        get enabled() {
                            return this.state.get("enabled", true);
                        }
                        set enabled(value) {
                            this.state.set("enabled", value);
                        }
                        get errors() {
                            return this.m_errors;
                        }
                        get errorCodeMaps() {
                            return this.state.get("errorCodeMaps", []);
                        }
                        get validators() {
                            return this.m_validators;
                        }
                        get isValid() {
                            return this.errors.count == 0;
                        }
                        get label() {
                            return this.state.get("label");
                        }
                        get labelColor() {
                            return this.state.get("labelColor", "var(--visiv-theme-base-2-text-color)");
                        }
                        get labelNode() {
                            return this.node.children("[role=label]");
                        }
                        get labelVisible() {
                            return this.state.get("labelVisible", true);
                        }
                        set labelVisible(value) {
                            this.state.get("labelVisible", value);
                        }
                        get tooltip() {
                            return this.state.get("tooltip");
                        }
                        get required() {
                            return this.state.get("required", false);
                        }
                        get controlNode() {
                            return this.node.children("[role=control]");
                        }
                        focus() {
                        }
                        validate() {
                            this.errors.clear();
                            this.removeValidationErrorToolTip();
                            this.validators.each((validator) => {
                                if (!this.validatorValidate(validator)) {
                                    this.errors.add(new Fields.FieldValidationError({
                                        message: validator.getMessage(this.label)
                                    }));
                                }
                                ;
                            });
                            this.onValidationErrorChange();
                        }
                        template() {
                            return `<div class="-pdjs-shared-ui-field">
                        <div role="label">:</div>
                        <div role="control" data-controls></div>
                    </div>`;
                        }
                        hasValue() {
                            return true;
                        }
                        hideTooltips() {
                            PDJS.Shared.PopOver.hide(this.labelNode);
                            PDJS.Shared.PopOver.hide(this.controlNode);
                        }
                        showTooltips() {
                            PDJS.Shared.PopOver.show(this.labelNode);
                            PDJS.Shared.PopOver.show(this.controlNode);
                        }
                        onInit(e) {
                            super.onInit(e);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            if (this.required) {
                                this.validators.add(new Fields.FieldValidatorRequired());
                            }
                        }
                        onDestroy(e) {
                            super.onDestroy(e);
                            PDJS.Shared.PopOver.remove(this.labelNode);
                            PDJS.Shared.PopOver.remove(this.controlNode);
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.labelNode.text(`${this.label}:`);
                            this.labelNode.css({
                                color: this.required ? "var(--visiv-required-text-color)" : this.labelColor
                            });
                            this.enabled ?
                                this.controlNode.removeClass(PDJS.Shared.UI.CssClass.Disabled) :
                                this.controlNode.addClass(PDJS.Shared.UI.CssClass.Disabled);
                            this.applyLabelVisibility();
                        }
                        onValidationErrorChange() {
                            if (this.errors.count > 0) {
                                this.addValidationErrorToolTip();
                            }
                            else {
                                this.removeValidationErrorToolTip();
                            }
                        }
                        validatorValidate(validator) {
                            return true;
                        }
                        addValidationErrorToolTip() {
                            this.removeValidationErrorToolTip();
                            let message = "";
                            let icon = Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x16);
                            this.errors.each((error) => {
                                message += error.message;
                            });
                            this.node.addClass("-pdjs-validation-errors");
                            this.labelVisible ?
                                this.addValidationErrorForLabeled(icon, message) :
                                this.addValidationErrorForUnlabeled(icon, message);
                        }
                        removeValidationErrorToolTip() {
                            PDJS.Shared.PopOver.remove(this.labelNode);
                            this.node.removeClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: ""
                            });
                            PDJS.Shared.PopOver.remove(this.controlNode);
                        }
                        applyLabelVisibility() {
                            if (this.labelVisible) {
                                this.labelNode.show();
                                this.node.css({ gridTemplateRows: "max-content auto" });
                                return;
                            }
                            if (!this.labelVisible) {
                                this.labelNode.hide();
                                this.node.css({ gridTemplateRows: "auto" });
                                return;
                            }
                        }
                        addValidationErrorForLabeled(icon, message) {
                            PDJS.Shared.PopOver.validation(this.labelNode, message);
                            this.labelNode.css({
                                backgroundImage: `url(${icon})`
                            });
                        }
                        addValidationErrorForUnlabeled(icon, message) {
                            let content = $(`<div style="width:200px;">${message}</div>`);
                            content.css({
                                backgroundRepeat: "no-repeat",
                                backgroundPosition: "5px center",
                                backgroundImage: `url(${icon})`,
                                padding: "5px 5px 5px 25px"
                            });
                            PDJS.Shared.PopOver.validation(this.controlNode, content, {
                                showOn: "mouseenter",
                                hideOnClickOutside: true,
                                hideOn: "mouseleave",
                                hideDelay: 0,
                                hideAfter: 0,
                                fadeIn: 0,
                                fadeOut: 0,
                                position: {
                                    target: "topleft",
                                    tooltip: "bottomleft"
                                }
                            });
                        }
                    }
                    Fields.Field = Field;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ExpressionField extends Fields.Field {
                        construtor(options) {
                        }
                        get aceNode() {
                            return this.controlNode.children("[role=ace]");
                        }
                        get editor() {
                            return this.m_editor;
                        }
                        get height() {
                            return this.state.get("height");
                        }
                        get theme() {
                            return PDJS.System.Environment
                                .current.profile.themes.defaultEditor || "ace/theme/chrome";
                        }
                        get value() {
                            return this.editor.getValue();
                        }
                        set value(value) {
                            this.editor.setValue(value || "", 0);
                            this.editor.clearSelection();
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        insertTag(text) {
                            this.editor.insert(`${text} ` || "");
                        }
                        focus() {
                            this.m_editor.focus();
                        }
                        blur() {
                            this.m_editor.blur();
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        redraw() {
                            this.editor.resize();
                            this.editor.renderer.updateFull(true);
                        }
                        highlight(texts) {
                            let regex = new RegExp(texts.split(", ").join("|"), "gim");
                            this.editor.moveCursorTo(0, 0);
                            this.editor.clearSelection();
                            this.editor.findAll(null, {
                                needle: regex,
                                wholeWord: true,
                                range: null,
                                regEx: true,
                                backwards: true
                            }, true);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.controlNode.append(`<div role="ace"></div>`);
                            ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                            this.m_editor = ace.edit(this.aceNode.get(0));
                            this.editor.renderer.setShowPrintMargin(false);
                            this.editor.setShowFoldWidgets(false);
                            this.editor.getSession().setUseSoftTabs(true);
                            this.editor.setFontSize("14px");
                            this.editor.renderer.setShowGutter(false);
                            this.editor.setHighlightActiveLine(false);
                            this.editor.setTheme(this.theme);
                            this.editor.commands.removeCommand("find");
                            this.editor.commands.removeCommand("showSettingsMenu");
                            this.editor.session.setMode({ path: "ace/mode/pdjsexpression", v: Date.now() });
                            this.editor.on("change", (e) => {
                                this.changeCallback();
                            });
                            this.node.addClass("-pdjs-shared-ui-controls-field-expression");
                            if (this.height != null) {
                                this.node.height(this.height);
                            }
                            this.subscriptions.add(PDJS.Shared.Themes.EventsHub.setThemeSubscribe(() => {
                                this.editor.setTheme(PDJS.System.Environment.current.profile.themes.manageEditor);
                            }));
                        }
                    }
                    Fields.ExpressionField = ExpressionField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ServiceValidation {
                        static mapServiceErrors(parent, errors = []) {
                            parent.controls.getByType(Shared.UI.Controls.Fields.Field).each(field => {
                                field.validators.getByType(Shared.UI.Controls.Fields.FieldValidatorErrorCodes).each(validator => {
                                    validator.errorCodes = errors;
                                });
                            });
                        }
                    }
                    Fields.ServiceValidation = ServiceValidation;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidationError {
                        constructor(options) {
                            this.m_message = options.message;
                        }
                        get message() {
                            return this.m_message;
                        }
                    }
                    Fields.FieldValidationError = FieldValidationError;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class BooleanField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get checkboxLabel() {
                            return this.state.get("checkboxLabel");
                        }
                        get checkboxLabelNode() {
                            return this.controlNode.find("div[role=input-label]");
                        }
                        get checkboxNode() {
                            return this.controlNode.find("input[type=checkbox]");
                        }
                        get value() {
                            return this.state.get("value");
                        }
                        set value(value) {
                            this.state.set("value", value);
                        }
                        focus() {
                            this.checkboxNode.focus();
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.node.css({
                                height: "50px"
                            });
                            this.controlNode.append(`<label>
                                        <input type="checkbox" ${this.value ? "checked" : ""} />
                                        <div role="input-label">
                                            ${this.checkboxLabel}
                                        </div>
                                    </label>`);
                            this.checkboxNode.prop("checked", this.value);
                            this.checkboxNode.css({
                                position: "absolute",
                                top: "4px",
                                left: "4px",
                            });
                            this.checkboxLabelNode.css({
                                position: "absolute",
                                top: 0,
                                left: "22px",
                                bottom: 0,
                                lineHeight: "22px"
                            });
                            this.controlNode.addClass(PDJS.Canvas.Shared.CanvasCss.BooleanField);
                        }
                    }
                    Fields.BooleanField = BooleanField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class DateField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        get value() {
                            return this.state.get("value");
                        }
                        set value(value) {
                            this.state.set("value", value);
                        }
                        get validateOnBlur() {
                            return this.state.get("validateOnBlur", true);
                        }
                        get validateOnChange() {
                            return this.state.get("validateOnChange", true);
                        }
                        focus() {
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.dateTextBox_init();
                            this.validators.add(new Fields.FieldValidatorFunction({
                                fn: (e) => {
                                    return Shared.DateFormat.isValid(this.value, "MM/DD/YYYY");
                                },
                                message: "Value is not a valid date."
                            }));
                            this.node.addClass("-pdjs-shared-ui-controls-field-date");
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.m_dateTextBox.enabled = this.enabled;
                            this.node.css({
                                height: `${(this.labelVisible ? 50 : 25)}px`
                            });
                            if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                                this.m_dateTextBox.value = this.value;
                                this.m_dateTextBox.mask = this.value;
                            }
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.value);
                        }
                        dateTextBox_init() {
                            this.m_dateTextBox = new PDJS.Shared.UI.Controls.DateTextBox({
                                tabIndex: 0,
                                format: "MM/dd/yyyy",
                                useValidationAnimation: false,
                                onChange: (e) => {
                                    this.value = e.value;
                                    if (Jade.String.isNullOrWhiteSpace(e.value)) {
                                        e.isValid = true;
                                    }
                                    if (this.validateOnChange) {
                                        this.validate();
                                    }
                                    if (e.isValid) {
                                        this.changeCallback({
                                            value: e.value
                                        });
                                    }
                                }
                            });
                            this.controls.add(this.m_dateTextBox);
                        }
                    }
                    Fields.DateField = DateField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class MultiSelectField extends Fields.Field {
                        constructor(options) {
                            super(options);
                            this.SELECT_ALL = "$select-all$";
                        }
                        get selected() {
                            return this.getSelectedDataItems();
                        }
                        get height() {
                            return this.state.get("height", 50);
                        }
                        get width() {
                            return this.state.get("width", "100%");
                        }
                        get tree() {
                            return this.m_tree;
                        }
                        get treeNode() {
                            return this.controlNode.children(".-pdjs-field-multi-select-tree");
                        }
                        get checkCallback() {
                            return this.state.get("check", () => { });
                        }
                        get binding() {
                            return _.extend({
                                label: "label",
                                value: "value",
                                checked: "checked"
                            }, this.state.get("binding", {}));
                        }
                        get items() {
                            return this.state.get("items", []);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.node.addClass("-pdjs-field-multi-select");
                            this.controlNode.append(`<div class="-pdjs-field-multi-select-tree"></div>`);
                            this.tree_init();
                            this.node.css({
                                height: this.height,
                                width: this.width
                            });
                        }
                        tree_init() {
                            let data = [{
                                    id: this.SELECT_ALL,
                                    text: "(Select All)"
                                }];
                            this.items.forEach(item => {
                                data.push({
                                    id: item[this.binding.value],
                                    text: item[this.binding.label],
                                    checked: item[this.binding.checked] == true || false
                                });
                            });
                            this.m_tree = this.treeNode.kendoTreeView({
                                dataSource: {
                                    data: data
                                },
                                checkboxes: true,
                                select: _.bind(this.tree_onSelect, this),
                                check: _.bind(this.tree_onChecked, this)
                            }).data("kendoTreeView");
                        }
                        tree_onChecked(e) {
                            let data = this.tree.dataItem(e.node);
                            let node = $(e.node);
                            this.triggerCheck(node, data);
                            this.checkCallback({
                                node: node,
                                data: this.tree.dataItem(e.node).toJSON()
                            });
                            e.preventDefault();
                        }
                        tree_onSelect(e) {
                            let data = this.tree.dataItem(e.node);
                            let node = $(e.node);
                            let checkbox = node.find(".k-checkbox > input");
                            this.checkNode(node, !checkbox.is(":checked"));
                            this.triggerCheck(node, data);
                            if (data[this.binding.value] == this.SELECT_ALL) {
                                this.checkAll(node);
                            }
                            this.checkCallback({
                                node: node,
                                data: this.tree.dataItem(e.node).toJSON()
                            });
                            e.preventDefault();
                            return false;
                        }
                        triggerCheck(node, data) {
                            data.id == this.SELECT_ALL ?
                                this.checkAll(node) :
                                this.setCheckAllState();
                        }
                        checkAll(node) {
                            let allCheckbox = node.find(".k-checkbox > input");
                            let allCheckboxChecked = allCheckbox.prop("checked");
                            let checkboxes = this.treeNode.find("INPUT[type=checkbox]:gt(0)");
                            if (allCheckbox.prop("indeterminate")) {
                                allCheckbox.prop("indeterminate", false);
                                allCheckbox.prop("checked", true);
                                allCheckboxChecked = true;
                            }
                            checkboxes.each((index, item) => {
                                this.checkNode($(item), allCheckboxChecked);
                            });
                        }
                        checkNode(node, checked) {
                            let checkbox = node.find(".k-checkbox > input");
                            let dataItem = this.tree.dataItem(node);
                            dataItem.set("checked", checked);
                            checkbox.prop("checked", checked);
                        }
                        setCheckAllState() {
                            let checkbox = this.treeNode.find("INPUT[type=checkbox]:first");
                            let groupState = this.checkboxesGroupState();
                            if (groupState === undefined) {
                                checkbox.prop("indeterminate", true);
                            }
                            else {
                                checkbox.prop("indeterminate", false);
                                checkbox.prop("checked", groupState);
                            }
                        }
                        checkboxesGroupState() {
                            let checkboxes = this.treeNode.find("INPUT[type=checkbox]:gt(0)");
                            let result = checkboxes.first().prop("checked");
                            checkboxes.each((index, item) => {
                                if (result !== $(item).prop("checked")) {
                                    result = undefined;
                                    return false;
                                }
                            });
                            return result;
                        }
                        getSelectedDataItems() {
                            let result = [];
                            this.treeNode.find("li.k-item input[type=checkbox]").each((index, element) => {
                                let checkbox = $(element);
                                let isChecked = checkbox.is(":checked");
                                if (isChecked) {
                                    let node = checkbox.closest(".k-item");
                                    let data = this.tree.dataItem(node);
                                    let item = _.first(this.items.filter((item => {
                                        return item[this.binding.value] == data.id;
                                    })));
                                    if (item) {
                                        result.push(item);
                                    }
                                }
                            });
                            return result;
                        }
                    }
                    Fields.MultiSelectField = MultiSelectField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class NumericField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        get inputCallback() {
                            return this.state.get("input", () => { });
                        }
                        get inputNode() {
                            return this.controlNode.find("input");
                        }
                        get numericType() {
                            return this.state.get("numericType", "int32");
                        }
                        get value() {
                            return this.isValidValue(this.rawValue) ?
                                (this.rawValue * 1) : null;
                        }
                        set value(value) {
                            this.rawValue = value == null ?
                                "" : value.toString();
                        }
                        get rawValue() {
                            return this.inputNode.val();
                        }
                        set rawValue(value) {
                            this.inputNode.val(value);
                        }
                        focus() {
                            this.inputNode.get(0).focus();
                            this.inputNode.get(0).select();
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.controlNode.append(`<input type="text" />`);
                            this.node.css({
                                height: this.labelVisible ? "50px" : "25px"
                            });
                            this.inputNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.input_onChange, this));
                            this.inputNode.get(0).addEventListener("input", _.bind(this.input_onInput, this));
                            this.addValidator();
                            this.node.addClass("-pdjs-shared-ui-controls-field-numeric");
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.enabled ?
                                this.inputNode.removeAttr("disabled") :
                                this.inputNode.attr("disabled", "disabled");
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.rawValue);
                        }
                        addValidator() {
                            let message = "";
                            switch (this.numericType) {
                                case "int32":
                                    message = `Value must be an integer.`;
                                    break;
                                case "int64":
                                    message = `Value must be an integer.`;
                                    break;
                                case "decimal":
                                    message = `Value must be a decimal.`;
                                    break;
                            }
                            this.validators.add(new Fields.FieldValidatorFunction({
                                message: message,
                                fn: (e) => {
                                    return this.isValidValue(this.value);
                                }
                            }));
                        }
                        getChangeEventArgs() {
                            return { value: this.rawValue, valid: this.isValidValue(this.rawValue) };
                        }
                        isValidValue(value) {
                            switch (this.numericType) {
                                case "int32":
                                    return PDJS.Shared.Numeric.isInt32(value);
                                case "int64":
                                    return PDJS.Shared.Numeric.isInt64(value);
                                case "decimal":
                                    return PDJS.Shared.Numeric.isDecimal(value);
                                default:
                                    return false;
                            }
                        }
                        input_onInput() {
                            let args = this.getChangeEventArgs();
                            this.validate();
                            this.inputCallback(args);
                            if (args.valid) {
                                this.value = args.value;
                            }
                        }
                        input_onChange() {
                            let args = this.getChangeEventArgs();
                            this.validate();
                            this.changeCallback(args);
                            if (args.valid) {
                                this.value = args.value;
                            }
                        }
                    }
                    Fields.NumericField = NumericField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ProcessComboBox extends PDJS.Shared.UI.Controls.SingleSelectList {
                        get entityTypeId() {
                            return this.state.get("entityTypeId");
                        }
                        set entityTypeId(value) {
                            this.state.set("entityTypeId", value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            if (this.entityTypeId != null) {
                                this.getRemoteData();
                            }
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            if (this.state.hasChanged("entityTypeId")) {
                                this.getRemoteData();
                            }
                        }
                        getRemoteData() {
                            let service = new PDJS.Services.Process.ProcessService();
                            service.getProcesses({
                                entityTypeId: this.entityTypeId,
                                success: (e) => {
                                    let items = [];
                                    _.each(e.data, (item) => {
                                        items[items.length] = {
                                            id: item.id,
                                            label: item.name,
                                            icon: null
                                        };
                                    });
                                    this.data.clear();
                                    this.data.addRange(items);
                                    this.selection = null;
                                }
                            });
                        }
                    }
                    Fields.ProcessComboBox = ProcessComboBox;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ProcessField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get entityTypeId() {
                            return this.state.get("entityTypeId");
                        }
                        set entityTypeId(value) {
                            this.state.set("entityTypeId", value);
                        }
                        get input() {
                            return this.m_input;
                        }
                        get onSelectionChangedCallback() {
                            return this.state.get("onSelectionChanged", () => { });
                        }
                        get processId() {
                            return this.input.selection != null
                                ? this.input.selection.id : null;
                        }
                        get processName() {
                            return this.input.selection != null
                                ? this.input.selection.label : null;
                        }
                        hasValue() {
                            return this.processId != null;
                        }
                        onInit(e) {
                            super.onInit(e);
                            this.m_input = new Fields.ProcessComboBox({
                                defaultMaskText: "Select...",
                                entityTypeId: this.entityTypeId,
                                onSelectionChanged: (e) => {
                                    let item = this.input.selection;
                                    let selection = null;
                                    if (item != null) {
                                        selection = {
                                            id: item.id,
                                            label: item.label,
                                            icon: item.icon
                                        };
                                    }
                                    this.onSelectionChangedCallback(selection);
                                }
                            });
                            this.controls.add(this.m_input);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.controlNode.css({
                                borderWidth: 0
                            });
                            this.node.addClass("-pdjs-shared-ui-single-select-field");
                            this.input.input.maskNode.removeAttr("tabIndex");
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.processId);
                        }
                    }
                    Fields.ProcessField = ProcessField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ProcessStatusComboBox extends PDJS.Shared.UI.Controls.SingleSelectList {
                        get processId() {
                            return this.state.get("processId");
                        }
                        set processId(value) {
                            this.state.set("processId", value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            if (this.processId != null) {
                                this.getRemoteData();
                            }
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            if (this.state.hasChanged("processId")) {
                                this.getRemoteData();
                            }
                        }
                        getRemoteData() {
                            let service = new PDJS.Services.Process.ProcessService();
                            if (this.processId == null) {
                                this.data.clear();
                                this.selection = null;
                                return;
                            }
                            service.getStatusList({
                                processId: this.processId,
                                success: (e) => {
                                    let items = [];
                                    _.each(e.data, (item) => {
                                        items[items.length] = {
                                            id: item.id,
                                            label: item.name,
                                            icon: item.icon
                                        };
                                    });
                                    this.data.clear();
                                    this.data.addRange(items);
                                    this.selection = null;
                                }
                            });
                        }
                    }
                    Fields.ProcessStatusComboBox = ProcessStatusComboBox;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class ProcessStatusField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get processId() {
                            return this.state.get("processId");
                        }
                        set processId(value) {
                            this.state.set("processId", value);
                        }
                        get statusId() {
                            return this.input.selection != null
                                ? this.input.selection.id : null;
                        }
                        get statusName() {
                            return this.input.selection != null
                                ? this.input.selection.label : null;
                        }
                        get statusIcon() {
                            return this.input.selection != null
                                ? this.input.selection.icon : null;
                        }
                        get input() {
                            return this.m_input;
                        }
                        get onSelectionChangedCallback() {
                            return this.state.get("onSelectionChanged", () => { });
                        }
                        hasValue() {
                            return this.statusId != null;
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.input.processId = this.processId;
                            this.input.enabled = this.processId != null && this.enabled;
                        }
                        onInit(e) {
                            super.onInit(e);
                            this.m_input = new Fields.ProcessStatusComboBox({
                                defaultMaskText: "Select...",
                                processId: this.processId,
                                onSelectionChanged: (e) => {
                                    let item = this.input.selection;
                                    let selection = null;
                                    if (item != null) {
                                        selection = {
                                            id: item.id,
                                            label: item.label,
                                            icon: item.icon
                                        };
                                    }
                                    this.onSelectionChangedCallback(selection);
                                }
                            });
                            this.controls.add(this.m_input);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.controlNode.css({
                                borderWidth: 0
                            });
                            this.node.addClass("-pdjs-shared-ui-single-select-field");
                            this.input.input.maskNode.removeAttr("tabIndex");
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.statusId);
                        }
                    }
                    Fields.ProcessStatusField = ProcessStatusField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class SelectField extends Fields.Field {
                        constructor(options) {
                            super(options);
                            this.m_items = [];
                            this.m_items = (options === null || options === void 0 ? void 0 : options.items) || [];
                        }
                        get selectNode() {
                            return this.controlNode.find("select");
                        }
                        get value() {
                            return this.selectNode.val();
                        }
                        set value(value) {
                            this.selectNode.val(value === null || value === void 0 ? void 0 : value.toString());
                        }
                        get binding() {
                            return this.state.get("binding", { label: "label", value: "value" });
                        }
                        set binding(value) {
                            this.state.set("binding", value);
                        }
                        get validateOnChange() {
                            return this.state.get("validateOnChange", true);
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        get items() {
                            return this.m_items || [];
                        }
                        set items(value) {
                            this.m_items = value;
                        }
                        focus() {
                            this.selectNode.get(0).focus();
                            this.selectNode.get(0).select();
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        data(items, binding) {
                            if (binding) {
                                this.binding = binding;
                            }
                            this.items = items;
                            this.dataBind();
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.node.addClass("-pdjs-field-select");
                            this.controlNode.append(`<div role="select-container"><select></select><div>`);
                            this.selectNode.on(Jade.BrowserEvent.CHANGE, () => {
                                if (this.validateOnChange) {
                                    this.validate();
                                }
                                this.changeCallback();
                            });
                            if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                                this.selectNode.val(this.value);
                            }
                            this.dataBind();
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.value);
                        }
                        dataBind() {
                            this.selectNode.empty();
                            this.items.forEach(item => {
                                this.selectNode.append(`<option value="${item[this.binding.value]}">${item[this.binding.label]}</option>`);
                            });
                        }
                    }
                    Fields.SelectField = SelectField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class SingleSelectField extends Fields.Field {
                        get inputNode() {
                            return this.controlNode.find("input");
                        }
                        get input() {
                            return this.m_input;
                        }
                        get data() {
                            return this.input.data;
                        }
                        get value() {
                            let result = parseInt(this.inputNode.val());
                            return result == Number.NaN ? null : result;
                        }
                        set value(value) {
                            if (value == null) {
                                this.rawValue = "";
                            }
                            else {
                                this.rawValue = value.toString();
                            }
                        }
                        get rawValue() {
                            return this.inputNode.val();
                        }
                        set rawValue(value) {
                            this.inputNode.val(value);
                        }
                        get onValueChangedCallback() {
                            return this.state.get("onValueChanged", () => { });
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        clear() {
                            this.input.data.clear();
                        }
                        onInit(e) {
                            super.onInit(e);
                            this.m_input = new Controls.SingleSelectList({
                                defaultMaskText: "Select...",
                                onSelectionChanged: (e) => {
                                    let item = this.input.selection;
                                    let selection = null;
                                    if (item != null) {
                                        selection = {
                                            id: item.id,
                                            label: item.label,
                                            icon: item.icon
                                        };
                                    }
                                    this.onValueChangedCallback(selection);
                                }
                            });
                            this.controls.add(this.m_input);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.controlNode.css({
                                borderWidth: 0
                            });
                            this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                                this.validate();
                            });
                            this.node.addClass("-pdjs-shared-ui-single-select-field");
                            this.input.input.maskNode.removeAttr("tabIndex");
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.rawValue);
                        }
                    }
                    Fields.SingleSelectField = SingleSelectField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class StringField extends Fields.Field {
                        constructor(options) {
                            super(options);
                        }
                        get blurCallback() {
                            return this.state.get("blur", () => { });
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        get height() {
                            return this.state.get("height", 50);
                        }
                        get inputCallback() {
                            return this.state.get("input", () => { });
                        }
                        get inputNode() {
                            return this.controlNode.find("input, textarea");
                        }
                        get minLength() {
                            return this.state.get("minLength", 0);
                        }
                        get maxLength() {
                            return this.state.get("maxLength", null);
                        }
                        get multiline() {
                            return this.state.get("multiline", null);
                        }
                        get validateOnBlur() {
                            return this.state.get("validateOnBlur", true);
                        }
                        get value() {
                            return this.inputNode.val();
                        }
                        set value(value) {
                            this.inputNode.val(value);
                        }
                        focus() {
                            this.inputNode.get(0).focus();
                            this.inputNode.get(0).select();
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.multiline ?
                                this.controlNode.append(`<textarea max-length=""></textarea>`) :
                                this.controlNode.append(`<input type="text" />`);
                            this.inputNode.css({
                                border: "0 none transparent",
                                height: `100%`,
                                width: "100%",
                                paddingLeft: "5px",
                                boxSizing: "border-box",
                                position: "absolute",
                                inset: 0,
                                fontSize: "12px"
                            });
                            this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.input_onBlur, this));
                            this.inputNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.input_onChange, this));
                            this.inputNode.get(0).addEventListener("input", _.bind(this.input_onInput, this));
                            if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                                this.inputNode.val(this.value);
                            }
                            this.validators.add(new Fields.FieldValidatorLength({
                                min: this.minLength,
                                max: this.maxLength
                            }));
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.inputNode.prop("disabled", !this.enabled);
                            if (this.maxLength > 0) {
                                this.inputNode.attr("maxlength", this.maxLength);
                            }
                            this.node.css({
                                height: `${this.height - (this.labelVisible ? 0 : 25)}px`
                            });
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.value);
                        }
                        input_onBlur(e) {
                            if (this.validateOnBlur) {
                                this.validate();
                                this.blurCallback();
                            }
                        }
                        input_onChange(e) {
                            let args = { value: this.value };
                            this.validate();
                            this.changeCallback(args);
                        }
                        input_onInput(element, e) {
                            let args = { value: this.value };
                            this.validate();
                            this.inputCallback(args);
                        }
                    }
                    Fields.StringField = StringField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class TileField extends Fields.Field {
                        constructor(options) {
                            super(options);
                            this.m_items = [];
                            this.m_items = (options === null || options === void 0 ? void 0 : options.items) || [];
                        }
                        get tilesNode() {
                            return this.controlNode.find("div[role=tiles]");
                        }
                        get tiles() {
                            return this.tilesNode.children("div[role=tile]");
                        }
                        get value() {
                            return this.getValue();
                        }
                        set value(value) {
                            this.setValue(value === null || value === void 0 ? void 0 : value.toString());
                        }
                        get binding() {
                            return this.state.get("binding", { label: "label", value: "value", image: "image" });
                        }
                        set binding(value) {
                            this.state.set("binding", value);
                        }
                        get changeCallback() {
                            return this.state.get("change", () => { });
                        }
                        get items() {
                            return this.m_items || [];
                        }
                        set items(value) {
                            this.m_items = value;
                        }
                        get height() {
                            return this.state.get("height", "125px");
                        }
                        set height(value) {
                            this.state.set("height", value);
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        data(items, binding) {
                            if (binding) {
                                this.binding = binding;
                            }
                            this.items = items;
                            this.dataBind();
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            this.node.addClass("-pdjs-field-tile");
                            this.controlNode.append(`<div role="tiles"><div>`);
                            this.tilesNode.on(Jade.BrowserEvent.CLICK, "div[role=tile]", (e) => {
                                this.tiles.removeClass("-pdjs-selected");
                                $(e.currentTarget).addClass("-pdjs-selected");
                                this.changeCallback();
                            });
                            this.dataBind();
                        }
                        dataBind() {
                            let icon = (name) => {
                                return Jade.IconSet.get("pdjs").resolve(name, Jade.IconSetSizeSpecificDirectory.x48);
                            };
                            this.items.forEach(item => {
                                let label = item[this.binding.label];
                                let value = item[this.binding.value];
                                let image = item[this.binding.image];
                                this.tilesNode.append(`
                    <div role="tile" data-value="${value}">
                        <div>
                            <img src="${icon(image)}"/>
                        </div>
                        <div>${label}</div>
                    </div>`);
                            });
                        }
                        setValue(value) {
                            this.tiles.each((index, item) => {
                                let node = $(item);
                                node.data("value") == value ?
                                    node.addClass("-pdjs-selected") :
                                    node.removeClass("-pdjs-selected");
                            });
                        }
                        getValue() {
                            let result;
                            this.tiles.each((index, item) => {
                                let node = $(item);
                                node.hasClass("-pdjs-selected") ?
                                    result = node.data("value") :
                                    null;
                            });
                            return result;
                        }
                    }
                    Fields.TileField = TileField;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidator {
                        constructor(options) {
                            this.m_state = new Jade.StateBag(options);
                        }
                        get field() {
                            return this.m_field;
                        }
                        set field(value) {
                            this.m_field = value;
                        }
                        get message() {
                            return this.state.get("message", "Validation Error");
                        }
                        set message(value) {
                            this.state.set("message", value);
                        }
                        get state() {
                            return this.m_state;
                        }
                        isValid(value) {
                            return true;
                        }
                        getMessage(fieldLabel) {
                            return Jade.String.format(this.message, fieldLabel);
                        }
                    }
                    Fields.FieldValidator = FieldValidator;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorErrorCodes extends Fields.FieldValidator {
                        constructor(options) {
                            super(options);
                        }
                        get errorCodes() {
                            return this.m_errorCodes || [];
                        }
                        set errorCodes(value) {
                            this.m_errorCodes = value;
                        }
                        isValid(value) {
                            this.message = "";
                            let errorCodes = this.errorCodes.filter(error => {
                                return this.field.errorCodeMaps.includes(error.code);
                            });
                            errorCodes.forEach((error, i) => {
                                this.message = `${this.message}${i > 0 ? "\n" : ""}${error.message}`;
                            });
                            return errorCodes.length == 0;
                        }
                    }
                    Fields.FieldValidatorErrorCodes = FieldValidatorErrorCodes;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorFunction extends Fields.FieldValidator {
                        constructor(options) {
                            super(options);
                        }
                        get fn() {
                            return this.state.get("fn");
                        }
                        isValid(value) {
                            return this.fn({ sender: this, value: value });
                        }
                    }
                    Fields.FieldValidatorFunction = FieldValidatorFunction;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorLength extends Fields.FieldValidator {
                        constructor(options) {
                            super(_.extend({
                                message: "Min/Max length is exceeded."
                            }, options));
                        }
                        get min() {
                            return this.state.get("min");
                        }
                        get max() {
                            return this.state.get("max");
                        }
                        isValid(value) {
                            let text = [];
                            let isMinSet = this.min != null && this.min > 0;
                            let isMaxSet = this.max != null && this.max > 0;
                            let isMinAndMaxNotSet = !isMinSet && !isMaxSet;
                            if (value == null || isMinAndMaxNotSet) {
                                return true;
                            }
                            if (isMinSet && value.length < this.min) {
                                text.push(`Value must contain a minimum of ${this.min} characters.`);
                            }
                            if (isMaxSet && value.length > this.max) {
                                text.push(`Value must contain a maximum of ${this.max} characters.`);
                            }
                            if (text.length > 0) {
                                this.message = text.join("");
                                return false;
                            }
                            return true;
                        }
                    }
                    Fields.FieldValidatorLength = FieldValidatorLength;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorMultipleOf extends Fields.FieldValidator {
                        constructor(options) {
                            super(_.extend({
                                message: `Value must be a multiple of ${options.multipleOf}.`
                            }, options));
                            this.m_multipleOf = options.multipleOf;
                        }
                        get multipleOf() {
                            return this.m_multipleOf;
                        }
                        isValid(value) {
                            if (Jade.String.isNullOrWhiteSpace(value)) {
                                return true;
                            }
                            let numericValue = parseInt(value);
                            let result = true;
                            if (numericValue != null) {
                                result = (numericValue % this.multipleOf) == 0;
                            }
                            return result;
                        }
                    }
                    Fields.FieldValidatorMultipleOf = FieldValidatorMultipleOf;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorRegex extends Fields.FieldValidator {
                        constructor(options) {
                            super(options);
                            this.m_expectedResult = options.expectedResult;
                            this.m_flags = options.flags;
                            this.m_regularExpression = options.regularExpression;
                        }
                        get expectedResult() {
                            return this.m_expectedResult;
                        }
                        get flags() {
                            return this.m_flags;
                        }
                        get regularExpression() {
                            return this.m_regularExpression;
                        }
                        isValid(value) {
                            let result = true;
                            let regEx = null;
                            if (Jade.String.isNullOrWhiteSpace(this.flags)) {
                                regEx = new RegExp(this.regularExpression);
                            }
                            else {
                                regEx = new RegExp(this.regularExpression, this.flags);
                            }
                            if (!Jade.String.isNullOrWhiteSpace(this.regularExpression) && !Jade.String.isNullOrWhiteSpace(value)) {
                                result = regEx.test(value) == this.expectedResult;
                            }
                            return result;
                        }
                    }
                    Fields.FieldValidatorRegex = FieldValidatorRegex;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                var Fields;
                (function (Fields) {
                    class FieldValidatorRequired extends Fields.FieldValidator {
                        constructor() {
                            super({ message: "Value is required." });
                        }
                        isValid(value) {
                            return !Jade.String.isNullOrWhiteSpace(value);
                        }
                    }
                    Fields.FieldValidatorRequired = FieldValidatorRequired;
                })(Fields = Controls.Fields || (Controls.Fields = {}));
            })(Controls = UI.Controls || (UI.Controls = {}));
        })(UI = Shared.UI || (Shared.UI = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            let Events;
            (function (Events) {
                Events["SetCommandState"] = "upload/set-command-state";
            })(Events = Upload.Events || (Upload.Events = {}));
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class EventsHub extends Shared.EventsHubBase {
                static setCommandStatePublish() {
                    this.current.publish(Upload.Events.SetCommandState);
                }
                static setCommandStateSubscribe(handler) {
                    return this.current.subscribe(Upload.Events.SetCommandState, handler);
                }
            }
            Upload.EventsHub = EventsHub;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class ConflictDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get fileName() {
                    return this.state.get("fileName");
                }
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get repeatNode() {
                    return this.node.find("div[role=repeat] input[type=checkbox]");
                }
                template() {
                    return super.template(`
                    <div class="-pdjs-shared-conflict-dialog">
                        <div role="header">${this.getHeaderText()}</div>
                        <div role="conflict">${this.getConflictText()}</div>
                        <div role="list"></div>
                        <div role="repeat">
                            <label>
                                <div>
                                    <input type="checkbox">
                                </div>
                                <div>
                                    Do this for all conflicts like this.
                                </div>
                            </label>
                        </div>
                    </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Replace or Skip Files",
                        actions: [],
                        width: "500px",
                        maximized: false,
                        resizable: true
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.init_list();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.center();
                }
                init_list() {
                    this.list = new PDJS.Shared.UI.Controls.ListView({
                        insertAt: "div[role=list]",
                        data: [
                            {
                                value: 2,
                                label: this.getResolveText(),
                                icon: this.getIcon("check.png")
                            },
                            {
                                value: 1,
                                label: this.getSkipText(),
                                icon: this.getIcon("undo.png")
                            }
                        ],
                        createItem: (e) => {
                            return new PDJS.Shared.UI.Controls.ListViewItem(e);
                        },
                        change: (e) => {
                            var _a, _b;
                            if (e.count > 0) {
                                this.close({
                                    name: "ok",
                                    data: {
                                        action: (_b = (_a = e.first()) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.value,
                                        repeat: this.repeatNode.is(":checked")
                                    }
                                });
                            }
                        }
                    });
                    this.controls.add(this.list);
                }
                getHeaderText() {
                    return `Upload files into folder.`;
                }
                getConflictText() {
                    return `The destination contains a file named "${this.fileName}".`;
                }
                getIcon(icon) {
                    return Jade.IconSet.get("pdjs")
                        .resolve(icon, Jade.IconSetSizeSpecificDirectory.x24);
                }
                getResolveText() {
                    return "Replace the file in the destination";
                }
                getSkipText() {
                    return "Skip the file";
                }
                static open(options) {
                    return new ConflictDialog(options);
                }
            }
            Upload.ConflictDialog = ConflictDialog;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploadDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get folderId() {
                    return this.uploader.folderId;
                }
                static get instance() {
                    return this.m_instance;
                }
                static set instance(value) {
                    this.m_instance = value;
                }
                get uploader() {
                    return this.state.get("$uploader");
                }
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get progressbar() {
                    return this.m_progressbar;
                }
                set progressbar(value) {
                    this.m_progressbar = value;
                }
                get toolbar() {
                    return this.m_toolbar;
                }
                set toolbar(value) {
                    this.m_toolbar = value;
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get commitButtonNode() {
                    return this.node.find("button[data-command=commit]");
                }
                get uploadButtonNode() {
                    return this.node.find("button[data-command=upload]");
                }
                close(options) {
                    super.close(options);
                    UploadDialog.instance = null;
                    if (this.uploader != null) {
                        this.uploader.stopUpload();
                        this.uploader.clear();
                    }
                }
                template() {
                    return super.template(`
                <div class="-pdjs-shared-upload-dialog">
                    <div role="toolbar"></div>
                    <div role="list"></div>
                    <div role="deck">
                        <div role="deck-l">
                        </div>
                        <div role="deck-r">
                            <button data-command="upload" class="-jadeui-dialog-button">Upload</button>
                            <button data-command="commit" class="-jadeui-dialog-button">Save</button>
                            <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                getDefaultOptions() {
                    return {
                        title: "Upload | File",
                        height: 450,
                        width: 700,
                        minHeight: "250px",
                        minWidth: "250px"
                    };
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.uploadButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                        this.uploader.startUpload();
                    }, this));
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                        this.close();
                    }, this));
                    this.commitButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                        this.commit();
                    }, this));
                    this.subscriptions.add(Upload.EventsHub.setCommandStateSubscribe(() => {
                        this.setCommandState();
                    }));
                    this.uploader_init();
                    this.toolbar_init();
                    this.progressbar_init();
                    this.list_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setButtonDisplay();
                    this.setPendingUploadMessage();
                    this.setCommandState();
                }
                commit() {
                    let files = this.uploader.files.toArray()
                        .filter(item => item.status == plupload.FileStatus.DONE)
                        .map(item => item.toJSON());
                    this.commit_serviceCall(this.folderId, files);
                }
                list_init() {
                    this.list = new Upload.UploadList({
                        insertAt: "div[role=list]",
                        items: this.uploader.files.transform(item => {
                            return item.toJSON();
                        }),
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.list);
                }
                progressbar_init() {
                    this.progressbar = new PDJS.Shared.UI.Controls.ProgressBar({
                        insertAt: "div[role=deck-l]",
                        showMessage: true,
                        backgroundColor: "var(--visiv-theme-progress-success-back-color)",
                        color: "var(--visiv-theme-progress-success-text-color)",
                        height: "22px",
                    });
                    this.controls.add(this.progressbar);
                }
                toolbar_init() {
                    this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Upload.UploaderToolbar()]
                    });
                    this.controls.add(this.toolbar);
                }
                uploader_init() {
                    this.uploader.onQueueChangedCallback = (sender, e) => {
                        this.setButtonDisplay();
                    };
                    this.uploader.onBeforeUploadCallback = (sender, e) => {
                        this.setButtonDisplay();
                    };
                    this.uploader.onFileUploadedCallback = (sender, e) => {
                        let data = JSON.parse(JSON.stringify(e));
                        this.list.updateItem(data);
                    };
                    this.uploader.onUploadProgressCallback = (sender, e) => {
                        this.list.updateItem(e);
                        this.progressbar.update({
                            message: `Uploading file "${e.name}...`,
                            percent: this.uploader.totalPercent
                        });
                    };
                    this.uploader.onUploadCompleteCallback = (sender, e) => {
                        let failedCount = this.uploader.files
                            .getByStatus(plupload.FileStatus.FAILED).count;
                        let doneCount = this.uploader.files
                            .getByStatus(plupload.FileStatus.DONE).count;
                        let message = failedCount > 0 ?
                            `Uploaded ${doneCount} files, ${failedCount} files failed.` :
                            `Uploaded all ${this.uploader.files.count} file(s).`;
                        this.progressbar.update({
                            message: message,
                            percent: 0
                        });
                        this.setButtonDisplay();
                        if (this.uploader.commitAfterUpload) {
                            this.commit();
                        }
                    };
                    this.uploader.onFileRemovedCallback = (sender, e) => {
                        this.setButtonDisplay();
                    };
                    this.uploader.onFilesAddedCallback = (sender, e) => {
                        e.each(file => {
                            this.list.addItem(file);
                        });
                        this.setPendingUploadMessage();
                        this.setButtonDisplay();
                        this.setCommandState();
                    };
                    this.uploader.onErrorCallback = (sender, e) => {
                        Jade.UI.Dialogs.MessageDialog.open({
                            dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                            allowClose: true,
                            title: e.title,
                            message: e.message,
                            select: (e) => {
                                e.close();
                            }
                        });
                        this.setPendingUploadMessage();
                    };
                }
                setButtonDisplay() {
                    this.setUploadButtonDisplay();
                    this.setCancelButtonDisplay();
                    this.setCommitButtonDisplay();
                }
                setUploadButtonDisplay() {
                    let isVisible = this.uploader.files.queued.count > 0
                        || this.uploader.files.uploading.count > 0
                        || this.uploader.files.count === 0;
                    let isEnabled = this.uploader.files.queued.count > 0
                        && !this.uploader.isUploading;
                    isVisible ?
                        this.uploadButtonNode.show() :
                        this.uploadButtonNode.hide();
                    this.uploadButtonNode.prop("disabled", !isEnabled);
                }
                setCancelButtonDisplay() {
                    this.cancelButtonNode.text("Close");
                    this.cancelButtonNode.prop("disabled", this.uploader.isUploading);
                }
                setCommitButtonDisplay() {
                    let isVisible = this.uploader.files.count > 0 &&
                        this.uploader.files.done.count == this.uploader.files.count &&
                        !this.uploader.commitAfterUpload;
                    isVisible ?
                        this.commitButtonNode.show() :
                        this.commitButtonNode.hide();
                    this.commitButtonNode.prop("disabled", this.uploader.isUploading);
                }
                setCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/shared/upload": {
                            $uploader: this.uploader,
                            $list: this.list,
                            $progressbar: this.progressbar
                        }
                    }, { force: true });
                }
                setPendingUploadMessage() {
                    this.progressbar.update({
                        message: `Pending upload of ${this.uploader.files.count} files.`,
                        percent: 0
                    });
                }
                commit_serviceCall(folderId, files) {
                    let service = new PDJS.Services.Resources.ResourcesService();
                    let indexFileCount = 1;
                    this.progressbar.update({
                        message: `Saving files ...`,
                        percent: 0
                    });
                    files.forEach(file => {
                        this.list.updateItem({
                            id: file.id,
                            status: plupload.FileStatus.QUEUED
                        });
                    });
                    service.addFiles({
                        folderId: folderId,
                        files: files,
                        success: (e) => {
                            this.close();
                            this.uploader.onCommitSuccessCallback(this, e.data);
                        },
                        onFileUploadConflicts: (e) => {
                            this.commit_handleConflicts(e);
                        },
                        onFileUploadErrors: (e) => {
                            e.forEach(error => {
                                this.list.updateItem({
                                    id: error.file.id,
                                    status: plupload.FileStatus.FAILED
                                }, error.message);
                            });
                            this.progressbar.update({
                                backgroundColor: "var(--visiv-theme-progress-error-back-color)",
                                color: "var(--visiv-theme-progress-error-text-color)",
                            });
                        },
                        onFileSaveFailure: (e) => {
                            this.list.updateItem({
                                id: e.id,
                                status: plupload.FileStatus.FAILED
                            });
                            this.progressbar.update({
                                message: `Failed to save file "${e.name}"...`,
                                percent: (indexFileCount / files.length) * 100
                            });
                            indexFileCount += 1;
                        },
                        onFileSaveSuccess: (e) => {
                            this.list.updateItem({
                                id: e.id,
                                status: plupload.FileStatus.DONE
                            });
                            this.progressbar.update({
                                message: `Saved file "${e.name}"...`,
                                percent: (indexFileCount / files.length) * 100
                            });
                            indexFileCount += 1;
                        }
                    });
                }
                commit_handleConflicts(conflicts, handled = []) {
                    var _a;
                    if (conflicts.length == 0 && handled.length > 0) {
                        this.commit_serviceCall(this.folderId, handled);
                        return;
                    }
                    let file = (_a = _.first(conflicts)) === null || _a === void 0 ? void 0 : _a.file;
                    let resolveCurrent = (fileId, action) => {
                        file.fileMode = action;
                        conflicts = conflicts.filter(item => item.file.id != fileId);
                        handled.push(file);
                        this.commit_handleConflicts(conflicts, handled);
                    };
                    let resolveRemaining = (action) => {
                        conflicts.forEach(item => {
                            item.file.fileMode = action;
                            handled.push(item.file);
                        });
                        conflicts = [];
                        this.commit_handleConflicts(conflicts, handled);
                    };
                    Upload.ConflictDialog.open({
                        fileName: file.name,
                        select: {
                            ok: (sender, e) => {
                                setTimeout(() => {
                                    e.repeat ?
                                        resolveRemaining(e.action) :
                                        resolveCurrent(file.id, e.action);
                                }, 500);
                            }
                        }
                    });
                }
                static open(options) {
                    if (this.instance == null) {
                        if (options.callbacks == null) {
                            options.callbacks = {};
                        }
                        for (let key in options.callbacks) {
                            let callback = options.callbacks[key];
                            if (_.isFunction(callback)) {
                                options.callbacks[key] = (sender, e) => {
                                    this.instance = null;
                                    callback(sender, e);
                                };
                            }
                        }
                        if (_.isEmpty(options.callbacks)) {
                            options.callbacks.cancel = (sender, e) => {
                                this.instance = null;
                            };
                        }
                        this.instance = new UploadDialog(options);
                    }
                    return this.instance;
                }
            }
            Upload.UploadDialog = UploadDialog;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploadFileDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options, windowOptions = {}) {
                    super(options);
                }
                get message() {
                    return this.state.get("message", "Select a file to upload.");
                }
                get mimeTypes() {
                    return this.state.get("mimeTypes", []);
                }
                get uploadId() {
                    return this.state.get("uploadId");
                }
                set uploadId(value) {
                    this.state.set("uploadId", value);
                }
                get uploadName() {
                    return this.state.get("uploadName");
                }
                set uploadName(value) {
                    this.state.set("uploadName", value);
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=cancel]");
                }
                template() {
                    return super.template(`<div class="-pdjs-shared-dialogs-upload-file-dialog">
                                        <div role="text">${this.message}</div>
                                        <div role="progress"></div>
                                        <div role="buttons">
                                            <button class="-pdjs-dialog-button" data-id="ok" disabled>OK</button>
                                            <button class="-pdjs-dialog-button" data-id="cancel">Cancel</button>
                                        </div>
                                    </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close({
                            name: "ok",
                            data: {
                                uploadId: this.uploadId,
                                uploadName: this.uploadName
                            }
                        });
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.close();
                    });
                    this.upload_init();
                }
                getDefaultOptions() {
                    return {
                        title: "Upload File Dialog",
                        width: "400px",
                        maximized: false,
                        resizable: false
                    };
                }
                upload_init() {
                    this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                        insertAt: "div[role=progress]",
                        mimeTypes: this.mimeTypes,
                        onFileSelected: (e) => {
                        },
                        onUploadStart: (e) => {
                            this.okButtonNode.attr("disabled", "disabled");
                        },
                        onUploadComplete: (e) => {
                            this.uploadId = `${e.id}${e.extension}`;
                            this.uploadName = e.name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options = {}) {
                    return new UploadFileDialog(options);
                }
            }
            Upload.UploadFileDialog = UploadFileDialog;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploadList extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get list() {
                    return this.m_list;
                }
                set list(value) {
                    this.m_list = value;
                }
                get items() {
                    return this.state.get("items", []);
                }
                get selected() {
                    return this.getSelected();
                }
                templateContent() {
                    return `<div class="-pdjs-shared-upload-list"></div>`;
                }
                addItem(file) {
                    let control = this.list.addItem(file.toJSON());
                    control.node.get(0).scrollIntoView({
                        behavior: "smooth",
                        block: "end"
                    });
                    this.changeCallback();
                }
                updateItem(file, message = null) {
                    let item = this.getListItem(file.id);
                    if (item) {
                        item.update(file, message);
                        if (item.percent == 0) {
                            item.node.get(0).scrollIntoView({
                                behavior: "smooth",
                                block: "end"
                            });
                        }
                    }
                }
                removeItem(value) {
                    this.list.removeItem(value);
                    this.changeCallback();
                }
                getSelected() {
                    let result = [];
                    this.list.selected.each(item => {
                        result.push(item);
                    });
                    return result;
                }
                clear() {
                    this.list.removeAll();
                    this.changeCallback();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.list_init();
                }
                onStateChanged() {
                    super.onStateChanged();
                }
                list_init() {
                    this.list = new PDJS.Shared.UI.Controls.ListView({
                        height: "100%",
                        binding: { value: "id" },
                        data: this.items,
                        selectMode: PDJS.Shared.UI.Controls.ListViewSelectMode.multiple,
                        allowRemove: false,
                        items: this.items,
                        noItemsMessage: "No files are in the upload queue.",
                        createItem: (e) => {
                            return new Upload.UploadListItem(e);
                        },
                        change: () => {
                            Upload.EventsHub.setCommandStatePublish();
                        }
                    });
                    this.controls.add(this.list);
                }
                getListItem(value) {
                    return _.first(this.list.items.toArray()
                        .filter(item => {
                        return item.data.value == value;
                    }));
                }
            }
            Upload.UploadList = UploadList;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploadListItem extends Shared.UI.Controls.ListViewItem {
                get message() {
                    return this.m_message;
                }
                set message(value) {
                    this.m_message = value;
                }
                get name() {
                    return this.data.get("name");
                }
                get progress() {
                    return this.m_progress;
                }
                set progress(value) {
                    this.m_progress = value;
                }
                get percent() {
                    return this.data.get("percent", 0);
                }
                get status() {
                    return this.data.get("status", 0);
                }
                get statusImageNode() {
                    return this.node.find("div[role=status] img");
                }
                templateContent() {
                    let iconPath = Jade.IconSet.get("pdv2")
                        .resolve("document_empty.png", Jade.IconSetSizeSpecificDirectory.x32);
                    return `<div class="-pdjs-shared-upload-list-item">
                        <div>
                            <div role="contents">
                                <div role="icon">
                                    <img src="${iconPath}"/>
                                </div>
                                <div role="label-progress">
                                    <div role="label">${this.name}</div>
                                    <div role="progress"></div>
                                </div>
                                <div role="status">
                                    <div>
                                        <img src="${iconPath}"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>`;
                }
                update(data, message = null) {
                    this.data.state.set(data);
                    this.message = message;
                    Jade.String.isNullOrWhiteSpace(this.message) ?
                        Tipped.disable(this.statusImageNode) :
                        Tipped.enable(this.statusImageNode);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.progress_init();
                    PDJS.Shared.PopOver.tooltip(this.statusImageNode, `<div>${this.message}</div>`, {
                        onShow: (content, element) => {
                            content.innerHTML = `<div>${this.message}</div>`;
                            PDJS.Shared.PopOver.refresh(this.statusImageNode.get(0));
                        }
                    });
                }
                onStateChanged() {
                    super.onStateChanged();
                    let icon = null;
                    switch (this.status) {
                        case plupload.FileStatus.DONE:
                            icon = "ok.png";
                            break;
                        case plupload.FileStatus.FAILED:
                            icon = "sign_warning.png";
                            break;
                        case plupload.FileStatus.QUEUED:
                            icon = "hourglass.png";
                            break;
                        case plupload.FileStatus.UPLOADING:
                            icon = "loading-animated.gif";
                            break;
                    }
                    if (this.statusImageNode.attr("status") != this.status.toString()) {
                        this.statusImageNode.attr("status", this.status);
                        this.statusImageNode.attr("src", this.getIcon24(icon));
                    }
                    this.progress.percent = this.percent;
                    this.node.find("div[role=icon]").show();
                }
                progress_init() {
                    this.progress = new PDJS.Shared.UI.Controls.ProgressBar({
                        insertAt: "div[role=progress]",
                        showMessage: false,
                        backgroundColor: "var(--visiv-theme-progress-success-back-color)",
                        color: "var(--visiv-theme-progress-success-text-color)",
                        height: "3px",
                        borderColor: "var(--visiv-theme-input-border-color)"
                    });
                    this.controls.add(this.progress);
                }
                getIcon24(image) {
                    return Jade.IconSet.get("pdjs")
                        .resolve(image, Jade.IconSetSizeSpecificDirectory.x24);
                }
            }
            Upload.UploadListItem = UploadListItem;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            let UploaderStatus;
            (function (UploaderStatus) {
                UploaderStatus[UploaderStatus["STARTED"] = 1] = "STARTED";
                UploaderStatus[UploaderStatus["STOPPED"] = 2] = "STOPPED";
                UploaderStatus[UploaderStatus["UPLOADING"] = 3] = "UPLOADING";
            })(UploaderStatus = Upload.UploaderStatus || (Upload.UploaderStatus = {}));
            ;
            class UploaderBase extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.onInitialize();
                    this.ID = Jade.Guid.new();
                }
                get files() {
                    return new Upload.UploaderFileCollection(this.uploader.files, {
                        onAfterRemove: (e) => {
                            this.uploader.removeFile(e.item);
                        }
                    });
                }
                get ID() {
                    return this.state.get("id");
                }
                set ID(value) {
                    this.state.set("id", value);
                }
                get isInitialized() {
                    return this.containerNode.hasClass("--uploader-initialized");
                }
                get isStarted() {
                    return this.status === UploaderStatus.STARTED;
                }
                get isStopped() {
                    return this.status === UploaderStatus.STOPPED;
                }
                get isUploading() {
                    return this.status === UploaderStatus.UPLOADING;
                }
                get mimeTypes() {
                    return this.state.get("mimeTypes", []);
                }
                get multiSelect() {
                    return this.state.get("multiSelect", true);
                }
                get onBeforeUploadCallback() {
                    return this.state.get("onBeforeUpload", () => { });
                }
                set onBeforeUploadCallback(value) {
                    this.state.set("onBeforeUpload", value);
                }
                get onBrowseCallback() {
                    return this.state.get("onBrowse", () => { });
                }
                set onBrowseCallback(value) {
                    this.state.set("onBrowse", value);
                }
                get onErrorCallback() {
                    return this.state.get("onError", _.bind(this.defaultErrorHandler, this));
                }
                set onErrorCallback(value) {
                    this.state.set("onError", value);
                }
                get onFileRemovedCallback() {
                    return this.state.get("onFileRemoved", () => { });
                }
                set onFileRemovedCallback(value) {
                    this.state.set("onFileRemoved", value);
                }
                get onFilesAddedCallback() {
                    return this.state.get("onFilesAdded", () => { });
                }
                set onFilesAddedCallback(value) {
                    this.state.set("onFilesAdded", value);
                }
                get onFileUploadedCallback() {
                    return this.state.get("onFileUploaded", () => { });
                }
                set onFileUploadedCallback(value) {
                    this.state.set("onFileUploaded", value);
                }
                get onQueueChangedCallback() {
                    return this.state.get("onQueueChanged", () => { });
                }
                set onQueueChangedCallback(value) {
                    this.state.set("onQueueChanged", value);
                }
                get onUploadProgressCallback() {
                    return this.state.get("onUploadProgress", () => { });
                }
                set onUploadProgressCallback(value) {
                    this.state.set("onUploadProgress", value);
                }
                get onUploadCompleteCallback() {
                    return this.state.get("onUploadComplete", () => { });
                }
                set onUploadCompleteCallback(value) {
                    this.state.set("onUploadComplete", value);
                }
                get status() {
                    return this.m_status;
                }
                set status(value) {
                    this.m_status = value;
                }
                get totalPercent() {
                    return this.state.get("totalPercent", 0);
                }
                set totalPercent(value) {
                    this.state.set("totalPercent", value);
                }
                get uploader() {
                    return this.m_uploader;
                }
                set uploader(value) {
                    this.m_uploader = value;
                }
                get uploadState() {
                    return this.uploader.state;
                }
                get containerNode() {
                    return this.state.get("containerNode");
                }
                get dropNode() {
                    return this.state.get("dropNode", $());
                }
                get selectButtonNode() {
                    return this.state.get("selectButtonNode");
                }
                onBrowse(sender) {
                    this.onBrowseCallback(this);
                    this.onUploaderStateChange();
                }
                onBeforeUpload(sender, e) {
                    this.onBeforeUploadCallback(this, new Upload.UploaderFile(e));
                    this.onUploaderStateChange();
                }
                onError(sender, e) {
                    this.uploader.stop();
                    this.onErrorCallback(this, new Upload.UploaderError(e));
                    this.onUploaderStateChange();
                }
                onFileUploaded(sender, e) {
                    this.onFileUploadedCallback(this, new Upload.UploaderFile(e));
                    this.onUploaderStateChange();
                }
                onFilesAdded(sender, e) {
                    this.onFilesAddedCallback(this, new Upload.UploaderFileCollection(e));
                    this.onUploaderStateChange();
                }
                onFileRemoved(sender, e) {
                    this.onFileRemovedCallback(this, new Upload.UploaderFile(e));
                    this.onUploaderStateChange();
                }
                onQueueChanged(sender, e) {
                    this.onQueueChangedCallback(this, this.files);
                    this.onUploaderStateChange();
                }
                onUploadComplete(sender, e) {
                    this.uploader.stop();
                    this.status = UploaderStatus.STOPPED;
                    this.onUploadCompleteCallback(this, new Upload.UploaderFileCollection(e));
                    this.onUploaderStateChange();
                }
                onUploadProgress(sender, e) {
                    this.totalPercent = sender.total.percent;
                    this.status = UploaderStatus.UPLOADING;
                    this.onUploadProgressCallback(this, e);
                }
                onUploaderStateChange() {
                }
                init() {
                    this.uploader.init();
                }
                startUpload() {
                    this.uploader.start();
                    this.status = UploaderStatus.STARTED;
                }
                stopUpload() {
                    this.uploader.stop();
                    this.status = UploaderStatus.STOPPED;
                }
                showOpenDialog() {
                    this.containerNode.find('div.moxie-shim input[type=file]').trigger('click');
                }
                clear() {
                    this.uploader.files.slice(0).reverse().forEach(item => {
                        this.uploader.removeFile(item);
                    });
                }
                refresh() {
                    this.uploader.refresh();
                }
                removeFile(fileId) {
                    this.uploader.removeFile({
                        id: fileId
                    });
                }
                onInitialize() {
                    if (this.isInitialized) {
                        return;
                    }
                    this.uploader = new plupload.Uploader({
                        runtimes: "html5,silverlight,flash,html4",
                        container: this.containerNode.get(0),
                        browse_button: this.selectButtonNode.get(0),
                        drop_element: this.dropNode.length > 0 ? this.dropNode.get(0) : undefined,
                        urlstream_upload: true,
                        multi_selection: this.multiSelect,
                        max_file_size: "2gb",
                        max_file_count: 100,
                        filters: {
                            mime_types: this.mimeTypes
                        },
                        chunk_size: "1024kb",
                        unique_names: true,
                        url: Jade.Path.resolve("~/application/handlers/Uploads.ashx"),
                        flash_swf_url: Jade.Path.resolve("~/areas/shared/assets/external/misc/plupload/moxie.swf"),
                        silverlight_xap_url: Jade.Path.resolve("~/areas/shared/assets/external/misc/plupload/moxie.xap")
                    });
                    this.onRegisterEventHandlers();
                    this.init();
                    this.refresh();
                    this.stopUpload();
                    this.containerNode.addClass("--uploader-initialized");
                }
                onRegisterEventHandlers() {
                    this.uploader.bind(plupload.UploaderEvent.BeforeUpload, _.bind(this.onBeforeUpload, this));
                    this.uploader.bind(plupload.UploaderEvent.Browse, _.bind(this.onBrowse, this));
                    this.uploader.bind(plupload.UploaderEvent.Error, _.bind(this.onError, this));
                    this.uploader.bind(plupload.UploaderEvent.FilesAdded, _.bind(this.onFilesAdded, this));
                    this.uploader.bind(plupload.UploaderEvent.FileRemoved, _.bind(this.onFileRemoved, this));
                    this.uploader.bind(plupload.UploaderEvent.FileUploaded, _.bind(this.onFileUploaded, this));
                    this.uploader.bind(plupload.UploaderEvent.QueueChanged, _.bind(this.onQueueChanged, this));
                    this.uploader.bind(plupload.UploaderEvent.UploadComplete, _.bind(this.onUploadComplete, this));
                    this.uploader.bind(plupload.UploaderEvent.UploadProgress, _.bind(this.onUploadProgress, this));
                }
                defaultErrorHandler(sender, e) {
                    Jade.UI.Dialogs.MessageDialog.open({
                        dialogStyle: Jade.UI.Dialogs.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.Dialogs.MessageDialogButtonStyle.OK,
                        message: e.message,
                        title: "Upload | Error"
                    });
                }
                static create(options) {
                    let container = options.containerNode;
                    let uploadIdAttr = container.attr("upload-id");
                    let uploadId = uploadIdAttr == null ?
                        Jade.Guid.new() : uploadIdAttr;
                    this.m_registrations[uploadId] == null ?
                        this.m_registrations[uploadId] = new Upload.Uploader(options) : null;
                    return this.m_registrations[uploadId];
                }
                static destroy(container) {
                    let uploadId = container.attr("upload-id");
                    if (this.m_registrations[uploadId]) {
                        this.m_registrations[uploadId].destroy();
                    }
                }
            }
            UploaderBase.m_registrations = {};
            Upload.UploaderBase = UploaderBase;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class Uploader extends Upload.UploaderBase {
                constructor(options) {
                    super(options);
                }
                get folderId() {
                    let result = this.state.get("folderId");
                    return _.isFunction(result) ? result() : result;
                }
                get commitAfterUpload() {
                    return this.state.get("commitAfterUpload", true);
                }
                get onOpenUploadDialogCallback() {
                    return this.state.get("onOpenUploadDialog", (sender) => {
                        this.openUploadDialog();
                    });
                }
                set onOpenUploadDialogCallback(value) {
                    this.state.set("onOpenUploadDialog", value);
                }
                get onCommitSuccessCallback() {
                    return this.state.get("onCommitSuccess", (sender) => { });
                }
                set onCommitSuccessCallback(value) {
                    this.state.set("onCommitSuccess", value);
                }
                onFilesAdded(sender, e) {
                    super.onFilesAdded(sender, e);
                    setTimeout(() => {
                        this.onOpenUploadDialogCallback(this);
                    }, 250);
                }
                onUploaderStateChange() {
                    Upload.EventsHub.setCommandStatePublish();
                }
                openUploadDialog() {
                    PDJS.Shared.Upload.UploadDialog.open({
                        $uploader: this
                    });
                }
            }
            Upload.Uploader = Uploader;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderCommand extends Jade.Command {
                constructor() {
                    super({});
                    this.state.set("$uploader", null);
                    this.state.set("$list", null);
                    this.state.set("$progressbar", null);
                }
                get uploader() {
                    return this.state.get("$uploader");
                }
                get list() {
                    return this.state.get("$list");
                }
                get progressbar() {
                    return this.state.get("$progressbar");
                }
                setCommandState() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "pdjs/shared/upload": {
                            $uploader: this.uploader,
                            $list: this.list,
                            $progressbar: this.progressbar
                        }
                    }, { force: true });
                }
            }
            Upload.UploaderCommand = UploaderCommand;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class AddFilesCommand extends Upload.UploaderCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.uploader.status != Upload.UploaderStatus.UPLOADING;
                }
                execute(e) {
                    this.uploader.showOpenDialog();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "uploader/add-files",
                        label: "Add Files",
                        icon: "documents_empty_plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Upload.AddFilesCommand = AddFilesCommand;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class RemoveFilesCommand extends Upload.UploaderCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.uploader.status != Upload.UploaderStatus.UPLOADING
                        && this.list.selected.length > 0;
                }
                execute(e) {
                    let selected = [];
                    this.list.selected.forEach(item => {
                        this.list.removeItem(item.value);
                        selected.push(item.toJSON());
                    });
                    selected.forEach(item => {
                        this.uploader.removeFile(item.id);
                    });
                    let queuedFileCount = this.uploader.files.queued.count;
                    this.progressbar.update({
                        message: `Pending upload of ${queuedFileCount} files.`
                    });
                    this.setCommandState();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "uploader/remove-files",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
            }
            Upload.RemoveFilesCommand = RemoveFilesCommand;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class ClearFilesCommand extends Upload.UploaderCommand {
                setState(state) {
                    super.setState(state);
                    this.enabled = this.uploader.status != Upload.UploaderStatus.UPLOADING
                        && this.uploader.files.count > 0;
                }
                execute(e) {
                    this.list.clear();
                    this.uploader.clear();
                    this.progressbar.update({
                        message: "Pending add files."
                    });
                    this.setCommandState();
                }
                getDefaultValuesForProps() {
                    return {
                        id: "uploader/clear-files",
                        label: "Clear",
                        icon: "Eraser.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Upload.ClearFilesCommand = ClearFilesCommand;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderCommands extends Jade.CommandGroup {
                constructor() {
                    super("pdjs/shared/upload");
                }
                registerCommands(e) {
                    e.commands.add(new Upload.AddFilesCommand());
                    e.commands.add(new Upload.RemoveFilesCommand());
                    e.commands.add(new Upload.ClearFilesCommand());
                }
            }
            Upload.UploaderCommands = UploaderCommands;
            Jade.CommandGroups.add(UploaderCommands);
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderFile extends PDJS.Core.Upload.UploadFile {
            }
            Upload.UploaderFile = UploaderFile;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderFileCollection extends Jade.ObservableCollection {
                constructor(data = [], callbacks) {
                    super([], callbacks);
                    data.forEach(item => {
                        this.add(new Upload.UploaderFile(item));
                    });
                }
                get done() {
                    return this.getByStatus(plupload.FileStatus.DONE);
                }
                get failed() {
                    return this.getByStatus(plupload.FileStatus.FAILED);
                }
                get queued() {
                    return this.getByStatus(plupload.FileStatus.QUEUED);
                }
                get uploading() {
                    return this.getByStatus(plupload.FileStatus.UPLOADING);
                }
                zeroLengthFiles() {
                    let result = new UploaderFileCollection();
                    this.each(file => {
                        if (file.size === 0) {
                            result.add(file);
                        }
                    });
                    return result;
                }
                removeById(id) {
                    let target = null;
                    this.each(file => {
                        if (file.id === id) {
                            target = file;
                            return false;
                        }
                    });
                    if (target != null) {
                        this.remove(target);
                    }
                }
                getById(id) {
                    let result;
                    this.each(file => {
                        if (file.id === id) {
                            result = file;
                            return false;
                        }
                    });
                    return result;
                }
                getByStatus(...status) {
                    let result = new UploaderFileCollection();
                    this.each((file) => {
                        if (status.indexOf(file.status) > -1) {
                            result.add(file);
                        }
                    });
                    return result;
                }
                truncate(size) {
                    if (this.innerList.length >= size) {
                        let list = this.innerList.slice(0, size);
                        this.clear();
                        list.forEach(item => {
                            this.add(item);
                        });
                    }
                }
            }
            Upload.UploaderFileCollection = UploaderFileCollection;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/shared/upload:uploader/add-files"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/shared/upload:uploader/remove-files"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/shared/upload:uploader/clear-files"
                    }));
                }
            }
            Upload.UploaderToolbar = UploaderToolbar;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            class UploaderError extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    if (options.file) {
                        this.m_file = new Upload.UploaderFile(options.file);
                        this.m_file.status = plupload.FileStatus.FAILED;
                        this.state.unset("file");
                    }
                    this.m_detail = Upload.UploaderErrorDetails.resolveError(this.code);
                    this.setMessage(options.response);
                }
                get code() {
                    return this.state.get("code");
                }
                get detail() {
                    return Upload.UploaderErrorDetails.resolveError(this.code);
                }
                get file() {
                    return this.m_file;
                }
                get message() {
                    return this.state.get("message");
                }
                set message(value) {
                    this.state.set("message", value);
                }
                get response() {
                    return this.m_response;
                }
                get title() {
                    return this.detail.title;
                }
                setMessage(response) {
                    var _a, _b;
                    try {
                        this.message = (_b = (_a = JSON.parse(response)) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.message;
                    }
                    catch (ex) {
                        this.message = this.file ?
                            this.detail.message.replace("{FILE_NAME}", this.file.name) : this.detail.message;
                    }
                }
            }
            Upload.UploaderError = UploaderError;
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Upload;
        (function (Upload) {
            let ErrorDetailType;
            (function (ErrorDetailType) {
                ErrorDetailType[ErrorDetailType["HTTP_ERROR"] = 400] = "HTTP_ERROR";
                ErrorDetailType[ErrorDetailType["CANNOT_READ_FILE"] = -300] = "CANNOT_READ_FILE";
                ErrorDetailType[ErrorDetailType["FILE_TOO_LARGE"] = -600] = "FILE_TOO_LARGE";
                ErrorDetailType[ErrorDetailType["INVALID_EXTENSION"] = -601] = "INVALID_EXTENSION";
                ErrorDetailType[ErrorDetailType["MAX_FILE_COUNT_EXCEEDED"] = 1000] = "MAX_FILE_COUNT_EXCEEDED";
            })(ErrorDetailType = Upload.ErrorDetailType || (Upload.ErrorDetailType = {}));
            class UploaderErrorDetails extends PDJS.Core.Upload.UploadFile {
                static get errors() {
                    return this.m_errors;
                }
                static addErrorDetail(error) {
                    this.errors[error.code] = error;
                }
                static resolveError(errorType) {
                    return this.errors[errorType] || this.errors[400];
                }
            }
            UploaderErrorDetails.m_errors = {};
            Upload.UploaderErrorDetails = UploaderErrorDetails;
            UploaderErrorDetails.addErrorDetail({
                code: ErrorDetailType.HTTP_ERROR,
                message: "Upload Error.",
                title: "Upload Error"
            });
            UploaderErrorDetails.addErrorDetail({
                code: ErrorDetailType.INVALID_EXTENSION,
                message: `The file "{FILE_NAME}" is being used by another process and cannot be uploaded.<br/><br/>
                This may be due to the file be open for editing in another program.`,
                title: "Cannot Read File"
            });
            UploaderErrorDetails.addErrorDetail({
                code: ErrorDetailType.FILE_TOO_LARGE,
                message: `The file "{FILE_NAME}" exceeds the maximum allowed size of 2 GB and cannot be uploaded.`,
                title: "File Size Exceeded"
            });
            UploaderErrorDetails.addErrorDetail({
                code: ErrorDetailType.CANNOT_READ_FILE,
                message: `The file "{FILE_NAME}" is being used by another process and cannot be uploaded.<br/><br/>
                This may be due to the file being open for editing in another program.`,
                title: "Cannot Read File"
            });
            UploaderErrorDetails.addErrorDetail({
                code: ErrorDetailType.MAX_FILE_COUNT_EXCEEDED,
                message: `More files than are allowed have been selected for upload. 
                Not all the files you selected have been added to the queue.`,
                title: "File Upload Limit Exceeded"
            });
        })(Upload = Shared.Upload || (Shared.Upload = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let Events;
            (function (Events) {
                Events["ColumnNameChanged"] = "ColumnNameChanged";
                Events["FinderParamsChanged"] = "FinderParamsChanged";
                Events["FinderSettingsChanged"] = "FinderSettingsChanged";
                Events["EntTypeAnchorsChanged"] = "EntTypeAnchorsChanged";
                Events["DocTypeAnchorsChanged"] = "DocTypeAnchorsChanged";
            })(Events = Views.Events || (Views.Events = {}));
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static columnNameChangedPublish() {
                    this.current.publish(Events.ColumnNameChanged);
                }
                static documentTypeAnchorsChangedPublish() {
                    this.current.publish(Events.DocTypeAnchorsChanged);
                }
                static entityTypeAnchorsChangedPublish() {
                    this.current.publish(Events.EntTypeAnchorsChanged);
                }
                static finderParamsChangedPublish(e) {
                    this.current.publish(Events.FinderParamsChanged, e);
                }
                static finderSettingsChangedPublish() {
                    this.current.publish(Events.FinderSettingsChanged);
                }
                static columnNameChangedSubscribe(handler) {
                    return this.current.subscribe(Events.ColumnNameChanged, handler);
                }
                static documentTypeAnchorsChangedSubscribe(handler) {
                    return this.current.subscribe(Events.DocTypeAnchorsChanged, handler);
                }
                static entityTypeAnchorsChangedSubscribe(handler) {
                    return this.current.subscribe(Events.EntTypeAnchorsChanged, handler);
                }
                static finderParamsChangedSubscribe(handler) {
                    return this.current.subscribe(Events.FinderParamsChanged, handler);
                }
                static finderSettingsChangedSubscribe(handler) {
                    return this.current.subscribe(Events.FinderSettingsChanged, handler);
                }
            }
            Views.EventsHub = EventsHub;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AnchorsCommands extends Jade.CommandGroup {
                constructor() {
                    super("view/anchors");
                }
                registerCommands(e) {
                    e.commands.add(new Views.AddEntTypeAnchorsCommand({}));
                    e.commands.add(new Views.ClearEntTypeAnchorsCommand({}));
                }
            }
            Views.AnchorsCommands = AnchorsCommands;
            Jade.Application.onStart(() => {
                Jade.CommandGroups.add(AnchorsCommands);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("viewStateId", null);
                    this.state.set("foundAnchors", null);
                    this.state.set("addedAnchors", null);
                    this.state.set("addedAnchorsAll", null);
                    this.state.set("$editorGrid", null);
                    this.state.set("$finderGrid", null);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get foundAnchors() {
                    return this.state.get("foundAnchors", []);
                }
                get addedAnchors() {
                    return this.state.get("addedAnchors", []);
                }
                get addedAnchorsAll() {
                    return this.state.get("addedAnchorsAll", []);
                }
                get editorGrid() {
                    return this.state.get("$editorGrid");
                }
                get finderGrid() {
                    return this.state.get("$finderGrid");
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Views.DocTypeAnchorsCommand = DocTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsCommands extends Jade.CommandGroup {
                constructor() {
                    super("view/document-type-anchors");
                }
                registerCommands(e) {
                    e.commands.add(new Views.AddDocTypeAnchorsCommand({}));
                    e.commands.add(new Views.RemoveDocTypeAnchorsCommand({}));
                    e.commands.add(new Views.ClearDocTypeAnchorsCommand({}));
                }
            }
            Views.DocTypeAnchorsCommands = DocTypeAnchorsCommands;
            Jade.Application.onStart(() => {
                Jade.CommandGroups.add(DocTypeAnchorsCommands);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get toolbarNode() {
                    return this.node.children("div[role=toolbar]");
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get headerNode() {
                    return this.node.children("div[role=header]");
                }
                get columns() {
                    return this.m_grid.get_dataSource().data();
                }
                template() {
                    return `
                <div class="-pdjs-view-document-type-anchors-editor">
                    <div role="toolbar"></div>
                    <div role="header"></div>
                    <div role="content" data-controls></div>
                </div>`;
                }
                save() {
                    let result = this.m_grid.get_dataSource().get_instance().data().toJSON();
                    return result;
                }
                load(data) {
                    if (_.isArray(data)) {
                        let dataSource = this.m_grid.get_dataSource().get_instance();
                        dataSource.data(data);
                        this.m_grid.refresh();
                    }
                    this.updateContextState();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.toolbar_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        pk: "id",
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No document type anchors have been added to the view."
                        },
                        dataSource: {
                            data: [],
                            storeAsLocalVariable: true
                        },
                        height: "100%",
                        container: this.contentNode,
                        selectionMode: "multiple",
                        selectOnRightClick: false,
                        selection: {
                            mapping: (e) => {
                                return {
                                    category: e.category,
                                    name: e.name,
                                    id: e.id,
                                    uid: e.uid
                                };
                            }
                        },
                        defaultSelectionEnabled: false,
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "200px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "category",
                                title: "Category",
                                width: "300px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ],
                        change: (e) => {
                            this.updateContextState();
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.DocTypeAnchorsToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                updateContextState() {
                    if (this.m_grid == null) {
                        return;
                    }
                    let allAnchors = this.m_grid.get_dataSource().get_instance().data().toJSON();
                    let addedAnchors = this.m_grid.getSelections().toArray();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/document-type-anchors": {
                            addedAnchors: addedAnchors,
                            addedAnchorsAll: allAnchors,
                            $editorGrid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Views.DocTypeAnchorsEditor = DocTypeAnchorsEditor;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsFeature extends FeatureBlendJS.Views.MacroEditorBase {
                constructor(options) {
                    super(options);
                }
                get documentTypesViewStateId() {
                    return this.source.getFeatureValue("documentTypesViewStateId");
                }
                get viewStateId() {
                    return this.source.getFeatureValue("viewStateId");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                template() {
                    return `
                <div class="-pdjs-view-doc-type-anchors-feature">
                    <div role="content">
                        <div role="splitter">
                            <div>
                                <div role="finder"></div>
                            </div>
                            <div>
                                <div role="editor"></div>
                            </div>
                        </div>
                    </div>
                </div>`;
                }
                resize() {
                    this.m_splitter.resize(true);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.finder_init();
                    this.editor_init();
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.DocTypeAnchorsChanged, () => {
                        this.source.primaryValue =
                            this.m_editor.save();
                    }));
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.m_editor.load(this.source.primaryValue);
                }
                finder_init() {
                    this.m_finder = new Views.DocTypeAnchorsFinder({
                        insertAt: "div[role=finder]",
                        viewStateId: this.documentTypesViewStateId
                    });
                    this.controls.add(this.m_finder);
                }
                editor_init() {
                    this.m_editor = new Views.DocTypeAnchorsEditor({
                        insertAt: "div[role=editor]",
                        viewStateId: this.viewStateId
                    });
                    this.controls.add(this.m_editor);
                }
                splitter_init() {
                    this.m_splitter = this.splitterNode.kendoSplitter({
                        orientation: "vertical",
                        panes: [
                            { size: "50%", resizable: true },
                            { size: "50%", resizable: true }
                        ]
                    }).data("kendoSplitter");
                }
            }
            Views.DocTypeAnchorsFeature = DocTypeAnchorsFeature;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Views.DocTypeAnchorsFeature", DocTypeAnchorsFeature);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsFinder extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                template() {
                    return `
                <div class="-pdjs-view-doc-type-anchors-finder">
                    <div role="toolbar"></div>
                    <div role="content"></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.FinderSettingsChanged, () => {
                        this.m_grid.refresh();
                    }));
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                        viewStateId: this.viewStateId,
                        container: this.contentNode,
                        resizable: true,
                        footer: {
                            visible: false
                        },
                        selection: {
                            mapping: (e) => {
                                return {
                                    category: e.Category,
                                    name: e.Name,
                                    id: e.ObjectId,
                                    uid: e.uid
                                };
                            }
                        },
                        messaging: {
                            noRecordsMessage: "No document types are available to add."
                        },
                        selectionMode: "multiple",
                        selectOnRightClick: true,
                        defaultSelectionEnabled: false,
                        change: (e) => {
                            this.updateContextState();
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/document-type-anchors:document-type-anchor/add");
                        }
                    });
                }
                updateContextState() {
                    if (this.m_grid == null) {
                        return;
                    }
                    let foundAnchors = this.m_grid.getSelections().toArray();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/document-type-anchors": {
                            foundAnchors: foundAnchors,
                            $finderGrid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            Views.DocTypeAnchorsFinder = DocTypeAnchorsFinder;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DocTypeAnchorsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/document-type-anchors:document-type-anchor/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/document-type-anchors:document-type-anchor/remove"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/document-type-anchors:document-type-anchor/clear"
                    }));
                }
            }
            Views.DocTypeAnchorsToolbar = DocTypeAnchorsToolbar;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AddDocTypeAnchorsCommand extends Views.DocTypeAnchorsCommand {
                onExecute(e) {
                    super.onExecute(e);
                    let dataSource = this.editorGrid.get_kendo().dataSource;
                    let selected = this.foundAnchors.map((item) => {
                        return item.id;
                    });
                    this.foundAnchors.forEach(item => {
                        if (!dataSource.get(item.id)) {
                            dataSource.add(item);
                        }
                    });
                    this.finderGrid.refresh({
                        clear: true
                    });
                    this.editorGrid.refresh({
                        selections: selected
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.DocTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.foundAnchors.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document-type-anchor/add",
                        tooltip: "Add Document Type Anchor",
                        label: "Add",
                        icon: "arrow_down_green.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Views.AddDocTypeAnchorsCommand = AddDocTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ClearDocTypeAnchorsCommand extends Views.DocTypeAnchorsCommand {
                onExecute() {
                    let grid = this.editorGrid.get_kendo();
                    grid.dataSource.data([]);
                    grid.refresh();
                    this.enabled = false;
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.DocTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.addedAnchorsAll.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document-type-anchor/clear",
                        tooltip: "Clear Anchors",
                        label: "Clear",
                        icon: "eraser2.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Views.ClearDocTypeAnchorsCommand = ClearDocTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class RemoveDocTypeAnchorsCommand extends Views.DocTypeAnchorsCommand {
                onExecute() {
                    let grid = this.editorGrid.get_kendo();
                    this.addedAnchors.forEach(item => {
                        let data = grid.dataSource.get(item.id);
                        if (data) {
                            grid.dataSource.remove(data);
                        }
                    });
                    grid.refresh();
                    this.editorGrid.refresh({
                        clear: true
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.DocTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.addedAnchors.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "document-type-anchor/remove",
                        tooltip: "Remove Anchors",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Views.RemoveDocTypeAnchorsCommand = RemoveDocTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EntTypeAnchorsCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("$editor", null);
                    this.state.set("$finder", null);
                    this.state.set("$feature", null);
                }
                get foundAnchors() {
                    return this.finder.selections;
                }
                get addedAnchors() {
                    return this.editor.selections;
                }
                get editor() {
                    return this.state.get("$editor");
                }
                get finder() {
                    return this.state.get("$finder");
                }
                get feature() {
                    return this.state.get("$feature");
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/anchors": {
                            $editor: this.editor,
                            $feature: this.feature,
                            $finder: this.finder
                        }
                    }, {
                        force: true
                    });
                }
            }
            Views.EntTypeAnchorsCommand = EntTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EntTypeAnchorsEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get dataSource() {
                    return this.m_grid.get_dataSource().get_instance();
                }
                get headerNode() {
                    return this.node.children("div[role=header]");
                }
                get selections() {
                    return this.m_grid.getSelections().toArray();
                }
                get toolbarNode() {
                    return this.node.children("div[role=toolbar]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                load(data) {
                    if (data == null || !_.isArray(data)) {
                        return;
                    }
                    let anchors = [];
                    data.forEach((item, index) => {
                        anchors[anchors.length] = {
                            depth: index,
                            parts: item.slice(0)
                        };
                    });
                    this.m_grid.get_kendo().dataSource.data(anchors);
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                save() {
                    let result = [];
                    let anchors = this.m_grid.get_dataSource().get_instance().data().toJSON();
                    anchors.forEach(anchor => {
                        result[result.length] = anchor.parts;
                    });
                    return result;
                }
                template() {
                    return `
                <div class="-pdjs-view-entity-type-anchors-editor">
                    <div role="toolbar"></div>
                    <div role="header"></div>
                    <div role="content" data-controls></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.toolbar_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        pk: "id",
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No entity type anchors have been added to the view."
                        },
                        dataSource: {
                            data: [],
                            storeAsLocalVariable: true
                        },
                        height: "100%",
                        container: this.contentNode,
                        selectionMode: "none",
                        selectOnRightClick: false,
                        defaultSelectionEnabled: false,
                        resizable: true,
                        selection: {
                            mapping: (e) => {
                                return {
                                    uid: e.uid,
                                    id: e.ObjectId,
                                    parts: e.parts,
                                    depth: e.depth,
                                    path: e.path,
                                    target: e.target
                                };
                            }
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "depth",
                                title: "Depth",
                                width: "200px",
                                template: (e) => {
                                    return e.depth == 0 ? "Target" : `Ancestor ${e.depth}`;
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "path",
                                title: "Path",
                                width: "300px",
                                template: (e) => {
                                    return e.parts.map((o) => {
                                        return o.name;
                                    }).sort((a, b) => {
                                        return a.toLowerCase() < b.toLowerCase() ? 1 : 0;
                                    }).reverse().join(", ");
                                }
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ],
                        change: (e) => {
                            this.changeCallback();
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.EntTypeAnchorsToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
            }
            Views.EntTypeAnchorsEditor = EntTypeAnchorsEditor;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EntTypeAnchorsFeature extends FeatureBlendJS.Views.MacroEditorBase {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.source.getFeatureValue("viewStateId");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                template() {
                    return `
                <div class="-pdjs-view-ent-type-anchors-feature">
                    <div role="content">
                        <div role="splitter">
                            <div>
                                <div role="finder"></div>
                            </div>
                            <div>
                                <div role="editor"></div>
                            </div>
                        </div>
                    </div>
                </div>`;
                }
                resize() {
                    this.m_splitter.resize(true);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.finder_init();
                    this.editor_init();
                    this.subscriptions.add(PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.EntTypeAnchorsChanged, () => {
                        this.source.primaryValue =
                            this.m_editor.save();
                    }));
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.m_editor.load(this.source.primaryValue);
                }
                finder_init() {
                    this.m_finder = new Views.EntTypeAnchorsFinder({
                        insertAt: "div[role=finder]",
                        viewStateId: this.viewStateId,
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_finder);
                }
                editor_init() {
                    this.m_editor = new Views.EntTypeAnchorsEditor({
                        insertAt: "div[role=editor]",
                        viewStateId: this.viewStateId,
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                splitter_init() {
                    this.m_splitter = this.splitterNode.kendoSplitter({
                        orientation: "vertical",
                        panes: [
                            { size: "50%", resizable: true },
                            { size: "50%", resizable: true }
                        ]
                    }).data("kendoSplitter");
                }
                setCommandState() {
                    if (this.m_finder == null || this.m_editor == null) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/anchors": {
                            $editor: this.m_editor,
                            $finder: this.m_finder,
                            $feature: this
                        }
                    }, { force: true });
                }
            }
            Views.EntTypeAnchorsFeature = EntTypeAnchorsFeature;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Views.EntTypeAnchorsFeature", EntTypeAnchorsFeature);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EntTypeAnchorsFinder extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get dataSource() {
                    return this.m_grid.get_dataSource().get_instance();
                }
                get searchTerm() {
                    return this.state.get("searchTerm");
                }
                set searchTerm(value) {
                    this.state.set("searchTerm", value);
                }
                get selections() {
                    return this.m_grid.getSelections().toArray();
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                refresh(e = {}) {
                    this.m_grid.refresh(e);
                }
                template() {
                    return `
                <div class="-pdjs-view-ent-type-anchors-finder">
                    <div role="toolbar"></div>
                    <div role="content"></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.searchBox_init();
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.contentNode,
                        pk: "id",
                        resizable: true,
                        height: "100%",
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No more columns are available to add."
                        },
                        dataSource: {
                            serverPaging: true,
                            serverSorting: true,
                            pageSize: 250,
                            transport: {
                                read: {
                                    url: Jade.Path.resolve(`~/Shared/ViewAnchors/SearchAnchors`),
                                    type: "post",
                                    data: (e) => {
                                        return {
                                            viewStateId: this.viewStateId,
                                            term: this.searchTerm
                                        };
                                    }
                                }
                            }
                        },
                        selectOnRightClick: true,
                        defaultSelectionEnabled: false,
                        selection: {
                            mapping: (e) => {
                                return {
                                    uid: e.uid,
                                    id: e.ObjectId,
                                    parts: e.parts,
                                    depth: e.depth,
                                    path: e.path,
                                    target: e.target
                                };
                            }
                        },
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "target",
                                title: "Target",
                                width: "250px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "path",
                                title: "Path",
                                width: "300px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ],
                        change: (e) => {
                            this.changeCallback();
                        },
                        dblclick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/anchors:entity-type-anchor/add");
                        }
                    });
                }
                searchBox_init() {
                    this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                        insertAt: "div[role=toolbar]",
                        onSearch: (e) => {
                            this.searchTerm = e.term;
                            this.m_grid.refresh();
                        }
                    });
                    this.controls.add(this.m_searchBox);
                }
            }
            Views.EntTypeAnchorsFinder = EntTypeAnchorsFinder;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EntTypeAnchorsToolbar extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/anchors:entity-type-anchor/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/anchors:entity-type-anchor/clear"
                    }));
                }
            }
            Views.EntTypeAnchorsToolbar = EntTypeAnchorsToolbar;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AddEntTypeAnchorsCommand extends Views.EntTypeAnchorsCommand {
                onExecute(e) {
                    super.onExecute(e);
                    this.foundAnchors.forEach(item => {
                        this.populate(item.parts);
                    });
                    this.setCommandState();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.EntTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.foundAnchors.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type-anchor/add",
                        tooltip: "Add Entity Type Anchor",
                        label: "Add",
                        icon: "arrow_down_green.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                populate(data) {
                    let dataSource = this.editor.dataSource;
                    data.forEach((item, index) => {
                        let record = dataSource.at(index);
                        if (record == null) {
                            dataSource.add({
                                depth: index,
                                parts: [data[index]]
                            });
                        }
                        else {
                            this.mergeRecord(record, data[index], index);
                        }
                    });
                    this.editor.refresh();
                }
                mergeRecord(record, mergingPart, index) {
                    let parts = record.parts.slice(0);
                    let contains = record.parts.find((part) => {
                        return part.id == mergingPart.id;
                    }) != null;
                    if (!contains) {
                        parts[parts.length] = mergingPart;
                    }
                    record
                        .set("parts", parts);
                }
            }
            Views.AddEntTypeAnchorsCommand = AddEntTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ClearEntTypeAnchorsCommand extends Views.EntTypeAnchorsCommand {
                onExecute() {
                    this.editor.dataSource.data([]);
                    this.editor.refresh();
                    this.enabled = false;
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.EntTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.editor.dataSource.data().length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "entity-type-anchor/clear",
                        tooltip: "Clear Anchors",
                        label: "Clear",
                        icon: "eraser2.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            Views.ClearEntTypeAnchorsCommand = ClearEntTypeAnchorsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get settingsButtonNode() {
                    return this.node.find("button[data-command=settings]");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-view-columns-dialog">
                    <div role="content">
                        <div role="splitter">
                            <div>
                                <div role="finder"></div>
                            </div>
                            <div>
                                <div role="editor"></div>
                            </div>
                        </div>
                    </div>
                    <div role="buttons">
                        <div>
                            <button class="-pdjs-dialog-button" data-command="settings">Settings</button>
                        </div>
                        <div>
                            <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.okButton_onClick(e);
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.cancelButton_onClick(e);
                    });
                    this.settingsButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.settingsButton_onClick(e);
                    });
                    this.splitter_init();
                    this.initializationRequest();
                    this.setDialogTitle();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                }
                getDefaultOptions() {
                    return {
                        height: 500,
                        width: 650
                    };
                }
                okButton_onClick(e) {
                    this.m_editor.save(() => {
                        this.close({
                            name: "ok"
                        });
                    });
                }
                cancelButton_onClick(e) {
                    this.close({
                        name: "cancel"
                    });
                }
                settingsButton_onClick(e) {
                    this.m_popup.show();
                }
                splitter_init() {
                    this.splitterNode.kendoSplitter({
                        orientation: "vertical",
                        panes: [
                            { size: "50%", resizable: true },
                            {}
                        ]
                    }).data("kendoSplitter");
                }
                editor_init() {
                    this.m_editor = new Views.ColumnsEditor({
                        insertAt: "div[role=editor]",
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                finder_init(anchorDepths, excludeColumns) {
                    this.m_finder = new Views.ColumnsFinder({
                        insertAt: "div[role=finder]",
                        anchorDepths: anchorDepths,
                        componentTarget: "columns",
                        componentType: this.componentType,
                        excludeColumns: excludeColumns,
                        viewStateId: this.viewStateId,
                        change: () => {
                            this.setCommandState();
                        },
                        dblclick: () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/columns:column/add");
                        }
                    });
                    this.controls.add(this.m_finder);
                }
                popup_init() {
                    this.m_popup =
                        new Views.ColumnsFinderSettings({
                            componentType: this.componentType,
                            viewStateId: this.viewStateId,
                            anchor: this.settingsButtonNode,
                            height: 320,
                            width: 200
                        });
                    this.controls.add(this.m_popup);
                }
                setDialogTitle() {
                    switch (this.componentType) {
                        case "bounds":
                            this.setWindowOptions({ title: "View | Bounds Columns" });
                            return;
                        case "design":
                            this.setWindowOptions({ title: "View | Design Columns" });
                            return;
                        case "findinresults":
                            this.setWindowOptions({ title: "View | Find in Results Columns" });
                            return;
                    }
                }
                initializationRequest() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/Get${this.componentType}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.editor_init();
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                setCommandState() {
                    if (this.m_finder == null || this.m_editor == null) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/columns": {
                            componentType: this.componentType,
                            $editor: this.m_editor,
                            $finder: this.m_finder
                        }
                    }, { force: true });
                }
                static open(options) {
                    return new ColumnsDialog(options);
                }
            }
            Views.ColumnsDialog = ColumnsDialog;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsDialogCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("componentType", null);
                    this.state.set("$editor", null);
                    this.state.set("$finder", null);
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get editor() {
                    return this.state.get("$editor");
                }
                get editorGrid() {
                    return this.editor.grid;
                }
                get finder() {
                    return this.state.get("$finder");
                }
                get finderGrid() {
                    return this.finder.grid;
                }
                onExecute(e) {
                    if (this.componentType == "design") {
                        this.onExecuteForDesign();
                    }
                    else {
                        this.onExecuteForBounds();
                    }
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                }
                onExecuteForDesign() {
                }
                setCommandState() {
                    if (this.finder == null || this.editor == null) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/columns": {
                            componentType: this.componentType,
                            $editor: this.editor,
                            $finder: this.finder
                        }
                    }, { force: true });
                }
            }
            Views.ColumnsDialogCommand = ColumnsDialogCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsDialogCommands extends Jade.CommandGroup {
                constructor() {
                    super("view/columns");
                }
                registerCommands(e) {
                    e.commands.add(new Views.AddColumnCommand({}));
                    e.commands.add(new Views.ClearColumnsCommand({}));
                    e.commands.add(new Views.RemoveColumnCommand({}));
                    e.commands.add(new Views.EditColumnCommand({}));
                    e.commands.add(new Views.MoveColumnCommand({
                        id: "column/move-up",
                        label: "Move Up",
                        tooltip: "Move Column Up",
                        icon: "arrow_up_blue.png",
                        moveDirection: Views.MoveDirection.up
                    }));
                    e.commands.add(new Views.MoveColumnCommand({
                        id: "column/move-down",
                        label: "Move Down",
                        tooltip: "Move Column Down",
                        icon: "arrow_down_blue.png",
                        moveDirection: Views.MoveDirection.down
                    }));
                }
            }
            Views.ColumnsDialogCommands = ColumnsDialogCommands;
            Jade.Application.onStart(() => {
                Jade.CommandGroups.add(ColumnsDialogCommands);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsDialogContextMenuSegment extends Jade.UI.ContextMenuSegment {
                onAddItems(e) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "view/columns:column/add"
                    }));
                }
            }
            Views.ColumnsDialogContextMenuSegment = ColumnsDialogContextMenuSegment;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsDialogToolBarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:column/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:column/remove"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:columns/clear"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:column/edit"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:column/move-up"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/columns:column/move-down"
                    }));
                }
            }
            Views.ColumnsDialogToolBarSegment = ColumnsDialogToolBarSegment;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AddColumnCommand extends Views.ColumnsDialogCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.finderGrid.selected.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "column/add",
                        tooltip: "Add Column",
                        label: "Add",
                        icon: "arrow_down_green.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                    let columns = this.finderGrid.selected.slice(0);
                    this.editorGrid.addColumns(columns);
                    this.finderGrid.removeColumns(columns);
                }
                onExecuteForDesign() {
                    let columns = this.finderGrid.selected.slice(0);
                    this.editorGrid.addColumns(columns);
                    this.finderGrid.removeColumns(columns);
                }
            }
            Views.AddColumnCommand = AddColumnCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ClearColumnsCommand extends Views.ColumnsDialogCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.editorGrid.columns.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "columns/clear",
                        tooltip: "Clear Columns",
                        label: "Clear",
                        icon: "eraser2.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                    this.editorGrid.clearColumns();
                    this.finderGrid.refresh();
                }
                onExecuteForDesign() {
                    this.editorGrid.clearColumns();
                    this.finderGrid.clearExcludedColumns();
                }
            }
            Views.ClearColumnsCommand = ClearColumnsCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EditColumnCommand extends Views.ColumnsDialogCommand {
                get column() {
                    return _.first(this.editorGrid.selected);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.editorGrid.selected.length == 1;
                    if (this.column) {
                        this.showEditState(this.column.name == this.column.defaultName);
                    }
                }
                getDefaultValuesForProps() {
                    return {
                        id: "column/edit",
                        tooltip: "Edit Name",
                        label: "Edit Name",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecute(e) {
                    super.onExecute(e);
                    let switchToEditMode = this.column.name == this.column.defaultName;
                    switchToEditMode ?
                        this.switchToEditMode() :
                        this.revertToOriginal();
                    this.showEditState(this.column.name == this.column.defaultName);
                }
                showEditState(enabled) {
                    if (!enabled) {
                        this.label = "Revert Name";
                        this.tooltip = "Revert to Original Name";
                        this.icon = "undo.png";
                    }
                    else {
                        this.label = "Edit Name";
                        this.tooltip = "Edit Name";
                        this.icon = "pencil.png";
                    }
                }
                switchToEditMode() {
                    let editorNode = this.editorGrid.node
                        .find(".k-state-selected").find(".-pdjs-grid-text-editor");
                    new Views.ColumnsEditorNameEditorNew({
                        target: editorNode,
                        commit: (e) => {
                            this.setCommandState();
                        }
                    });
                }
                revertToOriginal() {
                    let data = this.column;
                    data.name = data.defaultName;
                    this.editorGrid.updateColumns([data]);
                }
            }
            Views.EditColumnCommand = EditColumnCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let MoveDirection;
            (function (MoveDirection) {
                MoveDirection["up"] = "up";
                MoveDirection["down"] = "down";
            })(MoveDirection = Views.MoveDirection || (Views.MoveDirection = {}));
            class MoveColumnCommand extends Views.ColumnsDialogCommand {
                constructor(options) {
                    super(options);
                }
                get moveDirection() {
                    return this.props.get("moveDirection", MoveDirection.up);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.editorGrid.selected.length > 0;
                    this.visible = this.componentType == "design";
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForDesign() {
                    this.move(this.editorGrid.columns.slice(0));
                }
                move(columns) {
                    if (this.moveDirection == MoveDirection.down) {
                        columns = columns.reverse();
                    }
                    let movingIds = this.editorGrid.selected.map(column => { return column.id; });
                    let movingColumns = [];
                    columns.forEach((column, index, array) => {
                        this.transfer({
                            column: column,
                            index: index,
                            movingColumns: movingColumns,
                            movingColumnsIds: movingIds
                        });
                    });
                    movingColumns = this.moveDirection == MoveDirection.up ?
                        movingColumns : movingColumns.reverse();
                    this.editorGrid.moveColumns(movingColumns);
                }
                transfer(e) {
                    let isFirstColumn = e.index == 0;
                    let lastColumn = null;
                    let currColumn = e.column;
                    if (!isFirstColumn) {
                        lastColumn = e.movingColumns[e.movingColumns.length - 1];
                    }
                    let isCurrMoving = e.movingColumnsIds.indexOf(currColumn.id) > -1;
                    let isLastMoved = false;
                    if (lastColumn) {
                        isLastMoved = e.movingColumnsIds.indexOf(lastColumn.id) > -1;
                    }
                    if (isLastMoved) {
                        e.movingColumns.push(currColumn);
                    }
                    else {
                        if (isCurrMoving) {
                            e.movingColumns.pop();
                            e.movingColumns.push(currColumn);
                            if (lastColumn) {
                                e.movingColumns.push(lastColumn);
                            }
                        }
                        else {
                            e.movingColumns.push(currColumn);
                        }
                    }
                }
            }
            Views.MoveColumnCommand = MoveColumnCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class RemoveColumnCommand extends Views.ColumnsDialogCommand {
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.editorGrid.selected.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "column/remove",
                        tooltip: "Remove Column",
                        label: "Remove",
                        icon: "arrow_up_red.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                    let columns = this.editorGrid.selected.slice(0);
                    this.editorGrid.removeColumns(columns);
                    this.finderGrid.addColumns(columns);
                }
                onExecuteForDesign() {
                    let columns = this.editorGrid.selected.slice(0);
                    this.editorGrid.removeColumns(columns);
                    this.finderGrid.addColumns(columns);
                }
            }
            Views.RemoveColumnCommand = RemoveColumnCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get grid() {
                    return this.m_grid;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                template() {
                    return `
                <div class="-pdjs-view-columns-editor">
                    <div role="toolbar"></div>
                    <div role="header"></div>
                    <div role="content" data-controls></div>
                </div>`;
                }
                save(callback) {
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.POST,
                        contentType: "application/json",
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/Set${this.componentType}`),
                        data: JSON.stringify({
                            viewStateId: this.viewStateId,
                            columns: this.m_grid.columns
                        }),
                        success: (e) => {
                            if (_.isFunction(callback)) {
                                callback();
                            }
                        }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.initializationRequest();
                }
                grid_init(data) {
                    this.m_grid = new Views.ColumnsEditorGrid({
                        insertAt: "[role=content]",
                        data: data,
                        change: () => {
                            this.changeCallback();
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.ColumnsDialogToolBarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                initializationRequest() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/Get${this.componentType}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.grid_init(e.columns);
                            this.toolbar_init();
                        }
                    });
                }
            }
            Views.ColumnsEditor = ColumnsEditor;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsEditorGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get columns() {
                    return this.grid.get_dataSource().data();
                }
                get grid() {
                    return this.m_grid;
                }
                set grid(value) {
                    this.m_grid = value;
                }
                get gridData() {
                    return this.state.get("data", []);
                }
                get gridDataSource() {
                    return this.grid.get_dataSource().get_instance();
                }
                get gridSelections() {
                    return this.grid.getSelections().toArray();
                }
                get selected() {
                    return this.gridSelections.map(item => _.extend({ uid: item.uid }, item.toJSON()));
                }
                addColumns(columns) {
                    columns.forEach(column => {
                        let record = this.gridDataSource.get(column.id);
                        if (record == null) {
                            this.gridDataSource.add(column);
                        }
                    });
                    this.grid.refresh({
                        clear: true,
                        selections: columns.map(column => { return column.id; })
                    });
                }
                clearColumns() {
                    this.gridDataSource.data().slice(0).forEach(column => {
                        this.gridDataSource.remove(column);
                    });
                    this.m_grid.refresh({
                        clear: true
                    });
                }
                moveColumns(columns) {
                    this.gridDataSource.data(columns);
                    this.grid.refresh({ reselect: true });
                }
                removeColumns(columns) {
                    columns.forEach(column => {
                        let record = this.gridDataSource.get(column.id);
                        if (record != null) {
                            this.gridDataSource.remove(record);
                        }
                    });
                    this.grid.refresh({
                        clear: true
                    });
                }
                updateColumns(columns) {
                    columns.forEach(column => {
                        let record = this.gridDataSource.get(column.id);
                        if (record != null) {
                            for (let name in column) {
                                record.set(name, column[name]);
                            }
                        }
                    });
                }
                template() {
                    return `<div class="-pdjs-view-columns-editor-grid"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                }
                grid_init() {
                    let grid = () => {
                        return this.node.children(".-pd-viewgrid").data("kendoGrid");
                    };
                    this.m_data = this.gridData || [];
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        pk: "id",
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No columns have been added to the view."
                        },
                        dataSource: {
                            data: this.m_data,
                            storeAsLocalVariable: true
                        },
                        container: this.node,
                        selectionMode: "multiple",
                        selectOnRightClick: false,
                        defaultSelectionEnabled: false,
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "id",
                                title: "&nbsp;",
                                width: "40px",
                                template: (e) => {
                                    return (grid().dataSource.data().indexOf(e) + 1) + ".";
                                },
                                attributes: {
                                    style: `
                                text-align: right;
                                font-weight: bold;
                                background-color: var(--visiv-theme-base-3-back-color);
                                border-color: var(--visiv-theme-base-3-border-color);
                                color: var(--visiv-theme-base-3-text-color);`
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px",
                                template: (e) => {
                                    return `<div class="-pdjs-grid-text-editor">
                                        <div role="label" class="${e.name !== e.defaultName ? "-pdjs-label-name-changed" : ""}">${e.name}</div>
                                        <input type="text" value="${e.name}" style="display:none;"/>
                                    </div>`;
                                },
                                attributes: {
                                    style: "padding: 0;"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "usedBy",
                                title: "Used By",
                                width: "150px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "sources",
                                title: "Found In",
                                width: "400px",
                                template: (e) => {
                                    return e.sources ? e.sources.join(", ") : "";
                                }
                            })
                        ],
                        change: (e) => {
                            if (this.m_grid != null) {
                                this.changeCallback();
                            }
                        }
                    });
                    this.m_grid.get_node().on("dblclick", ".-pdjs-grid-text-editor", (e) => {
                        new Views.ColumnsEditorNameEditorNew({
                            target: $(e.currentTarget),
                            commit: (e) => {
                                this.changeCallback();
                            }
                        });
                    });
                }
            }
            Views.ColumnsEditorGrid = ColumnsEditorGrid;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsEditorNameEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get column() {
                    return this.state.get("column");
                }
                get inputNode() {
                    return this.node.children("input");
                }
                get grid() {
                    return this.node.closest(".k-grid").data("kendoGrid");
                }
                get dataource() {
                    return this.grid.dataSource;
                }
                get labelNode() {
                    return this.node.children("div[role=label]");
                }
                get isInEditMode() {
                    return this.inputNode.is(":visible");
                }
                get isNotOriginalName() {
                    return this.column.name != this.column.defaultName;
                }
                get commit() {
                    return this.state.get("commit", () => { });
                }
                set commit(value) {
                    this.state.set("commit", value);
                }
                template() {
                    return `<div class="-pdjs-grid-text-editor">
                        <div role="label">${this.column.name}</div>
                        <input type="text" value="${name}"/>
                    </div>`;
                }
                edit() {
                    this.enterEditMode();
                }
                revert() {
                    let row = this.dataource.getByUid(this.column.uid);
                    row.set("name", this.column.defaultName);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.on(Jade.BrowserEvent.DOUBLECLICK, _.bind(this.onDoubleClick, this));
                    this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.onBlur, this));
                    this.inputNode.on(Jade.BrowserEvent.KEYUP, _.bind(this.onKeyUp, this));
                    this.inputNode.hide();
                    this.setCssStyle(this.column.name);
                }
                onDoubleClick(e) {
                    this.enterEditMode();
                    this.inputNode.focus();
                    this.inputNode.select();
                }
                onBlur(e) {
                    this.commitChange();
                }
                onKeyUp(e) {
                    if (e.keyCode == 13) {
                        this.inputNode.blur();
                    }
                }
                enterEditMode() {
                    this.labelNode.hide();
                    this.inputNode.show();
                    this.inputNode.val(this.labelNode.text());
                    this.inputNode.focus();
                    this.inputNode.select();
                }
                commitChange() {
                    let value = this.inputNode.val();
                    this.labelNode.show();
                    this.inputNode.hide();
                    this.labelNode.text(value);
                    this.inputNode.selectionStart = this.inputNode.selectionEnd = -1;
                    let row = this.dataource.getByUid(this.column.uid);
                    value = Jade.String.isNullOrWhiteSpace(value)
                        ? this.column.defaultName : value;
                    row.set("name", value);
                    this.commit(value);
                    this.setCssStyle(value);
                }
                setCssStyle(value) {
                    if (this.column.defaultName != value) {
                        this.labelNode.addClass("-pdjs-label-name-changed");
                    }
                    else {
                        this.labelNode.removeClass("-pdjs-label-name-changed");
                    }
                }
            }
            Views.ColumnsEditorNameEditor = ColumnsEditorNameEditor;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsEditorNameEditorMap {
                constructor() {
                    this.m_map = {};
                }
                add(e) {
                    let cell = null;
                    setTimeout(() => {
                        cell = $(`tr[data-uid=${e.uid}] div[data-id=${e.id}]`);
                        if (cell.find(".-pdjs-grid-text-editor").length == 0) {
                            this.remove(e.uid);
                            this.m_map[e.uid] =
                                new Views.ColumnsEditorNameEditor({
                                    container: cell,
                                    column: e
                                });
                        }
                    }, 100);
                }
                remove(uid) {
                    if (this.exists(uid)) {
                        this.m_map[uid].destroy();
                        delete this.m_map[uid];
                    }
                }
                clear() {
                    for (var uid in this.m_map) {
                        this.remove(uid);
                    }
                }
                exists(uid) {
                    return this.m_map[uid] != null;
                }
                get(uid) {
                    return this.m_map[uid];
                }
            }
            Views.ColumnsEditorNameEditorMap = ColumnsEditorNameEditorMap;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsEditorNameEditorNew extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.m_rowUid = options.target.closest("tr[role=row]").data("uid");
                    this.init();
                }
                get column() {
                    return this.columnModel.toJSON();
                }
                get columnModel() {
                    return this.dataSource.getByUid(this.rowNode.data("uid"));
                }
                get commitCallback() {
                    return this.state.get("commit", () => { });
                }
                get inputNode() {
                    return this.editorNode.children("input");
                }
                get grid() {
                    return this.rowNode.closest(".k-grid").data("kendoGrid");
                }
                get dataSource() {
                    return this.grid.dataSource;
                }
                get rowUid() {
                    return this.m_rowUid;
                }
                set rowUid(value) {
                    this.m_rowUid = value;
                }
                get rowNode() {
                    return $(`tr[role=row][data-uid=${this.rowUid}]`);
                }
                get editorNode() {
                    return this.rowNode.find(".-pdjs-grid-text-editor");
                }
                get labelNode() {
                    return this.editorNode.children("div[role=label]");
                }
                get isInEditMode() {
                    return this.inputNode.is(":visible");
                }
                get isNotOriginalName() {
                    return this.column.name != this.column.defaultName;
                }
                edit() {
                    this.enterEditMode();
                }
                revert() {
                    let row = this.dataSource.getByUid(this.column.uid);
                    row.set("name", this.column.defaultName);
                }
                init() {
                    this.rowUid;
                    this.inputNode.on(Jade.BrowserEvent.BLUR, _.bind(this.onBlur, this));
                    this.inputNode.on(Jade.BrowserEvent.KEYUP, _.bind(this.onKeyUp, this));
                    this.inputNode.hide();
                    this.show();
                    this.setCssStyle(this.column.name);
                }
                destroy() {
                    this.inputNode.off(Jade.BrowserEvent.BLUR);
                    this.inputNode.off(Jade.BrowserEvent.KEYUP);
                }
                onBlur(e) {
                    this.commitChange();
                    this.destroy();
                    this.hide();
                }
                onKeyUp(e) {
                    if (e.keyCode == 13) {
                        this.inputNode.blur();
                    }
                }
                enterEditMode() {
                    this.labelNode.hide();
                    this.inputNode.show();
                    this.inputNode.val(this.labelNode.text());
                    this.inputNode.focus();
                    this.inputNode.select();
                }
                commitChange() {
                    let value = this.inputNode.val();
                    value = Jade.String.isNullOrWhiteSpace(value)
                        ? this.column.defaultName : value;
                    this.columnModel.set("name", value);
                    this.commitCallback(this.column);
                    this.labelNode.show();
                    this.inputNode.hide();
                    this.labelNode.text(value);
                    this.inputNode.selectionStart = this.inputNode.selectionEnd = -1;
                    this.setCssStyle(value);
                }
                setCssStyle(value) {
                    if (this.column.defaultName != value) {
                        this.labelNode.addClass("-pdjs-label-name-changed");
                    }
                    else {
                        this.labelNode.removeClass("-pdjs-label-name-changed");
                    }
                }
                show() {
                    this.labelNode.hide();
                    this.inputNode.show();
                    this.inputNode.select();
                    this.inputNode.focus();
                }
                hide() {
                    this.labelNode.show();
                    this.inputNode.hide();
                }
            }
            Views.ColumnsEditorNameEditorNew = ColumnsEditorNameEditorNew;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let AddedColumnsChangedEventType;
            (function (AddedColumnsChangedEventType) {
                AddedColumnsChangedEventType["add"] = "add";
                AddedColumnsChangedEventType["remove"] = "remove";
                AddedColumnsChangedEventType["clear"] = "clear";
            })(AddedColumnsChangedEventType = Views.AddedColumnsChangedEventType || (Views.AddedColumnsChangedEventType = {}));
            let ColumnFinderType;
            (function (ColumnFinderType) {
                ColumnFinderType[ColumnFinderType["Columns"] = 0] = "Columns";
                ColumnFinderType[ColumnFinderType["Filters"] = 1] = "Filters";
            })(ColumnFinderType = Views.ColumnFinderType || (Views.ColumnFinderType = {}));
            class ColumnsFinder extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get anchorDepths() {
                    return this.state.get("anchorDepths", []);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get dblclickCallback() {
                    return this.state.get("dblclick", () => { });
                }
                get componentTarget() {
                    return this.state.get("componentTarget", "columns");
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get excludeColumns() {
                    return this.state.get("excludeColumns", []);
                }
                set excludeColumns(value) {
                    this.state.set("excludeColumns", null);
                    this.state.set("excludeColumns", value);
                }
                get grid() {
                    return this.m_grid;
                }
                get selected() {
                    return this.m_grid.selected;
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                template() {
                    return `
                <div class="-pdjs-view-columns-finder">
                    <div role="toolbar"></div>
                    <div role="content"></div>
                </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.toolbar_init();
                    this.grid_init();
                    this.subscriptions.add(Views.EventsHub.finderSettingsChangedSubscribe(() => {
                        this.m_grid.refresh();
                    }));
                }
                grid_init() {
                    this.m_grid = new Views.ColumnsFinderGrid({
                        insertAt: "div[role=content]",
                        componentType: this.componentType,
                        componentTarget: this.componentTarget,
                        excludeColumns: this.excludeColumns,
                        change: () => {
                            this.changeCallback();
                        },
                        dblclick: () => {
                            this.changeCallback();
                            this.dblclickCallback();
                        },
                        viewStateId: this.viewStateId
                    });
                    this.controls.add(this.m_grid);
                }
                toolbar_init() {
                    this.m_toolbar = new Views.ColumnsFinderToolbar({
                        insertAt: "div[role=toolbar]",
                        anchorDepths: this.anchorDepths
                    });
                    this.controls.add(this.m_toolbar);
                }
            }
            Views.ColumnsFinder = ColumnsFinder;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsFinderDialog extends Jade.UI.Dialogs.DialogOf {
                constructor(options) {
                    super(options);
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get settingsButtonNode() {
                    return this.node.find("button[data-command=settings]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-view-columns-finder-dialog">
                    <div role="content">
                        <div role="finder"></div>
                    </div>
                    <div role="buttons">
                        <div>
                            <button class="-pdjs-dialog-button" data-command="settings">Settings</button>
                        </div>
                        <div>
                            <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.okButton_onClick(e);
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.cancelButton_onClick(e);
                    });
                    this.settingsButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.settingsButton_onClick(e);
                    });
                    this.initializationRequest();
                    this.setDialogTitle();
                }
                getDefaultOptions() {
                    return {
                        height: 400,
                        width: 600
                    };
                }
                okButton_onClick(e) {
                    this.okAndClose();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                settingsButton_onClick(e) {
                    this.m_popup.show();
                }
                finder_init(anchorDepths, excludeColumns) {
                    this.m_finder = new Views.ColumnsFinder({
                        insertAt: "div[role=finder]",
                        componentTarget: "columns",
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        anchorDepths: anchorDepths,
                        excludeColumns: excludeColumns,
                        dblclick: () => {
                            this.okAndClose();
                        }
                    });
                    this.controls.add(this.m_finder);
                }
                popup_init() {
                    this.m_popup =
                        new Views.ColumnsFinderSettings({
                            componentType: this.componentType,
                            viewStateId: this.viewStateId,
                            anchor: this.settingsButtonNode,
                            height: 320,
                            width: 200
                        });
                    this.controls.add(this.m_popup);
                }
                setDialogTitle() {
                    switch (this.componentType) {
                        case "bounds":
                            this.setWindowOptions({ title: "View | Bounds Columns" });
                        case "design":
                            this.setWindowOptions({ title: "View | Design Columns" });
                    }
                }
                initializationRequest() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/Get${this.componentType}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                okAndClose() {
                    this.close({
                        name: "ok",
                        data: {
                            columns: this.m_finder.selected
                        }
                    });
                }
                static open(options) {
                    return new ColumnsFinderDialog(options);
                }
            }
            Views.ColumnsFinderDialog = ColumnsFinderDialog;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsFinderGrid extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get anchorDepth() {
                    return this.state.get("anchorDepth", 0);
                }
                set anchorDepth(value) {
                    this.state.set("anchorDepth", value);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get columns() {
                    return this.grid.get_dataSource().data();
                }
                get componentTarget() {
                    return this.state.get("componentTarget", "columns");
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get dblclickCallback() {
                    return this.state.get("dblclick", () => { });
                }
                get excludeColumns() {
                    return this.state.get("excludeColumns", []);
                }
                set excludeColumns(value) {
                    this.state.set("excludeColumns", null);
                    this.state.set("excludeColumns", value);
                }
                get grid() {
                    return this.m_grid;
                }
                set grid(value) {
                    this.m_grid = value;
                }
                get gridSelections() {
                    return this.grid.getSelections().toArray();
                }
                get searchTerm() {
                    return this.state.get("searchTerm");
                }
                set searchTerm(value) {
                    this.state.set("searchTerm", value);
                }
                get selected() {
                    return this.gridSelections.map(item => {
                        return _.extend({ uid: item.uid }, item.toJSON());
                    });
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                addColumns(columns) {
                    let remaining = [];
                    this.excludeColumns.forEach(column => {
                        let match = columns
                            .find(item => item.id === column.id) != null;
                        if (!match) {
                            remaining.push(column);
                        }
                    });
                    this.excludeColumns = remaining;
                    this.refresh({
                        clear: true,
                        selections: columns.map(column => { return column.id; })
                    });
                }
                clearExcludedColumns() {
                    this.excludeColumns = [];
                    this.refresh({ clear: true });
                }
                refresh(options) {
                    this.grid.refresh(options);
                }
                removeColumns(columns) {
                    columns.forEach(column => {
                        let match = this.excludeColumns
                            .find(item => item.id === column.id) != null;
                        if (!match) {
                            this.excludeColumns.push(column);
                        }
                    });
                    this.refresh({
                        clear: true
                    });
                }
                template() {
                    return `<div class="-pdjs-view-columns-finder-grid"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.subscriptions.add(Views.EventsHub.finderParamsChangedSubscribe((e) => {
                        this.anchorDepth = e.anchorDepth;
                        this.searchTerm = e.searchTerm;
                        this.grid.get_dataSource().get_instance()._skip = 0;
                        this.grid.get_dataSource().read();
                    }));
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.node,
                        pk: "id",
                        resizable: true,
                        footer: {
                            visible: false
                        },
                        messaging: {
                            noRecordsMessage: "No more columns are available to add."
                        },
                        dataSource: {
                            serverPaging: true,
                            serverSorting: true,
                            pageSize: 250,
                            transport: {
                                read: {
                                    url: this.generateUrl(),
                                    type: "post",
                                    data: () => {
                                        return {
                                            viewStateId: this.viewStateId,
                                            term: this.searchTerm,
                                            textOnly: this.componentType === "findinresults",
                                            depth: this.anchorDepth,
                                            exclude: this.excludeColumns.flatMap(column => { return column.id; })
                                        };
                                    }
                                }
                            },
                            schema: {
                                data: "data",
                                total: "totalCount"
                            },
                            sort: [
                                { field: "name", dir: "asc" }
                            ]
                        },
                        sortable: {
                            mode: "multiple",
                            allowUnsort: true
                        },
                        selectOnRightClick: true,
                        defaultSelectionEnabled: false,
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "usedBy",
                                title: "Used By",
                                width: "150px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "foundIn",
                                title: "Found In",
                                width: "400px",
                                attributes: {
                                    style: "white-space:no-wrap"
                                }
                            })
                        ],
                        change: (e) => {
                            if (this.m_grid != null) {
                                this.draggable_init();
                                this.changeCallback();
                            }
                        },
                        dblclick: (e) => {
                            this.dblclickCallback();
                        },
                        contextMenu: (grid) => {
                            this.contextMenu_init(grid);
                        }
                    });
                }
                draggable_init() {
                    let dialogNode = this.node.closest(".-jadejs-window");
                    this.m_grid.get_node().find("tr.k-state-selected").draggable({
                        appendTo: dialogNode,
                        containment: dialogNode,
                        delay: 250,
                        helper: (e) => {
                            return `<div class="-pdjs-grid-drag-and-drop-helper">X Columns</div>`;
                        },
                        cursorAt: {
                            top: 5,
                            left: 5
                        }
                    });
                }
                contextMenu_init(grid) {
                    let contextMenu = new PDJS.Shared.UI.Controls.GridContextMenu({
                        grid: grid,
                        segments: [
                            {
                                type: "PDJS.Shared.Views.ColumnsDialogContextMenuSegment"
                            }
                        ]
                    });
                    this.controls.add(contextMenu);
                }
                generateUrl() {
                    return Jade.Path.resolve(`~/Shared/View${this.componentTarget}/Search${this.componentType}`);
                }
            }
            Views.ColumnsFinderGrid = ColumnsFinderGrid;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ColumnsFinderToolbar extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get searchTerm() {
                    return this.state.get("searchTerm");
                }
                set searchTerm(value) {
                    this.state.set("searchTerm", value);
                }
                get anchorDepth() {
                    let value = parseInt(this.anchorDepthNode.val());
                    return isNaN(value) ? 0 : value;
                }
                get anchorNode() {
                    return this.node.find("div[role=anchors]");
                }
                get anchorDepthNode() {
                    return this.node.find("select");
                }
                get dividerNode() {
                    return this.node.children("div:nth-child(2)");
                }
                get anchorDepths() {
                    return this.state.get("anchorDepths", []);
                }
                template() {
                    return `
            <div class="-pdjs-view-columns-finder-dialog-toolbar">
                <div role="anchors">
                    <select></select>
                </div>
                <div></div>
                <div role="filter"></div>
            </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.anchorDepth_init();
                    this.searchBox_init();
                }
                searchBox_init() {
                    this.m_searchBox = new PDJS.Shared.UI.Controls.SearchBox({
                        insertAt: "div[role=filter]",
                        onSearch: (e) => {
                            this.searchTerm = e.term;
                            Views.EventsHub.finderParamsChangedPublish({
                                anchorDepth: this.anchorDepth,
                                searchTerm: this.searchTerm
                            });
                        }
                    });
                    this.controls.add(this.m_searchBox);
                }
                anchorDepth_init() {
                    this.anchorDepthNode.on(Jade.BrowserEvent.CHANGE, () => {
                        Views.EventsHub.finderParamsChangedPublish({
                            anchorDepth: this.anchorDepth,
                            searchTerm: this.searchTerm
                        });
                    });
                    this.anchorDepthVisible(this.anchorDepths.length > 1);
                    this.anchorDepths.forEach(depth => {
                        this.anchorDepthNode.append(`<option value="${depth.value}">Columns for: ${depth.name}</option>`);
                    });
                }
                anchorDepthVisible(visible) {
                    if (visible) {
                        this.anchorNode.show();
                        this.dividerNode.show();
                        this.node.attr("depths", "true");
                    }
                    else {
                        this.anchorNode.hide();
                        this.dividerNode.hide();
                        this.node.removeAttr("depths");
                    }
                }
            }
            Views.ColumnsFinderToolbar = ColumnsFinderToolbar;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let searchFlag;
            (function (searchFlag) {
                searchFlag[searchFlag["name"] = 1] = "name";
                searchFlag[searchFlag["usedBy"] = 2] = "usedBy";
                searchFlag[searchFlag["foundIn"] = 4] = "foundIn";
            })(searchFlag || (searchFlag = {}));
            let includeFlag;
            (function (includeFlag) {
                includeFlag[includeFlag["listValues"] = 8] = "listValues";
                includeFlag[includeFlag["listLabels"] = 4] = "listLabels";
                includeFlag[includeFlag["mslLists"] = 16] = "mslLists";
                includeFlag[includeFlag["entityData"] = 32] = "entityData";
                includeFlag[includeFlag["userData"] = 64] = "userData";
                includeFlag[includeFlag["processData"] = 2] = "processData";
            })(includeFlag || (includeFlag = {}));
            class ColumnsFinderSettings extends PDJS.Shared.UI.Controls.PopUp {
                constructor(options) {
                    super(options);
                }
                get contentNode() {
                    return this.node.find("div[role=content]");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addContent();
                }
                getPopUpOptions() {
                    return _.extend(super.getPopUpOptions(), {
                        skin: "themed",
                        position: "topleft",
                        padding: true,
                        maxHeight: 0,
                        onShow: () => {
                            this.getFinderSettings();
                        },
                        afterHide: () => {
                            this.setFinderSettings();
                        }
                    });
                }
                addContent() {
                    let content = `
            <div class="-pdjs-finder-settings">
                <div role="header"></div>
                <div role="content" data-controls></div>
            </div>`;
                    this.node.append(content);
                }
                addCheckBoxHeader(text) {
                    this.contentNode.append(`<div role="checkbox-header">${text}</div>`);
                }
                addCheckBoxInput(name, text, value, checked = false) {
                    this.contentNode.append(`
                <div role="checkbox">
                    <label>
                        <div></div>
                        <div><input type="checkbox" value="${value}" name="${name}" ${checked ? "checked" : ""} /></div>
                        <div>${text}</div>
                    </label>
                </div>
            `);
                }
                getFinderSettings() {
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.GET,
                        url: Jade.Path.resolve("~/Shared/View/GetColumnFinderSettings"),
                        success: (e) => {
                            this.contentNode.empty();
                            var searchFlags = e.search;
                            var includeFlags = e.include;
                            var condenseFlags = e.condense;
                            this.addCheckBoxHeader("Search against:");
                            this.addCheckBoxInput("search", "Name", 1, ((searchFlags & searchFlag.name) == searchFlag.name));
                            this.addCheckBoxInput("search", "Used By", 2, ((searchFlags & searchFlag.usedBy) == searchFlag.usedBy));
                            this.addCheckBoxInput("search", "Found In", 4, ((searchFlags & searchFlag.foundIn) == searchFlag.foundIn));
                            this.addCheckBoxHeader("Include results from:");
                            this.addCheckBoxInput("include", "List Values", 8, ((includeFlags & includeFlag.listValues) !== includeFlag.listValues));
                            this.addCheckBoxInput("include", "List Labels", 4, ((includeFlags & includeFlag.listLabels) !== includeFlag.listLabels));
                            this.addCheckBoxInput("include", "Multi-Select Lists", 16, ((includeFlags & includeFlag.mslLists) !== includeFlag.mslLists));
                            this.addCheckBoxInput("include", "Referenced Entity Data", 32, ((includeFlags & includeFlag.entityData) !== includeFlag.entityData));
                            this.addCheckBoxInput("include", "Referenced User Data", 64, ((includeFlags & includeFlag.userData) !== includeFlag.userData));
                            this.addCheckBoxInput("include", "Process Data", 2, ((includeFlags & includeFlag.processData) !== includeFlag.processData));
                            this.addCheckBoxHeader("Other options:");
                            this.addCheckBoxInput("condense", "Condense Results", 1, condenseFlags == 1);
                        }
                    });
                }
                setFinderSettings() {
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.POST,
                        url: Jade.Path.resolve("~/Shared/View/SetColumnFinderSettings"),
                        data: {
                            condense: this.getFlagValue("condense"),
                            include: this.getFlagValue("include"),
                            search: this.getFlagValue("search")
                        },
                        success: () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .events
                                .publish(Views.Events.FinderSettingsChanged);
                        }
                    });
                }
                getFlagValue(name) {
                    let result = 0;
                    this.node.find(`input[name=${name}]`).each((index, element) => {
                        let node = $(element);
                        if (node.is(":checked")) {
                            result += parseInt(node.attr("value"));
                        }
                    });
                    return result;
                }
            }
            Views.ColumnsFinderSettings = ColumnsFinderSettings;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var View;
        (function (View) {
            let TemplateTarget;
            (function (TemplateTarget) {
                TemplateTarget[TemplateTarget["origin"] = 0] = "origin";
                TemplateTarget[TemplateTarget["parent"] = 1] = "parent";
                TemplateTarget[TemplateTarget["siblings"] = 2] = "siblings";
                TemplateTarget[TemplateTarget["children"] = 4] = "children";
                TemplateTarget[TemplateTarget["all"] = 8] = "all";
            })(TemplateTarget = View.TemplateTarget || (View.TemplateTarget = {}));
            let CssSelectors;
            (function (CssSelectors) {
                CssSelectors["innerItem"] = "li[data-uid] span.k-in";
                CssSelectors["conditions"] = ".-pd-condition";
                CssSelectors["topMidBot"] = ".k-top, .k-mid, .k-bot";
            })(CssSelectors = View.CssSelectors || (View.CssSelectors = {}));
            class ConstraintsTree extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_constraints = options.constraints;
                    this.state.unset("constraints");
                }
                get treeNode() {
                    return this.node.find(".-pdjs-view-constraints-tree");
                }
                get tree() {
                    return this.m_tree;
                }
                get dataSource() {
                    return this.m_tree.dataSource;
                }
                get constraints() {
                    return this.m_constraints;
                }
                get onChangeCallback() {
                    return this.state.get("onChange", () => { });
                }
                get onConstraintDblClickCallback() {
                    return this.state.get("onConstraintDblClick", () => { });
                }
                get onClickConstraintLinkCallback() {
                    return this.state.get("onClickConstraintLink", () => { });
                }
                get selectedNode() {
                    return this.tree.select();
                }
                get selectedConstraint() {
                    return this.constraints.getConstraint(this.tree.select().data("id"));
                }
                get contextMenu() {
                    return this.state.get("contextMenu");
                }
                get rootConditionNode() {
                    return this.node
                        .children(".k-group")
                        .children(".k-item")
                        .first();
                }
                get rootConditionData() {
                    return this.tree.dataItem(this.rootConditionNode);
                }
                template() {
                    return `<div class="-pd-treeview -pdjs-view-constraints-tree"></div>`;
                }
                addFilter(filtersOptions) {
                    var _a;
                    let options = _.isArray(filtersOptions) ?
                        filtersOptions : [filtersOptions];
                    let filters = this.generateFilters(options);
                    let condition = this.getParentCondition();
                    let conditionNode = this.getParentConditionNode();
                    let hasChildren = condition.hasConditionsOrFilters;
                    filters.forEach(filter => {
                        if (hasChildren) {
                            let filtersCount = condition.filters.count;
                            let insertNode = null;
                            if (this.selectedConstraint instanceof PDJS.Core.Views.Filter) {
                                let index = condition.filters.indexOf(this.selectedConstraint);
                                index == condition.filters.count - 1 ?
                                    condition.filters.add(filter) :
                                    condition.filters.insert(filter, index);
                                insertNode = this.selectedNode;
                            }
                            else {
                                insertNode = filtersCount > 0 ?
                                    this.getInsertNode("filter") :
                                    this.getInsertNode("condition");
                                condition.filters.add(filter);
                            }
                            filtersCount > 0 ?
                                this.tree.insertAfter(filter.toJSON(), insertNode) :
                                this.tree.insertBefore(filter.toJSON(), insertNode);
                        }
                        else {
                            condition.filters.add(filter);
                            this.tree.append(filter.toJSON(), conditionNode);
                        }
                    });
                    if (filters.length > 0) {
                        this.applyNodeTemplateToAllAdjacent((_a = _.last(filters)) === null || _a === void 0 ? void 0 : _a.id);
                    }
                    let addedData = _.last(filters).toJSON();
                    let addedItem = this.tree.dataSource.get(addedData.id);
                    let addedNode = this.tree.findByUid(addedItem.uid);
                    if (addedNode.length > 0) {
                        this.tree.select(addedNode);
                        addedNode.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                    }
                    this.constraints.commit();
                }
                addCondition(conditionOptions) {
                    let condition = this.constraints.addCondition(_.extend({
                        operatorName: "AND"
                    }, conditionOptions), this.selectedConstraint.id);
                    if (condition) {
                        let node = this.tree
                            .append(condition.toKendoData(), this.selectedNode);
                        this.applyNodeTemplateToAllAdjacent(condition.id);
                        this.tree.select(node);
                        node.get(0).scrollIntoView({
                            behavior: "smooth",
                            block: "end"
                        });
                        this.constraints.commit();
                    }
                }
                remove(id) {
                    let fallbackNode = this.getFallbackNode(this.selectedNode);
                    let fallbackConstraint = this.constraints.getConstraint(fallbackNode.data("id"));
                    this.constraints.remove(this.selectedConstraint.id);
                    this.tree.remove(this.selectedNode);
                    this.tree.select(fallbackNode);
                    if (fallbackConstraint) {
                        this.applyNodeTemplateToAllAdjacent(fallbackConstraint.id);
                    }
                    this.constraints.commit();
                }
                clear() {
                    this.constraints.condition.conditions.clear();
                    this.constraints.condition.filters.clear();
                    this.tree.dataSource.data([this.constraints.condition.toKendoData()]);
                    this.applyNodeTemplateToAllAdjacent(this.constraints.condition.id);
                    this.constraints.commit();
                    this.tree.select(this.rootConditionNode);
                }
                setConditionOperator(id, operatorName) {
                    let constraint = this.constraints.getConstraint(id);
                    if (constraint instanceof PDJS.Core.Views.Condition) {
                        constraint.operatorName = operatorName;
                        this.applyNodeTemplateToAllAdjacent(constraint.id);
                        this.constraints.commit();
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.init_contextMenu();
                    this.showMessage();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.showMessage();
                    this.tree.select(this.node.find(".k-item").first());
                }
                init_contextMenu() {
                    if (!this.contextMenu) {
                        return;
                    }
                    let contextMenu = new PDJS.Shared.UI.Controls.TreeViewContextMenu({
                        tree: this.tree,
                        segments: [
                            { type: this.contextMenu }
                        ]
                    });
                    this.controls.add(contextMenu);
                }
                tree_init() {
                    let data = this.constraints.toKendoData();
                    this.m_tree = this.node.kendoTreeView({
                        autoScroll: true,
                        checkboxes: {
                            checkChildren: false
                        },
                        dataTextField: "columnName",
                        dragAndDrop: true,
                        template: _.bind(this.tree_onTemplate, this),
                        drag: _.bind(this.tree_onDrag, this),
                        drop: _.bind(this.tree_onDrop, this),
                        check: _.bind(this.tree_onCheck, this),
                        change: _.bind(this.tree_onChange, this),
                        collapse: (e) => { e.preventDefault(); },
                        expand: (e) => { e.preventDefault(); }
                    }).data("kendoTreeView");
                    this.tree.bind("dataBound", _.bind(this.tree_onDataBound, this));
                    this.tree.dataSource.data(data);
                    this.tree.templates.dragClue = (data) => {
                        return `<div class="k-header k-drag-clue" style="font-size:12px;">
                            <span class="k-icon k-drag-status" />
                            ${(data.item.columnName ? "Moving Filter" : "Moving Group")}
                        </div>`;
                    };
                    this.node.on(Jade.BrowserEvent.DOUBLECLICK, CssSelectors.innerItem, _.bind(this.tree_onDblClick, this));
                    this.node.on(Jade.BrowserEvent.MOUSEDOWN, ".k-item", (e) => {
                        this.tree.select($(e.target));
                    });
                    this.restoreCheckState();
                    this.formatNodes();
                }
                tree_onTemplate(e) {
                    let constraint = this.constraints.getConstraint(e.item.id);
                    let result = constraint != null ?
                        constraint.toMarkup() : "render error";
                    return result;
                }
                tree_onChange(e) {
                    this.node.find(CssSelectors.topMidBot)
                        .removeClass("k-state-selected");
                    this.selectedNode
                        .children(CssSelectors.topMidBot)
                        .addClass("k-state-selected");
                    this.onChangeCallback({
                        constraint: this.selectedConstraint,
                        node: this.selectedNode
                    });
                    this.showMessage();
                }
                tree_onDblClick(e) {
                    this.onConstraintDblClickCallback({
                        constraint: this.selectedConstraint,
                        node: this.selectedNode
                    });
                }
                tree_onDrag(e) {
                    let srcNode = $(e.sourceNode).closest(".k-item");
                    let dstNode = $(e.dropTarget).closest(".k-item");
                    let srcRole = srcNode.data("role") || "unknown";
                    let dstRole = dstNode.data("role") || "unknown";
                    let isAdd = e.statusClass == "add";
                    switch (true) {
                        case isAdd && srcRole == "condition" && dstRole == "condition":
                        case isAdd && srcRole == "filter" && dstRole == "condition":
                        case isAdd && srcRole == "filter" && dstRole == "filter":
                            e.setStatusClass(e.statusClass);
                            break;
                        default:
                            e.setStatusClass("k-denied");
                    }
                }
                tree_onDrop(e) {
                    if (!e.valid) {
                        return;
                    }
                    let srcNode = $(e.sourceNode);
                    let dstNode = $(e.destinationNode);
                    let srcId = srcNode.data("id");
                    let dstId = dstNode.data("id");
                    let srcRole = srcNode.data("role");
                    let dstRole = dstNode.data("role");
                    this.move(srcId, dstId);
                    setTimeout(() => {
                        if (srcRole == "filter") {
                            this.ensureProperFilterDropLocation({
                                srcId: srcId,
                                srcNode: srcNode,
                                srcRole: srcRole,
                                dstId: dstId,
                                dstNode: dstNode,
                                dstRole: dstRole
                            });
                        }
                        this.applyNodeTemplateToAllAdjacent(srcId);
                        this.applyNodeTemplateToAllAdjacent(dstId);
                        this.setIndentations(srcNode);
                    }, 5);
                    if (srcRole == "filter") {
                        e.preventDefault();
                        return false;
                    }
                }
                tree_onDataBound(e) {
                    let item = e.node ?
                        this.tree.dataItem(e.node) :
                        this.tree.dataSource.get(this.constraints.condition.id);
                    if (item) {
                        this.initializeNodes(item.toJSON());
                    }
                }
                tree_onCheck(e) {
                    let node = $(e.node);
                    let constraint = this.constraints.getConstraint(node.data("id"));
                    if (constraint) {
                        constraint.isEnabled = node
                            .children(CssSelectors.topMidBot)
                            .find("input[type=checkbox]")
                            .is(":checked");
                        this.applyNodeTemplate(constraint.id);
                        this.constraints.commit();
                    }
                }
                restoreCheckState() {
                    this.node.find(".k-checkbox > INPUT").each((index, node) => {
                        let constraint = null;
                        let item = $(node).closest(".k-item");
                        let data = this.tree.dataItem(item);
                        constraint = this.constraints.getConstraint(item.data("id"));
                        data.set("checked", constraint.isEnabled);
                    });
                }
                move(srcId, dstId) {
                    let srcConstraint = this.constraints.getConstraint(srcId);
                    let dstConstraint = this.constraints.getConstraint(dstId);
                    if (srcConstraint == null || dstConstraint == null) {
                        return;
                    }
                    if (dstConstraint instanceof PDJS.Core.Views.Condition) {
                        srcConstraint.move(dstConstraint);
                    }
                    if (dstConstraint instanceof PDJS.Core.Views.Filter) {
                        srcConstraint.move(dstConstraint.parent);
                    }
                    this.constraints.commit();
                }
                initializeNodes(origin) {
                    let data = origin ?
                        origin.items || [] :
                        this.tree.dataSource.data();
                    if (origin) {
                        this.initializeNode(origin);
                    }
                    data.forEach(item => {
                        this.initializeNodes(item);
                    });
                }
                initializeNode(data) {
                    let item = this.tree.dataSource.get(data.id);
                    let node = item ?
                        this.tree.findByUid(item.uid) : null;
                    let constraint = this.constraints.getConstraint(item.id);
                    if (constraint) {
                        node.attr("data-id", constraint.id);
                        node.attr("data-role", constraint.role);
                        this.setIndentation(node, constraint.getDepth());
                        this.applyNodeTemplate(data.id);
                    }
                }
                formatNodes() {
                    let notIcon = ":not(:has(span.k-icon))";
                    this.node.find(`.k-top${notIcon}, .k-mid${notIcon}, .k-bot${notIcon}`)
                        .children(".k-checkbox")
                        .before(`<span class="k-icon k-minus" role="presentation"></span>`);
                    this.node.find(".k-in.k-state-selected")
                        .closest(CssSelectors.topMidBot)
                        .addClass("k-state-selected");
                }
                setIndentation(node, depth = 0) {
                    let kin = node.children(".k-top, .k-mid, .k-bot");
                    kin.css({
                        gridTemplateColumns: `${25 * depth}px min-content auto`
                    });
                }
                setIndentations(origin) {
                    let nodes = origin.children(".k-group").find(".k-item");
                    nodes.each((index, element) => {
                        let node = $(element);
                        let constraint = this.constraints.getConstraint(node.data("id"));
                        if (constraint) {
                            this.setIndentation(node, constraint.getDepth());
                        }
                    });
                }
                getFallbackNode(node) {
                    let result = null;
                    let next = node.next();
                    let prev = node.prev();
                    let parent = node.parent().closest(".k-item");
                    switch (true) {
                        case next.length == 1:
                            result = next;
                            break;
                        case prev.length == 1:
                            result = prev;
                            break;
                        case parent.length == 1:
                            result = parent;
                            break;
                    }
                    return result;
                }
                applyNodeTemplate(id) {
                    var _a;
                    let constraint = this.constraints.getConstraint(id);
                    if (constraint == null) {
                        return;
                    }
                    let uid = (_a = this.dataSource.get(id)) === null || _a === void 0 ? void 0 : _a.uid;
                    let span = $(constraint.toMarkup());
                    let node = this.tree.findByUid(uid);
                    let kin = node.find(".k-in").first();
                    let checkbox = node
                        .children(CssSelectors.topMidBot)
                        .children(".k-checkbox")
                        .children("input");
                    constraint.isEnabled ?
                        node.removeClass("-pdjs-disabled") :
                        node.addClass("-pdjs-disabled");
                    checkbox.prop("checked", constraint.isEnabled);
                    kin.empty();
                    kin.html(span[0].outerHTML);
                    span.hide();
                    this.setIndentation(node, constraint.getDepth());
                    this.formatNodes();
                }
                applyNodeTemplateToParent(id) {
                    let constraint = this.constraints.getConstraint(id);
                    if (!constraint) {
                        return;
                    }
                    if (constraint.parent) {
                        this.applyNodeTemplate(constraint.parent.id);
                    }
                }
                applyNodeTemplateToSiblings(id) {
                    let constraint = this.constraints.getConstraint(id);
                    if (!constraint) {
                        return;
                    }
                    if (constraint.parent) {
                        constraint.parent.conditions.each(condition => {
                            this.applyNodeTemplate(condition.id);
                        });
                        constraint.parent.filters.each(condition => {
                            this.applyNodeTemplate(condition.id);
                        });
                    }
                }
                applyNodeTemplateToChildren(id) {
                    let constraint = this.constraints.getConstraint(id);
                    if (!constraint) {
                        return;
                    }
                    if (constraint instanceof PDJS.Core.Views.Condition) {
                        constraint.conditions.each(condition => {
                            this.applyNodeTemplate(condition.id);
                        });
                        constraint.filters.each(condition => {
                            this.applyNodeTemplate(condition.id);
                        });
                    }
                }
                applyNodeTemplateToAllAdjacent(id) {
                    this.applyNodeTemplateToParent(id);
                    this.applyNodeTemplateToSiblings(id);
                    this.applyNodeTemplateToChildren(id);
                    this.applyNodeTemplate(id);
                }
                getParentCondition() {
                    var _a;
                    switch ((_a = this.selectedConstraint) === null || _a === void 0 ? void 0 : _a.role) {
                        case "condition":
                            return this.selectedConstraint;
                            break;
                        case "filter":
                            return this.selectedConstraint.parent;
                            break;
                    }
                }
                getParentConditionNode() {
                    switch (this.selectedNode.data("role")) {
                        case "condition":
                            return this.selectedNode;
                            break;
                        case "filter":
                            return this.selectedNode.parent().closest(".k-item");
                            break;
                    }
                }
                generateFilters(items) {
                    let result = [];
                    let parent = this.getParentCondition();
                    items.forEach(item => {
                        result.push(new PDJS.Core.Views.Filter(_.extend(item, {
                            parent: parent
                        })));
                    });
                    return result;
                }
                ensureProperFilterDropLocation(e) {
                    var _a;
                    let srcNodeData = (_a = this.tree.dataItem(e.srcNode)) === null || _a === void 0 ? void 0 : _a.toJSON();
                    let parentNode = e.dstRole == "condition" ?
                        e.dstNode : e.dstNode.parent().closest(".k-item");
                    let lastFilterNode = parentNode
                        .children(`.k-group`)
                        .children(`.k-item[data-role=filter]:not([data-id=${e.srcId}])`)
                        .last();
                    let firstConditionNode = parentNode
                        .children(`.k-group`)
                        .children(".k-item[data-role=condition]")
                        .first();
                    switch (true) {
                        case lastFilterNode.length > 0:
                            this.tree.remove(e.srcNode);
                            this.tree.insertAfter(srcNodeData, lastFilterNode);
                            break;
                        case firstConditionNode.length > 0:
                            this.tree.remove(e.srcNode);
                            this.tree.insertBefore(srcNodeData, firstConditionNode);
                            break;
                        default:
                            this.tree.remove(e.srcNode);
                            this.tree.append(srcNodeData, parentNode);
                            break;
                    }
                }
                getInsertNode(role) {
                    let conditionNode = this.selectedNode.data("role") == "filter" ?
                        this.selectedNode.parent().closest(".k-item") :
                        this.selectedNode;
                    let itemNodes = conditionNode
                        .children(".k-group")
                        .children(`.k-item[data-role=${role}]`);
                    let result = role == "condition" ?
                        itemNodes.first().closest(".k-item") :
                        itemNodes.last().closest(".k-item");
                    return result;
                }
                showMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (!message) {
                        message = new PDJS.Shared.UI.Controls.Message({
                            message: `No filters have been added.<br/>
                                Add a <a href="#" role="filter">filter</a>.`
                        });
                        this.controls.add(message);
                        message.node.on(Jade.BrowserEvent.CLICK, "a[role]", (e) => {
                            this.onClickConstraintLinkCallback({
                                type: $(e.target).attr("role")
                            });
                            return false;
                        });
                    }
                    message.node.css({
                        position: "absolute",
                        top: 0,
                        bottom: 0,
                        height: "auto",
                        backgroundColor: "var(--visiv-theme-base-1-back-color)"
                    });
                    this.constraints.condition.hasConditionsOrFilters ?
                        message.node.hide() :
                        message.node.show();
                }
            }
            View.ConstraintsTree = ConstraintsTree;
        })(View = Shared.View || (Shared.View = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get toolbarNode() {
                    return this.node.children("div[role=toolbar]");
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get headerNode() {
                    return this.node.children("div[role=header]");
                }
                template() {
                    return `
                <div class="-pdjs-view-filters-editor">
                    <div role="toolbar"></div>
                    <div role="header"></div>
                    <div role="content" data-controls></div>
                </div>`;
                }
                save(callback) {
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.POST,
                        contentType: "application/json",
                        url: Jade.Path.resolve(`~/Shared/ViewFilters/Set${this.componentType}`),
                        data: JSON.stringify({
                            viewStateId: this.viewStateId,
                            condition: this.m_tree.pull()
                        }),
                        success: (e) => {
                            if (_.isFunction(callback)) {
                                callback();
                            }
                        }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.initializationRequest();
                }
                tree_init(data) {
                    this.m_tree = new Views.FiltersEditorTree({
                        viewStateId: this.viewStateId
                    });
                    this.controls.add(this.m_tree);
                    this.m_tree.load(data);
                }
                toolbar_init() {
                    this.m_toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.FiltersDialogToolBarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                initializationRequest() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewFilters/Get${this.componentType}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.tree_init(e.condition);
                            this.toolbar_init();
                            this.m_tree.setCommandState();
                        }
                    });
                }
            }
            Views.FiltersEditor = FiltersEditor;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersEditorTemplates {
                static filterTemplate(filter) {
                    return `
            <div role="filter">
                <div data-checkbox><input type="checkbox" ${filter.checked ? "checked" : ""}/></div>
                <div data-name>${filter.name}</div>
                <div data-operator="${!filter.operator ? "notset" : ""}">${this.convertOperatorToText(filter.operator)}</div>
                <div data-verse>${filter.verse || (filter.value || "")}</div>
            </div>`;
                }
                static conditionTemplate(condition) {
                    return `
            <div role="condition">
                <div data-checkbox><input type="checkbox" ${condition.checked ? "checked" : ""}/></div>
                <div data-name>${condition.type}</div>
            </div>`;
                }
                static applyContentTemplate(node, content) {
                    let target = node.children("div").find(".k-in");
                    target.empty();
                    target.html(content);
                }
                static convertOperatorToText(operator) {
                    operator = parseInt((operator || Views.FilterOperator.NotSet).toString());
                    let result = "Not Set";
                    switch (operator) {
                        case Views.FilterOperator.Contains:
                            result = "contains";
                            break;
                        case Views.FilterOperator.EndsWith:
                            result = "ends with";
                            break;
                        case Views.FilterOperator.EQ:
                            result = "equals";
                            break;
                        case Views.FilterOperator.GE:
                            result = "is greater than or equal to";
                            break;
                        case Views.FilterOperator.GT:
                            result = "is greater than";
                            break;
                        case Views.FilterOperator.HasTag:
                            result = "has tag";
                            break;
                        case Views.FilterOperator.InList:
                            result = "is in list";
                            break;
                        case Views.FilterOperator.IsNull:
                            result = "is null";
                            break;
                        case Views.FilterOperator.LE:
                            result = "is less than or equal to";
                            break;
                        case Views.FilterOperator.LT:
                            result = "is less than";
                            break;
                        case Views.FilterOperator.NE:
                            result = "is not equal to";
                            break;
                        case Views.FilterOperator.NotContains:
                            result = "does not contain";
                            break;
                        case Views.FilterOperator.NotEndsWith:
                            result = "does not end with";
                            break;
                        case Views.FilterOperator.NotHasTag:
                            result = "does not have tag";
                            break;
                        case Views.FilterOperator.NotInList:
                            result = "is not in list";
                            break;
                        case Views.FilterOperator.NotNull:
                            result = "is not null";
                            break;
                        case Views.FilterOperator.NotSet:
                            result = "Not Set";
                            break;
                        case Views.FilterOperator.NotStartsWith:
                            result = "does not start with";
                            break;
                        case Views.FilterOperator.StartsWith:
                            result = "starts with";
                            break;
                    }
                    return result;
                }
            }
            Views.FiltersEditorTemplates = FiltersEditorTemplates;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let FilterOperator;
            (function (FilterOperator) {
                FilterOperator[FilterOperator["NotSet"] = 0] = "NotSet";
                FilterOperator[FilterOperator["EQ"] = 1] = "EQ";
                FilterOperator[FilterOperator["NE"] = 2] = "NE";
                FilterOperator[FilterOperator["GE"] = 4] = "GE";
                FilterOperator[FilterOperator["GT"] = 8] = "GT";
                FilterOperator[FilterOperator["LE"] = 16] = "LE";
                FilterOperator[FilterOperator["LT"] = 32] = "LT";
                FilterOperator[FilterOperator["IsNull"] = 64] = "IsNull";
                FilterOperator[FilterOperator["NotNull"] = 128] = "NotNull";
                FilterOperator[FilterOperator["StartsWith"] = 256] = "StartsWith";
                FilterOperator[FilterOperator["EndsWith"] = 512] = "EndsWith";
                FilterOperator[FilterOperator["Contains"] = 1024] = "Contains";
                FilterOperator[FilterOperator["HasTag"] = 2048] = "HasTag";
                FilterOperator[FilterOperator["NotStartsWith"] = 4096] = "NotStartsWith";
                FilterOperator[FilterOperator["NotEndsWith"] = 8192] = "NotEndsWith";
                FilterOperator[FilterOperator["NotContains"] = 16384] = "NotContains";
                FilterOperator[FilterOperator["NotHasTag"] = 32768] = "NotHasTag";
                FilterOperator[FilterOperator["InList"] = 65536] = "InList";
                FilterOperator[FilterOperator["NotInList"] = 131072] = "NotInList";
            })(FilterOperator = Views.FilterOperator || (Views.FilterOperator = {}));
            class FiltersEditorTree extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get tree() {
                    return this.m_tree;
                }
                get treeNode() {
                    return this.node.find("div[role=tree]");
                }
                template() {
                    return `<div data-controls>
                        <div role="tree"></div>
                    </div>`;
                }
                load(condition) {
                    let data = null;
                    if (condition != null) {
                        data = this.parseToTreeData(condition);
                    }
                    if (data != null) {
                        data.selected = true;
                        this.tree.dataSource.data([data]);
                    }
                    this.showMessage();
                }
                pull() {
                    let data = this.tree.dataSource.data().toJSON();
                    let result = null;
                    if (data.length > 0) {
                        result = this.parseFromTreeData(data[0]);
                    }
                    return result;
                }
                setCommandState() {
                    this.pushContextState();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.tree_init();
                    this.tree.element
                        .off('dblclick', '.k-in:not(.k-state-disabled)')
                        .on(Jade.BrowserEvent.DOUBLECLICK, "li[data-uid] .k-in", (e) => {
                        let node = $(e.target).closest(".k-item");
                        this.tree_nodeDoubleClick(node);
                        e.preventDefault();
                        e.stopPropagation();
                        e.cancelBubble = true;
                        e.returnValue = false;
                        return false;
                    });
                    this.tree.element.on(Jade.BrowserEvent.CLICK, "input[type=checkbox]", (e) => {
                        let node = $(e.target);
                        this.check(node.is(":checked"), node.closest("li"));
                    });
                    this.subscriptions.add("filters/changed", () => {
                        this.showMessage();
                    });
                    this.pushContextState();
                }
                tree_init() {
                    this.m_tree = this.treeNode.kendoTreeView({
                        autoScroll: true,
                        dataSource: new kendo.data.HierarchicalDataSource({
                            data: []
                        }),
                        dragAndDrop: true,
                        template: (e) => {
                            let item = e.item;
                            switch (item.role) {
                                case "filter":
                                    return Views.FiltersEditorTemplates.filterTemplate(item);
                                case "condition":
                                    return Views.FiltersEditorTemplates.conditionTemplate(item);
                            }
                            return "error";
                        },
                        change: (e) => {
                            this.pushContextState();
                        },
                        drop: (e) => {
                            this.tree_drop(e);
                        },
                        drag: (e) => {
                            this.tree_drag(e);
                        },
                        dragend: (e) => {
                            this.tree_dragend(e);
                        }
                    }).data("kendoTreeView");
                    let dragClueTemplate = `
                <div class='k-header k-drag-clue -pdjs-view-filters-editor-drag-clue'>
                    <span>
                        <span class='k-icon k-drag-status' />
                    </span>
                    <span style="">
                        # if (item.name != null) { #
                            #= item.name #
                        # } else { #
                            #: item.type #
                        # } #
                    </span>
                </div>
            `;
                    this.m_tree.templates.dragClue =
                        kendo.template(dragClueTemplate);
                }
                tree_nodeDoubleClick(node) {
                    let item = this.tree.dataItem(node);
                    this.pushContextState();
                    switch (item.get("role")) {
                        case "condition":
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/filters:condition/convert");
                            break;
                        case "filter":
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/filters:filter/edit");
                            break;
                    }
                }
                tree_drag(e) {
                    let srcItem = this.tree.dataItem(e.sourceNode);
                    let dstItem = this.tree.dataItem(e.dropTarget);
                    let dropType = this.getDropType(srcItem, dstItem);
                    let isDropBetween = e.statusClass == "insert-top" ||
                        e.statusClass == "insert-middle" ||
                        e.statusClass == "insert-bottom";
                    if (isDropBetween || dropType === "ConditionOnFilter") {
                        e.setStatusClass("denied");
                    }
                }
                tree_drop(e) {
                    let srcData = this.tree.dataItem(e.sourceNode);
                    let dstData = this.tree.dataItem(e.destinationNode);
                    let srcItem = srcData;
                    let dstItem = dstData;
                    ;
                    if (dstItem == null) {
                        return;
                    }
                    if (e.dropPosition != "over") {
                        e.setValid(false);
                    }
                    let dropType = this.getDropType(srcItem, dstItem);
                    if (dropType === "ConditionOnFilter") {
                        e.setValid(false);
                    }
                }
                tree_dragend(e) {
                    let srcData = this.tree.dataItem(e.sourceNode);
                    let dstData = this.tree.dataItem(e.destinationNode);
                    let srcItem = srcData;
                    let dstItem = dstData;
                    ;
                    if (dstItem == null) {
                        return;
                    }
                    let dropType = this.getDropType(srcItem, dstItem);
                    let srcNode = null;
                    let dstNode = null;
                    let sibNode = null;
                    let newSrcNode = null;
                    switch (dropType) {
                        case "ConditionOnCondition":
                            dstNode = $(e.destinationNode);
                            srcNode = $(e.sourceNode);
                            sibNode = Views.FiltersEditorTreeActions.getFirstChildFilter(dstNode);
                            this.tree.remove(e.sourceNode);
                            if (sibNode.length == 1) {
                                this.tree.insertBefore(srcData.toJSON(), sibNode);
                                newSrcNode = sibNode.prev();
                            }
                            else {
                                newSrcNode = this.tree.append(srcData, dstNode);
                            }
                            this.tree.select(newSrcNode);
                            break;
                        case "FilterOnFilter":
                            sibNode = $(e.destinationNode);
                            this.tree.remove(e.sourceNode);
                            this.tree.insertAfter(srcData.toJSON(), sibNode);
                            newSrcNode = sibNode.next();
                            this.tree.select(newSrcNode);
                            break;
                        case "ConditionOnFilter":
                            dstNode = this.tree.parent(e.destinationNode);
                            sibNode = Views.FiltersEditorTreeActions.getFirstChildFilter(dstNode);
                            this.tree.remove(e.sourceNode);
                            this.tree.insertBefore(srcData.toJSON(), sibNode);
                            newSrcNode = sibNode.prev();
                            this.tree.select(newSrcNode);
                            break;
                    }
                }
                parseToTreeData(condition) {
                    condition.items = [];
                    condition.conditions = condition.conditions || [];
                    condition.filters = condition.filters || [];
                    condition.role = "condition";
                    condition.checked = condition.enabled;
                    condition.enabled = true;
                    condition.expanded = true;
                    condition.conditions.forEach(item => {
                        condition.items.push(item);
                        this.parseToTreeData(item);
                    });
                    condition.filters.forEach(item => {
                        item.role = "filter";
                        item.checked = item.enabled;
                        item.enabled = true;
                        item.expanded = true;
                        condition.items.push(item);
                    });
                    return condition;
                }
                parseFromTreeData(condition) {
                    condition.items = condition.items || [];
                    condition.conditions = [];
                    condition.filters = [];
                    condition.enabled = condition.checked;
                    condition.items.forEach(item => {
                        switch (item.role) {
                            case "condition":
                                condition.conditions.push(item);
                                this.parseFromTreeData(item);
                                break;
                            case "filter":
                                item.enabled = item.checked;
                                condition.filters.push(item);
                                break;
                        }
                    });
                    return condition;
                }
                pushContextState() {
                    let node = this.tree.select();
                    let item = this.tree.dataItem(node);
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/filters": {
                            $tree: this.tree,
                            viewStateId: this.viewStateId,
                            $selectedItem: item || null
                        }
                    }, { force: true });
                }
                check(checked, node) {
                    let item = this.tree.dataItem(node);
                    item.set("checked", checked);
                    node.children("ul")
                        .children("li")
                        .children("div")
                        .find("input[type=checkbox]")
                        .each((index, element) => {
                        let input = $(element);
                        input.prop("checked", checked);
                        this.check(checked, input);
                    });
                }
                showMessage() {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    let data = this.tree.dataSource.data().toJSON();
                    if (message == null) {
                        message = new PDJS.Shared.UI.Controls.Message({
                            message: "No filters have been added to the view."
                        });
                        this.controls.add(message);
                        message.node.css({
                            position: "absolute"
                        });
                    }
                    data.length == 0 ? message.node.show() : message.node.hide();
                }
                getDropType(srcItem, dstItem) {
                    if (dstItem == null) {
                        return "Unknown";
                    }
                    let conditionOnCondition = srcItem.role == "condition" &&
                        dstItem.role == "condition";
                    let filterOnFilter = srcItem.role == "filter" &&
                        dstItem.role == "filter";
                    let conditionOnFilter = srcItem.role == "condition" &&
                        dstItem.role == "filter";
                    let filterOnCondition = srcItem.role == "filter" &&
                        dstItem.role == "condition";
                    switch (true) {
                        case conditionOnCondition:
                            return "ConditionOnCondition";
                        case filterOnFilter:
                            return "FilterOnFilter";
                        case conditionOnFilter:
                            return "ConditionOnFilter";
                        case filterOnCondition:
                            return "FilterOnCondition";
                        default:
                            return "Unknown";
                    }
                }
            }
            Views.FiltersEditorTree = FiltersEditorTree;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersEditorTreeActions {
                static addCondtion(tree, condition) {
                    condition.role = "condition";
                    let parentNode = tree.select();
                    let parentItem = null;
                    if (parentNode.length > 0) {
                        parentItem = tree.dataItem(parentNode).toJSON();
                    }
                    let resultNode = null;
                    if (parentItem != null) {
                        switch (parentItem.role) {
                            case "condition":
                                resultNode = this.addConditionWhenConditionSelected(tree, condition, parentNode);
                                break;
                            case "filter":
                                resultNode = this.addConditionWhenFilterSelected(tree, condition, parentNode);
                                break;
                        }
                    }
                    else {
                        resultNode = tree.append(condition);
                    }
                    tree.select(resultNode);
                    return resultNode;
                }
                static addFilter(tree, filter, parentNode = null) {
                    filter.role = "filter";
                    parentNode = parentNode || tree.select();
                    let parentItem = null;
                    if (parentNode.length > 0) {
                        parentItem = tree.dataItem(parentNode).toJSON();
                    }
                    let resultNode = null;
                    switch (parentItem.role) {
                        case "condition":
                            resultNode = tree.append(filter, parentNode);
                            break;
                        case "filter":
                            tree.insertAfter(filter, parentNode);
                            resultNode = parentNode.next();
                            break;
                    }
                    tree.select(resultNode);
                    return resultNode;
                }
                static getLastChildCondition(root) {
                    return root
                        .children("ul")
                        .children("li")
                        .children("div")
                        .find("[role=condition]")
                        .last();
                }
                static getFirstChildFilter(root) {
                    return root
                        .children("ul")
                        .children("li")
                        .children("div")
                        .find("[role=filter]")
                        .first();
                }
                static addConditionWhenFilterSelected(tree, condition, selectedNode) {
                    let resultNode = null;
                    let parentNode = selectedNode.parent().closest("li");
                    let nearestCondition = this.getLastChildCondition(parentNode);
                    let nearestFilter = this.getFirstChildFilter(parentNode);
                    switch (true) {
                        case nearestCondition.length > 0:
                            tree.insertAfter(condition, nearestCondition);
                            resultNode = this.getLastChildCondition(parentNode);
                            break;
                        case nearestFilter.length > 0:
                            tree.insertBefore(condition, nearestFilter);
                            resultNode = this.getLastChildCondition(parentNode);
                            break;
                    }
                    return resultNode;
                }
                static addConditionWhenConditionSelected(tree, condition, selectedNode) {
                    let resultNode = null;
                    let childCondition = this.getLastChildCondition(selectedNode);
                    let childFilter = this.getFirstChildFilter(selectedNode);
                    switch (true) {
                        case childCondition.length > 0:
                            tree.insertAfter(condition, childCondition);
                            resultNode = this.getLastChildCondition(selectedNode);
                            break;
                        case childFilter.length > 0:
                            tree.insertBefore(condition, childFilter);
                            resultNode = this.getLastChildCondition(selectedNode);
                            break;
                        default:
                            resultNode = tree.append(condition, selectedNode);
                            break;
                    }
                    return resultNode;
                }
            }
            Views.FiltersEditorTreeActions = FiltersEditorTreeActions;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var FieldValidationError = PDJS.Shared.UI.Controls.Fields.FieldValidationError;
            class FilterEditorBase extends PDJS.Shared.Features.Editors.Macro.MacroEditor {
                get defaultHeight() {
                    return 170 +
                        (this.supportsAutos ? 50 : 0) +
                        (this.supportsScalars ? 50 : 0);
                    ;
                }
                get defaultWidth() {
                    return 350;
                }
                get autosContainer() {
                    return this.node.children("div[role=autos]");
                }
                get autosInput() {
                    return this.m_autoValueInput;
                }
                get autosInputValue() {
                    return this.m_autoValueInput.value;
                }
                set autosInputValue(value) {
                    this.m_autoValueInput.value = value;
                }
                get autosList() {
                    return this.source.feature.getValue("autoValues", []);
                }
                get autoValueId() {
                    return this.source.getFeatureValue("autoValueId");
                }
                set autoValueId(value) {
                    this.source.setFeatureValue("autoValueId", value, { postback: true });
                }
                get autoValueName() {
                    return this.source.getFeatureValue("autoValueName");
                }
                set autoValueName(value) {
                    this.source.setFeatureValue("autoValueName", value);
                }
                get operatorId() {
                    return this.source.getFeatureValue("operatorId", 0);
                }
                set operatorId(value) {
                    this.source.setFeatureValue("operatorId", value);
                }
                get operatorInput() {
                    return this.m_operatorInput;
                }
                get operatorInputValue() {
                    return this.m_operatorInput.value;
                }
                set operatorInputValue(value) {
                    this.m_operatorInput.value = value;
                }
                get operatorList() {
                    return this.source.feature.getValue("operators", []);
                }
                get operatorContainer() {
                    return this.node.children("select[role=operator]");
                }
                get providerContainer() {
                    return this.node.children("div[role=provider]");
                }
                get providerInput() {
                    return this.m_providerInput;
                }
                get providerInputValue() {
                    return this.m_providerInput.value == "true";
                }
                set providerInputValue(value) {
                    this.m_providerInput.value = value;
                }
                get scalarFunctionId() {
                    return this.source.getRemoteFeatureValue("scalarFunctionId");
                }
                set scalarFunctionId(value) {
                    this.source.setFeatureValue("scalarFunctionId", value, { postback: true });
                }
                get scalarFunctionName() {
                    return this.source.getRemoteFeatureValue("scalarFunctionName");
                }
                set scalarFunctionName(value) {
                    this.source.setFeatureValue("scalarFunctionName", value);
                }
                get scalarsContainer() {
                    return this.node.children("div[role=scalar]");
                }
                get scalarsInput() {
                    return this.node.children("div[role=scalar]");
                }
                get scalarsInputValue() {
                    return this.m_scalarValueInput.value;
                }
                set scalarsInputValue(value) {
                    this.m_scalarValueInput.value = value;
                }
                get scalarsList() {
                    return this.source.getRemoteFeatureValue("scalarFunctions", []);
                }
                get supportsAutos() {
                    return this.source.getFeatureValue("supportsAutoValues", false);
                }
                get supportsScalars() {
                    return this.scalarsList.length > 0;
                }
                get useAutos() {
                    return this.source.getFeatureValue("useAutoValue", false);
                }
                set useAutos(value) {
                    this.source.setFeatureValue("useAutoValue", value, { postback: true });
                }
                get valueContainer() {
                    return this.node.children("div[role=value]");
                }
                get value() {
                    return this.source.getFeatureValue("value");
                }
                set value(value) {
                    this.source.setFeatureValue("value", value);
                }
                template() {
                    return `<div class="-pdjs-view-filter-editor">
                        <div role="provider"></div>
                        <div role="scalar"></div>
                        <div role="operator"></div>
                        <div role="autos"></div>
                        <div role="value" data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.operator_init();
                    this.provider_init();
                    this.scalar_init();
                    this.autoValue_init();
                    this.configureUI();
                    this.setDialogDimensions();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.operatorInputValue = this.operatorId;
                    this.scalarsInputValue = this.scalarFunctionId;
                    this.providerInputValue = this.useAutos;
                    this.autosInputValue = this.autoValueId;
                }
                configureUI() {
                    this.node.css({
                        gridTemplateRows: `${this.supportsAutos ? "50px" : ""} ${this.supportsScalars ? "50px" : ""} 50px auto`
                    });
                    this.supportsAutos ?
                        this.providerContainer.show() :
                        this.providerContainer.hide();
                    this.supportsScalars ?
                        this.scalarsContainer.show() :
                        this.scalarsContainer.hide();
                    this.useAutos ?
                        this.autosContainer.show() :
                        this.autosContainer.hide();
                    this.useAutos ?
                        this.valueContainer.hide() :
                        this.valueContainer.show();
                }
                setDialogDimensions() {
                    this.setDimensons({
                        height: this.defaultHeight,
                        width: this.defaultWidth
                    });
                }
                onValidationErrors() {
                    super.onValidationErrors();
                    this.source.feature.errors.forEach(error => {
                        error.propertyName === "AutoValueId" ?
                            this.autosInput.errors.add(new FieldValidationError({
                                message: error.message
                            })) : null;
                    });
                }
                provider_init() {
                    this.m_providerInput = new PDJS.Shared.UI.Controls.Fields.SelectField({
                        insertAt: "div[role=provider]",
                        label: "Where Current Value",
                        items: [
                            { label: "Is Supplied By Me", value: "false" },
                            { label: "Is Supplied By System", value: "true" }
                        ],
                        change: () => {
                            this.useAutos =
                                this.providerInputValue;
                        }
                    });
                    this.controls.add(this.m_providerInput);
                }
                scalar_init() {
                    var getScalarName = (id) => {
                        let result = null;
                        this.scalarsList.forEach(item => {
                            (item.id == id) ?
                                result = item.name : null;
                        });
                        return result || "";
                    };
                    this.m_scalarValueInput = new PDJS.Shared.UI.Controls.Fields.SelectField({
                        insertAt: "div[role=scalar]",
                        label: "Filter Using",
                        items: this.scalarsList,
                        binding: { label: "name", value: "id" },
                        change: () => {
                            this.scalarFunctionId =
                                this.scalarsInputValue;
                            this.scalarFunctionName =
                                getScalarName(this.scalarFunctionId);
                            this.clearAutoValue();
                        }
                    });
                    this.controls.add(this.m_scalarValueInput);
                }
                operator_init() {
                    this.m_operatorInput = new PDJS.Shared.UI.Controls.Fields.SelectField({
                        insertAt: "div[role=operator]",
                        label: this.supportsAutos ? "and" : "Where Current Value",
                        items: this.operatorList,
                        binding: { label: "name", value: "id" },
                        change: () => {
                            this.operatorId =
                                this.operatorInputValue;
                        }
                    });
                    this.controls.add(this.m_operatorInput);
                }
                autoValue_init() {
                    var getAutoName = (id) => {
                        let result = null;
                        this.autosList.forEach(item => {
                            (item.value == id) ?
                                result = item.name : null;
                        });
                        return result || "";
                    };
                    this.m_autoValueInput = new PDJS.Shared.UI.Controls.Fields.SelectField({
                        insertAt: "div[role=autos]",
                        label: "System Value",
                        items: this.autosList,
                        binding: { label: "name", value: "id" },
                        change: () => {
                            this.autoValueId = this.autosInputValue;
                            this.autoValueName = getAutoName(this.autosInputValue);
                            this.clearScalar();
                        }
                    });
                    this.controls.add(this.m_autoValueInput);
                }
                clearAutoValue() {
                    this.autoValueId = null;
                    this.autoValueName = null;
                }
                clearScalar() {
                    this.scalarFunctionId = null;
                    this.scalarFunctionName = null;
                }
            }
            Views.FilterEditorBase = FilterEditorBase;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var FieldValidationError = PDJS.Shared.UI.Controls.Fields.FieldValidationError;
            class FilterListEditor extends Views.FilterEditorBase {
                get value() {
                    return !Jade.String.isNullOrWhiteSpace(super.value) ?
                        super.value : [];
                }
                set value(value) {
                    super.value = value;
                }
                get valueInput() {
                    return this.m_valueInput;
                }
                get listItems() {
                    return this.source.getFeatureValue("listItems");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    if (!this.useAutos) {
                    }
                }
                configureUI() {
                    super.configureUI();
                }
                onValidationErrors() {
                    super.onValidationErrors();
                    this.source.feature.errors.forEach(error => {
                        error.propertyName === "Value" ?
                            this.valueInput.errors.add(new FieldValidationError({
                                message: error.message
                            })) : null;
                    });
                }
                setDialogDimensions() {
                    this.setDimensons({
                        height: this.defaultHeight + 150,
                        width: this.defaultWidth
                    });
                }
                input_init() {
                    let data = [];
                    this.listItems.forEach(item => {
                        data.push(_.extend(item, {
                            checked: this.value.indexOf(item.value) > -1
                        }));
                    });
                    this.m_valueInput = new PDJS.Shared.UI.Controls.Fields.MultiSelectField({
                        label: "Value",
                        items: data,
                        height: "100%",
                        binding: { label: "name", value: "value" },
                        check: () => {
                            let values = this.valueInput.selected.map((item) => {
                                return item.value;
                            });
                            this.value = values;
                        }
                    });
                    this.controls.add(this.m_valueInput);
                }
            }
            Views.FilterListEditor = FilterListEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Views.FilterListEditor", FilterListEditor);
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var FieldValidationError = PDJS.Shared.UI.Controls.Fields.FieldValidationError;
            class FilterSimpleEditor extends Views.FilterEditorBase {
                get valueInput() {
                    return this.m_valueInput;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.input_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    if (!this.useAutos) {
                        this.valueInput.value = this.value;
                    }
                }
                configureUI() {
                    super.configureUI();
                    this.node.css({ height: "50px" });
                }
                onValidationErrors() {
                    super.onValidationErrors();
                    this.source.feature.errors.forEach(error => {
                        error.propertyName === "Value" ?
                            this.valueInput.errors.add(new FieldValidationError({
                                message: error.message
                            })) : null;
                    });
                }
                input_init() {
                    this.m_valueInput = new PDJS.Shared.UI.Controls.Fields.StringField({
                        label: "Value",
                        blur: () => {
                            this.value = this.valueInput.value;
                        }
                    });
                    this.controls.add(this.m_valueInput);
                }
            }
            Views.FilterSimpleEditor = FilterSimpleEditor;
            FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Shared.Views.FilterSimpleEditor", FilterSimpleEditor);
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersDialog extends Jade.UI.Dialogs.Dialog {
                constructor(options) {
                    super(options);
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get settingsButtonNode() {
                    return this.node.find("button[data-command=settings]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                template() {
                    return super.template(`
                <div class="-pdjs-view-filters-dialog">
                    <div role="content">
                        <div role="splitter">
                            <div>
                                <div role="finder"></div>
                            </div>
                            <div>
                                <div role="editor"></div>
                            </div>
                        </div>
                    </div>
                    <div role="buttons">
                        <div>
                            <button class="-pdjs-dialog-button" data-command="settings">Settings</button>
                        </div>
                        <div>
                            <button class="-pdjs-dialog-button" data-command="ok">OK</button>
                            <button class="-pdjs-dialog-button" data-command="cancel">Cancel</button>
                        </div>
                    </div>
                </div>`);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.okButton_onClick(e);
                    });
                    this.cancelButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.cancelButton_onClick(e);
                    });
                    this.settingsButtonNode.on(Jade.BrowserEvent.CLICK, (e) => {
                        this.settingsButton_onClick(e);
                    });
                    this.splitter_init();
                    this.initializationRequest();
                    this.setDialogTitle();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                getDefaultOptions() {
                    return {
                        height: 500,
                        width: 600
                    };
                }
                okButton_onClick(e) {
                    this.m_editor.save(() => {
                        this.close({
                            name: "ok"
                        });
                    });
                }
                cancelButton_onClick(e) {
                    this.close({
                        name: "cancel"
                    });
                }
                settingsButton_onClick(e) {
                    this.m_popup.show();
                }
                splitter_init() {
                    this.m_splitter = this.splitterNode.kendoSplitter({
                        orientation: "vertical",
                        panes: [
                            { size: "50%", resizable: true },
                            {}
                        ]
                    }).data("kendoSplitter");
                }
                editor_init() {
                    this.m_editor = new Views.FiltersEditor({
                        insertAt: "div[role=editor]",
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        change: () => {
                            this.setCommandState();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                finder_init(anchorDepths, excludeColumns) {
                    this.m_finder = new Views.ColumnsFinder({
                        insertAt: "div[role=finder]",
                        componentTarget: "filters",
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        anchorDepths: anchorDepths,
                        excludeColumns: excludeColumns,
                        change: () => {
                            this.setCommandState();
                        },
                        dblclick: () => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("view/filters:filter/add");
                        }
                    });
                    this.controls.add(this.m_finder);
                }
                popup_init() {
                    this.m_popup =
                        new Views.ColumnsFinderSettings({
                            componentType: this.componentType,
                            viewStateId: this.viewStateId,
                            anchor: this.settingsButtonNode,
                            height: 320,
                            width: 200
                        });
                    this.controls.add(this.m_popup);
                }
                setDialogTitle() {
                    switch (this.componentType) {
                        case "bounds":
                            this.setWindowOptions({ title: "View Bounds Filters" });
                            return;
                        case "design":
                            this.setWindowOptions({ title: "View Design Filters" });
                            return;
                    }
                }
                initializationRequest() {
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewFilters/Get${this.componentType}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.editor_init();
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                setCommandState() {
                    if (this.m_finder == null || this.m_editor == null) {
                        return;
                    }
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/filters": {
                            componentType: this.componentType,
                            $editor: this.m_editor,
                            $finder: this.m_finder
                        }
                    }, { force: true });
                }
                static open(options, windowOptions = {}) {
                    return new FiltersDialog(options);
                }
            }
            Views.FiltersDialog = FiltersDialog;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            let SelectedNodeType;
            (function (SelectedNodeType) {
                SelectedNodeType["None"] = "none";
                SelectedNodeType["Condition"] = "condition";
                SelectedNodeType["Filter"] = "filter";
            })(SelectedNodeType = Views.SelectedNodeType || (Views.SelectedNodeType = {}));
            class FiltersDialogCommand extends Jade.Command {
                constructor(options) {
                    super(options);
                    this.state.set("componentType", null);
                    this.state.set("viewStateId", null);
                    this.state.set("$finder", null);
                    this.state.set("$selectedItem", null);
                    this.state.set("$tree", null);
                }
                get componentType() {
                    return this.state.get("componentType", "design");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get finder() {
                    return this.state.get("$finder");
                }
                get finderGrid() {
                    var _a;
                    return (_a = this.finder) === null || _a === void 0 ? void 0 : _a.grid;
                }
                get selectedItem() {
                    return this.state.get("$selectedItem");
                }
                get selectedNode() {
                    return this.tree.select();
                }
                get itemIsCondition() {
                    var _a;
                    return ((_a = this.selectedItem) === null || _a === void 0 ? void 0 : _a.role) == "condition";
                }
                get itemIsFilter() {
                    var _a;
                    return ((_a = this.selectedItem) === null || _a === void 0 ? void 0 : _a.role) == "filter";
                }
                get treeHasSelection() {
                    return this.tree !== null &&
                        this.tree.select().length > 0;
                }
                get treeHasNodes() {
                    return this.tree !== null &&
                        this.tree.element.find("li.k-item").length > 0;
                }
                get tree() {
                    return this.state.get("$tree");
                }
                get commandContext() {
                    return PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands;
                }
                onExecute(e) {
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                fireFiltersChangedEvent() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("filters/changed");
                }
            }
            Views.FiltersDialogCommand = FiltersDialogCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersDialogCommands extends Jade.CommandGroup {
                constructor() {
                    super("view/filters");
                }
                registerCommands(e) {
                    e.commands.add(new Views.AddFilterCommand({}));
                    e.commands.add(new Views.ClearFiltersCommand({}));
                    e.commands.add(new Views.RemoveFilterCommand({}));
                    e.commands.add(new Views.EditFilterCommand({}));
                    e.commands.add(new Views.DuplicateFiltersCommand({}));
                    e.commands.add(new Views.ConvertConditionCommand({}));
                    e.commands.add(new Views.AddConditionCommand({}));
                }
            }
            Views.FiltersDialogCommands = FiltersDialogCommands;
            Jade.Application.onStart(() => {
                Jade.CommandGroups.add(FiltersDialogCommands);
            });
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class FiltersDialogToolBarSegment extends PDJS.Shared.UI.Controls.ToolbarSegment {
                onAddItems(e) {
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:filter/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:filter/edit"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:filter/duplicate"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:filter/remove"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:filters/clear"
                    }));
                    e.addSeparator();
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:condition/add"
                    }));
                    e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "view/filters:condition/convert"
                    }));
                }
            }
            Views.FiltersDialogToolBarSegment = FiltersDialogToolBarSegment;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AddConditionCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let node = null;
                    node = Views.FiltersEditorTreeActions.addCondtion(this.tree, {
                        type: "AND"
                    });
                    this.commandContext.setState({
                        "view/filters": {
                            selectedItem: node
                        }
                    }, { force: true });
                    this.fireFiltersChangedEvent();
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "condition/add",
                        tooltip: "Add Condition",
                        label: "Add Condition",
                        icon: "add.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
            }
            Views.AddConditionCommand = AddConditionCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class AddFilterCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let node = this.selectedNode;
                    if (node.length == 0) {
                        node = Views.FiltersEditorTreeActions
                            .addCondtion(this.tree, { type: "AND", checked: true });
                    }
                    let filterNode = null;
                    this.finderGrid.selected.forEach(column => {
                        filterNode =
                            Views.FiltersEditorTreeActions.addFilter(this.tree, {
                                id: column.id,
                                name: column.name,
                                checked: true
                            }, node);
                    });
                    if (filterNode.length == 0) {
                        return;
                    }
                    let filterItem = this.tree.dataItem(filterNode);
                    this.commandContext.setState({
                        "view/filters": {
                            selectedItem: filterItem
                        }
                    }, { force: true });
                    this.fireFiltersChangedEvent();
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.finderGrid != null && this.finderGrid.selected.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filter/add",
                        tooltip: "Add Filter",
                        label: "Add Filter",
                        icon: "arrow_down_green.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
            }
            Views.AddFilterCommand = AddFilterCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ClearFiltersCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    this.tree.dataSource.data([]);
                    this.commandContext.setState({
                        "view/filters": {
                            selectedItem: null
                        }
                    }, { force: true });
                    this.fireFiltersChangedEvent();
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.treeHasSelection;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filters/clear",
                        tooltip: "Clear Filters",
                        label: "Clear",
                        icon: "eraser2.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
            }
            Views.ClearFiltersCommand = ClearFiltersCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class ConvertConditionCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let node = this.tree.findByUid(this.selectedItem.uid);
                    let item = this.selectedItem.toJSON();
                    this.selectedItem.set("type", item.type == "OR" ? "AND" : "OR");
                    item = this.selectedItem.toJSON();
                    this.setProperties(item);
                    Views.FiltersEditorTemplates.applyContentTemplate(node, Views.FiltersEditorTemplates.conditionTemplate(item));
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.itemIsCondition;
                    this.visible = this.itemIsCondition;
                    if (!this.enabled) {
                        return;
                    }
                    let condition = this.selectedItem.toJSON();
                    this.setProperties(condition);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "condition/convert",
                        label: "Convert to AND",
                        icon: "logic_and.png",
                        tooltip: "Convert to AND",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
                setProperties(condition) {
                    switch (condition.type) {
                        case "AND":
                            this.label = "Convert to OR";
                            this.icon = "logic_or.png";
                            this.tooltip = this.label;
                            break;
                        case "OR":
                            this.label = "Convert to AND";
                            this.icon = "logic_and.png";
                            this.tooltip = this.label;
                            break;
                    }
                }
            }
            Views.ConvertConditionCommand = ConvertConditionCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class DuplicateFiltersCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let node = this.tree.select();
                    if (node.length === 0) {
                        return;
                    }
                    let data = this.tree.dataItem(node);
                    let item = data.toJSON();
                    data.set("selected", false);
                    item.uid = null;
                    item.selected = true;
                    this.tree.insertAfter(item, node);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.itemIsFilter;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filter/duplicate",
                        tooltip: "Duplicate",
                        label: "Duplicate",
                        icon: "copy.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
            }
            Views.DuplicateFiltersCommand = DuplicateFiltersCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class EditFilterCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let filter = this.selectedItem;
                    if (filter.value === null) {
                        delete filter.value;
                    }
                    ;
                    PDJS.Shared.Views.Filters.FilterEditorDialog.open({
                        viewStateId: this.viewStateId,
                        filter: {
                            id: filter.id,
                            enabled: filter.enabled,
                            operator: filter.operator,
                            value: filter.value,
                            verse: filter.verse
                        },
                        select: {
                            ok: (sender, e) => {
                                filter.id = e.id;
                                filter.enabled = e.enabled;
                                filter.operator = e.operator;
                                filter.value = e.value;
                                filter.verse = e.verse || e.value;
                                filter.checked = true;
                                Views.FiltersEditorTemplates.applyContentTemplate(this.selectedNode, Views.FiltersEditorTemplates.filterTemplate(filter));
                            }
                        }
                    });
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.itemIsFilter;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filter/edit",
                        tooltip: "Edit Filter",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
            }
            Views.EditFilterCommand = EditFilterCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            class RemoveFilterCommand extends Views.FiltersDialogCommand {
                onExecute() {
                    let node = this.tree.select();
                    if (node.length === 0) {
                        return;
                    }
                    let fallbackNode = this.getFallbackNode(node);
                    let fallbackItem = null;
                    if (fallbackNode != null) {
                        fallbackItem = this.tree.dataItem(fallbackNode);
                    }
                    this.tree.remove(node);
                    this.tree.select(fallbackNode);
                    this.commandContext.setState({
                        "view/filters": {
                            selectedItem: fallbackItem
                        }
                    }, { force: true });
                    this.fireFiltersChangedEvent();
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.treeHasSelection;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filter/remove",
                        tooltip: "Remove Filter",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon",
                        iconSetId: "pd"
                    };
                }
                getFallbackNode(currrentNode) {
                    let result = currrentNode.next();
                    if (result.length == 0) {
                        result = currrentNode.prev();
                    }
                    if (result.length == 0) {
                        result = this.tree.parent(currrentNode);
                    }
                    if (result.length == 0) {
                        result = null;
                    }
                    return result;
                }
            }
            Views.RemoveFilterCommand = RemoveFilterCommand;
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterModel extends PDJS.Core.Model {
                    constructor(filter) {
                        super(filter);
                    }
                    get autoValueId() {
                        return this.state.get("autoValueId");
                    }
                    set autoValueId(value) {
                        this.state.set("autoValueId", value);
                    }
                    get autoValueName() {
                        return this.state.get("autoValueName");
                    }
                    set autoValueName(value) {
                        this.state.set("autoValueName", value);
                    }
                    get autoValueList() {
                        return this.state.get("autoValueList");
                    }
                    set autoValueList(value) {
                        this.state.set("autoValueList", value);
                    }
                    get autoValueActive() {
                        return this.state.get("autoValueActive");
                    }
                    set autoValueActive(value) {
                        this.state.set("autoValueActive", value);
                    }
                    get autoValueEnabled() {
                        return this.state.get("autoValueEnabled");
                    }
                    set autoValueEnabled(value) {
                        this.state.set("autoValueEnabled", value);
                    }
                    get columnId() {
                        return this.state.get("columnId");
                    }
                    set columnId(value) {
                        this.state.set("columnId", value);
                    }
                    get columnName() {
                        return this.state.get("columnName");
                    }
                    set columnName(value) {
                        this.state.set("columnName", value);
                    }
                    get enabled() {
                        return this.state.get("enabled");
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get id() {
                        return this.state.get("id");
                    }
                    set id(value) {
                        this.state.set("id", value);
                    }
                    get inline() {
                        return this.state.get("inline");
                    }
                    set inline(value) {
                        this.state.set("inline", value);
                    }
                    get name() {
                        return this.state.get("name");
                    }
                    set name(value) {
                        this.state.set("name", value);
                    }
                    get operator() {
                        return this.state.get("operator");
                    }
                    set operator(value) {
                        this.state.set("operator", value);
                    }
                    get operatorName() {
                        return this.state.get("operatorName");
                    }
                    set operatorName(value) {
                        this.state.set("operatorName", value);
                    }
                    get operatorList() {
                        return this.state.get("operatorList");
                    }
                    set operatorList(value) {
                        this.state.set("operatorList", value);
                    }
                    get scalarFunctionId() {
                        return this.state.get("scalarFunctionId");
                    }
                    set scalarFunctionId(value) {
                        this.state.set("scalarFunctionId", value);
                    }
                    get scalarFunctionName() {
                        return this.state.get("scalarFunctionName");
                    }
                    set scalarFunctionName(value) {
                        this.state.set("scalarFunctionName", value);
                    }
                    get scalarFunctionList() {
                        return this.state.get("scalarFunctionList");
                    }
                    set scalarFunctionList(value) {
                        this.state.set("scalarFunctionList", value);
                    }
                    get scalarFunctionActive() {
                        return this.state.get("scalarFunctionActive");
                    }
                    set scalarFunctionActive(value) {
                        this.state.set("scalarFunctionActive", value);
                    }
                    get scalarFunctionEnabled() {
                        return this.state.get("scalarFunctionEnabled");
                    }
                    set scalarFunctionEnabled(value) {
                        this.state.set("scalarFunctionEnabled", value);
                    }
                    get value() {
                        return this.state.get("value");
                    }
                    set value(value) {
                        this.state.set("value", value);
                    }
                    get valueType() {
                        return this.state.get("valueType");
                    }
                    set valueType(value) {
                        this.state.set("valueType", value);
                    }
                    get valueList() {
                        return this.state.get("valueList");
                    }
                    set valueList(value) {
                        this.state.set("valueList", value);
                    }
                    get verse() {
                        return this.state.get("verse");
                    }
                    set verse(value) {
                        this.state.set("verse", value);
                    }
                    update(data) {
                        this.state.set(data);
                    }
                    changeValueType(newType) {
                        this.valueType = newType;
                    }
                    toJSON() {
                        return this.state.toJSON();
                    }
                }
                Filters.FilterModel = FilterModel;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterComponent extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get parent() {
                        this.ensureParent();
                        return this.m_parent;
                    }
                    get source() {
                        return this.parent.source;
                    }
                    get autoValueActive() {
                        return this.source.autoValueActive;
                    }
                    set autoValueActive(value) {
                        this.source.autoValueActive = value;
                    }
                    get autoValueEnabled() {
                        return this.source.autoValueEnabled;
                    }
                    get scalarFunctionEnabled() {
                        return this.source.scalarFunctionEnabled;
                    }
                    get visible() {
                        return this.node.css("display") != "none";
                    }
                    commit() {
                    }
                    getFieldError(message) {
                        return new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: message
                        });
                    }
                    handleError(error) {
                    }
                    hide() {
                        this.node.hide();
                    }
                    isValid() {
                        return true;
                    }
                    show() {
                        this.node.show();
                    }
                    validate() {
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-pdjs-view-filter-component");
                    }
                    ensureParent() {
                        if (this.m_parent == null) {
                            this.m_parent = this.state.get("parent");
                            this.state.unset("parent");
                        }
                    }
                }
                Filters.FilterComponent = FilterComponent;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterComponents extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get autos() {
                        return this.m_autos;
                    }
                    set autos(value) {
                        this.m_autos = value;
                    }
                    get components() {
                        return [
                            this.m_autos,
                            this.m_operator,
                            this.m_provider,
                            this.m_scalar,
                            this.m_value
                        ];
                    }
                    get operator() {
                        return this.m_operator;
                    }
                    set operator(value) {
                        this.m_operator = value;
                    }
                    get provider() {
                        return this.m_provider;
                    }
                    set provider(value) {
                        this.m_provider = value;
                    }
                    get scalar() {
                        return this.m_scalar;
                    }
                    set scalar(value) {
                        this.m_scalar = value;
                    }
                    get source() {
                        return this.state.get("source");
                    }
                    get autoValueEnabled() {
                        return this.source.autoValueEnabled;
                    }
                    get scalarFunctionEnabled() {
                        return this.source.scalarFunctionEnabled;
                    }
                    get value() {
                        return this.m_value;
                    }
                    set value(value) {
                        this.m_value = value;
                    }
                    get defaultHeight() {
                        return 170 +
                            (this.autoValueEnabled ? 50 : 0) +
                            (this.scalarFunctionEnabled ? 50 : 0);
                        ;
                    }
                    get defaultWidth() {
                        return 350;
                    }
                    commit() {
                        this.components.forEach(component => {
                            component.commit();
                        });
                    }
                    isValid() {
                        return this.components.filter(component => !component.isValid()).length === 0;
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-components"></div>`;
                    }
                    validate() {
                        this.components.forEach(component => {
                            component.validate();
                        });
                    }
                    handleError(error) {
                        this.components.forEach(component => {
                            component.handleError(error);
                        });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.operator_init();
                        this.provider_init();
                        this.scalar_init();
                        this.autos_init();
                        this.value_init();
                        this.node.css({
                            gridTemplateRows: `max-content ${this.autoValueEnabled ? "max-content" : ""} ${this.autoValueEnabled ? "max-content" : ""} ${this.scalarFunctionEnabled ? "max-content" : ""} auto`
                        });
                    }
                    autos_init() {
                        this.m_autos = new Filters.FilterAutos({
                            source: this.source,
                            parent: this
                        });
                        this.controls.add(this.m_autos);
                    }
                    operator_init() {
                        this.m_operator = new Filters.FilterOperator({
                            source: this.source,
                            parent: this,
                            change: () => {
                                this.value.enabled = !Filters.FilterOperators.isNullOperator(this.operator.value);
                            }
                        });
                        this.controls.add(this.m_operator);
                    }
                    provider_init() {
                        this.m_provider = new Filters.FilterProvider({
                            source: this.source,
                            parent: this
                        });
                        this.controls.add(this.m_provider);
                    }
                    scalar_init() {
                        this.m_scalar = new Filters.FilterScalar({
                            source: this.source,
                            parent: this
                        });
                        this.controls.add(this.m_scalar);
                    }
                    value_init() {
                        this.m_value = Filters.FilterValueFactory.createFilterValue({
                            parent: this
                        });
                        if (this.m_value == null) {
                            return;
                        }
                        this.controls.add(this.m_value);
                    }
                }
                Filters.FilterComponents = FilterComponents;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterEditorDialog extends Jade.UI.Dialogs.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    get components() {
                        return this.m_components;
                    }
                    set components(value) {
                        this.m_components = value;
                    }
                    get filter() {
                        this.ensureFilterModel();
                        return this.m_filter;
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    static open(options) {
                        return new FilterEditorDialog(options);
                    }
                    template() {
                        return super.template(`
                <div class="-pdjs-filter-editor-dialog" data-controls>
                    <div class="-pdjs-filter-editor-dialog-content" data-controls></div>
                    <div class="-pdjs-filter-editor-dialog-buttons">
                        <button data-command="ok" class="-jadeui-dialog-button">OK</button>
                        <button data-command="cancel" class="-jadeui-dialog-button">Cancel</button>
                    </div>
                </div>`);
                    }
                    getDefaultOptions() {
                        return { resizable: false };
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.init();
                        this.okButton.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_click, this));
                        this.cancelButton.on(Jade.BrowserEvent.CLICK, _.bind(this.cancelButton_click, this));
                    }
                    onInputReturnKeystroke() {
                        this.commit();
                    }
                    cancelButton_click() {
                        this.close();
                    }
                    components_init() {
                        this.components = new Filters.FilterComponents({
                            insertAt: `.-pdjs-filter-editor-dialog-content`,
                            source: this.filter
                        });
                        this.controls.add(this.components);
                        this.setWindowOptions({
                            height: 58 + this.components.node.outerHeight(true),
                            width: 350
                        });
                        this.center();
                        this.setDefaultInputFocus();
                    }
                    commit() {
                        let value = this.components.source.value;
                        this.components.commit();
                        this.components.validate();
                        if (!this.components.isValid()) {
                            return;
                        }
                        if (!this.components.source.inline) {
                            this.commitValidate();
                            return;
                        }
                        let clear = Jade.String.isNullOrWhiteSpace(value)
                            && !Filters.FilterOperators.isNullOperator(this.components.source.operator);
                        clear ? this.commitInlineRemove() : this.commitInlineSave();
                    }
                    commitValidate() {
                        let service = new PDJS.Services.Views.ViewFilterService();
                        service.validate({
                            viewStateId: this.viewStateId,
                            filter: this.filter.toJSON(),
                            success: (e) => {
                                this.close({
                                    name: "ok",
                                    data: this.components.source
                                });
                            },
                            error: (e) => {
                                let errors = PDJS.Shared.ErrorFactory.convert(e.xhr);
                                errors.forEach(err => {
                                    this.components.handleError(err);
                                });
                                if (errors.length > 0) {
                                    e.errorHandled = true;
                                }
                            }
                        });
                    }
                    commitInlineSave() {
                        let service = new PDJS.Services.Views.ViewFilterService();
                        service.save({
                            viewStateId: this.viewStateId,
                            filter: this.filter.toJSON(),
                            success: (e) => {
                                this.close({
                                    name: "ok",
                                    data: this.components.source
                                });
                            },
                            error: (e) => {
                                let errors = PDJS.Shared.ErrorFactory.convert(e.xhr);
                                errors.forEach(err => {
                                    this.components.handleError(err);
                                });
                                if (errors.length > 0) {
                                    e.errorHandled = true;
                                }
                            }
                        });
                    }
                    commitInlineRemove() {
                        let service = new PDJS.Services.Views.ViewFilterService();
                        service.removeInline({
                            viewStateId: this.viewStateId,
                            columnId: this.filter.id,
                            success: (e) => {
                                this.close({ name: "ok" });
                            }
                        });
                    }
                    ensureFilterModel() {
                        if (this.m_filter != null) {
                            return;
                        }
                        let filter = this.state.get("filter");
                        this.m_filter = new Filters.FilterModel(filter);
                        this.state.unset("filter");
                    }
                    init() {
                        let service = new PDJS.Services.Views.ViewFilterService();
                        service.load({
                            viewStateId: this.viewStateId,
                            filter: this.filter,
                            success: (e) => {
                                this.filter.update(e.data);
                                this.components_init();
                                this.setWindowOptions({
                                    title: `Filter | ${this.filter.name}`
                                });
                            }
                        });
                    }
                    okButton_click() {
                        this.commit();
                    }
                }
                Filters.FilterEditorDialog = FilterEditorDialog;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                let Operators;
                (function (Operators) {
                    Operators[Operators["NoFilterSet"] = 0] = "NoFilterSet";
                    Operators[Operators["Equals"] = 1] = "Equals";
                    Operators[Operators["DoesNotEqual"] = 2] = "DoesNotEqual";
                    Operators[Operators["GreaterThanOrEqualTo"] = 4] = "GreaterThanOrEqualTo";
                    Operators[Operators["GreaterThan"] = 8] = "GreaterThan";
                    Operators[Operators["LessThanOrEqualTo"] = 16] = "LessThanOrEqualTo";
                    Operators[Operators["LessThan"] = 32] = "LessThan";
                    Operators[Operators["IsNull"] = 64] = "IsNull";
                    Operators[Operators["IsNotNull"] = 128] = "IsNotNull";
                    Operators[Operators["StartsWith"] = 256] = "StartsWith";
                    Operators[Operators["EndsWith"] = 512] = "EndsWith";
                    Operators[Operators["Contains"] = 1024] = "Contains";
                    Operators[Operators["Has"] = 2048] = "Has";
                    Operators[Operators["DoesNotStartWith"] = 4096] = "DoesNotStartWith";
                    Operators[Operators["DoesNotEndWith"] = 8192] = "DoesNotEndWith";
                    Operators[Operators["DoesNotContain"] = 16384] = "DoesNotContain";
                    Operators[Operators["DoesNotHave"] = 32768] = "DoesNotHave";
                    Operators[Operators["InList"] = 65536] = "InList";
                    Operators[Operators["NotInList"] = 131072] = "NotInList";
                })(Operators = Filters.Operators || (Filters.Operators = {}));
                class FilterOperators {
                    static isNullOperator(flag) {
                        let value = parseInt(flag.toString());
                        return value === Operators.NoFilterSet
                            || value === Operators.IsNull
                            || value === Operators.IsNotNull;
                    }
                    static isValueOperator(flag) {
                        let value = parseInt(flag.toString());
                        return value !== Operators.NoFilterSet
                            && value !== Operators.IsNull
                            && value !== Operators.IsNotNull;
                    }
                    static isVerseOperator(flag) {
                        return flag === Operators.InList
                            || flag === Operators.NotInList;
                    }
                    static isSetOperator(flag) {
                        return flag !== Operators.NoFilterSet;
                    }
                }
                Filters.FilterOperators = FilterOperators;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValueFactory {
                    static createFilterValue(options) {
                        let result = null;
                        let type = options.parent.source.valueType;
                        switch (type) {
                            case "date":
                                result = new Filters.FilterValueDate(options);
                                break;
                            case "decimal":
                                result = new Filters.FilterValueNumeric(options);
                                break;
                            case "int32":
                                result = new Filters.FilterValueNumeric(options);
                                break;
                            case "int64":
                                result = new Filters.FilterValueNumeric(options);
                                break;
                            case "string":
                                result = new Filters.FilterValueNumeric(options);
                                break;
                            case "list":
                                result = new Filters.FilterValueList(options);
                                break;
                        }
                        return result;
                    }
                }
                Filters.FilterValueFactory = FilterValueFactory;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterAutos extends Filters.FilterComponent {
                    get field() {
                        return this.m_field;
                    }
                    get list() {
                        return this.source.autoValueList || [];
                    }
                    get value() {
                        return this.field.value;
                    }
                    set value(value) {
                        this.field.value = value;
                    }
                    get valueId() {
                        return this.source.autoValueId;
                    }
                    set valueId(value) {
                        this.source.autoValueId = value;
                    }
                    get valueName() {
                        return this.source.autoValueName;
                    }
                    set valueName(value) {
                        this.source.autoValueName;
                    }
                    clear() {
                        this.valueId = null;
                        this.valueName = null;
                    }
                    handleError(error) {
                        if (error.propertyName === "AutoValueId") {
                            this.field.errors.add(this.getFieldError(error.message));
                        }
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-autos"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                        this.autoValueActive ?
                            this.show() :
                            this.hide();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.value = this.valueId;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.SelectField({
                            insertAt: "div[role=autos]",
                            label: "System Value",
                            items: this.list,
                            binding: { label: "name", value: "id" },
                            change: () => {
                                this.valueId = this.value;
                                this.valueName = this.getAutoName(this.value);
                                this.changeCallback();
                            }
                        });
                        this.controls.add(this.field);
                    }
                    getAutoName(id) {
                        let result = null;
                        this.list.forEach(item => {
                            (item.value == id) ?
                                result = item.label : null;
                        });
                        return result || "";
                    }
                }
                Filters.FilterAutos = FilterAutos;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterOperator extends Filters.FilterComponent {
                    get field() {
                        return this.m_field;
                    }
                    get operator() {
                        return this.source.operator;
                    }
                    set operator(value) {
                        this.source.operator = value;
                    }
                    get list() {
                        return this.source.operatorList;
                    }
                    get value() {
                        return this.source.operator;
                    }
                    commit() {
                        this.operator = this.field.value;
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-operator"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.operator_init();
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.SelectField({
                            label: this.autoValueEnabled ? "Where Current Value" : this.source.name,
                            items: this.list,
                            binding: { label: "label", value: "value" },
                            change: () => {
                                this.operator = this.field.value;
                                this.changeCallback();
                            }
                        });
                        this.controls.add(this.field);
                    }
                    operator_init() {
                        let isNotSet = this.operator == null || this.operator == 0;
                        this.operator = isNotSet ? _.first(this.list).value : this.operator;
                        this.field.value = this.operator;
                        this.changeCallback();
                    }
                }
                Filters.FilterOperator = FilterOperator;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterProvider extends Filters.FilterComponent {
                    get field() {
                        return this.m_field;
                    }
                    get value() {
                        return this.field.value == "true";
                    }
                    set value(value) {
                        this.field.value = value;
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-provider"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                        this.autoValueEnabled ?
                            this.show() :
                            this.hide();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.value = this.autoValueActive;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.SelectField({
                            label: "Where Current Value",
                            items: [
                                { label: "Is Supplied By Me", value: "false" },
                                { label: "Is Supplied By System", value: "true" }
                            ],
                            change: () => {
                                this.autoValueActive = this.value;
                            }
                        });
                        this.controls.add(this.field);
                    }
                }
                Filters.FilterProvider = FilterProvider;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterScalar extends Filters.FilterComponent {
                    get functionId() {
                        return this.source.scalarFunctionId;
                    }
                    set functionId(value) {
                        this.source.scalarFunctionId = value;
                    }
                    get functionName() {
                        return this.source.scalarFunctionName;
                    }
                    get field() {
                        return this.m_field;
                    }
                    get value() {
                        return this.field.value;
                    }
                    set value(value) {
                        this.field.value = value;
                    }
                    get list() {
                        return this.source.scalarFunctionList || [];
                    }
                    clear() {
                        this.functionId = null;
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-scalar"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                        this.scalarFunctionEnabled ?
                            this.show() :
                            this.hide();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.value = this.functionId;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.SelectField({
                            label: "Filter Using",
                            items: this.list,
                            binding: { label: "name", value: "id" },
                            change: () => {
                                this.functionId = this.value;
                            }
                        });
                        this.controls.add(this.field);
                    }
                    getScalarName(id) {
                        let result = null;
                        this.list.forEach(item => {
                            (item.value == id) ?
                                result = item.label : null;
                        });
                        return result || "";
                    }
                }
                Filters.FilterScalar = FilterScalar;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValue extends Filters.FilterComponent {
                    get enabled() {
                        return this.state.get("enabled", true);
                    }
                    set enabled(value) {
                        this.state.set("enabled", value);
                    }
                    get valueType() {
                        return this.source.valueType;
                    }
                    get value() {
                        return this.source.value;
                    }
                    set value(value) {
                        this.source.value = value;
                    }
                    get verse() {
                        return this.source.verse;
                    }
                    set verse(value) {
                        this.source.verse = value;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.autoValueActive ?
                            this.hide() :
                            this.show();
                        this.node.addClass("-pdjs-view-filter-value");
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.state.hasChanged("enabled")) {
                            this.onEnabledStateChanged();
                        }
                    }
                    onEnabledStateChanged() {
                    }
                }
                Filters.FilterValue = FilterValue;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValueDate extends Filters.FilterValue {
                    get dateField() {
                        return this.m_dateField;
                    }
                    get dateFieldNode() {
                        return this.node.find("div[role=date]");
                    }
                    get daysField() {
                        return this.m_daysField;
                    }
                    get daysFieldNode() {
                        return this.node.find("div[role=days]");
                    }
                    get mode() {
                        return this.selectNode.val();
                    }
                    get selectNode() {
                        return this.node.find("select");
                    }
                    commit() {
                        this.mode == "date" ?
                            this.value = this.dateField.value :
                            this.value = this.daysField.value;
                        this.mode == "date" ?
                            this.verse = this.dateField.value :
                            this.verse = this.daysField.value;
                    }
                    handleError(e) {
                        super.handleError(e);
                        let targetField = this.mode === "date" ? this.dateField : this.daysField;
                        targetField.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: e.message
                        }));
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-value-date">
                        <div>
                            <select>
                                <option value="date">Selected Date</option>
                                <option value="days">Days from Today</option>
                            </select>
                        </div>
                        <div role="date" role="input"></div>
                        <div role="days" role="input"></div>
                    </div>`;
                    }
                    validate() {
                        this.mode == "date" ?
                            this.dateField.validate() :
                            this.daysField.validate();
                    }
                    isValid() {
                        return this.mode == "date" ?
                            this.dateField.isValid :
                            this.daysField.isValid;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.dateField_init();
                        this.daysField_init();
                        this.setModeDisplay();
                        this.selectNode.on(Jade.BrowserEvent.CHANGE, _.bind(this.select_change, this));
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.setModeDefault();
                    }
                    onEnabledStateChanged() {
                        this.dateField.enabled = this.enabled;
                        this.daysField.enabled = this.enabled;
                        this.selectNode.prop("disabled", !this.enabled);
                    }
                    dateField_init() {
                        this.m_dateField = new PDJS.Shared.UI.Controls.Fields.StringField({
                            insertAt: "div[role=date]",
                            label: "Value",
                            labelVisible: false,
                            change: () => {
                                this.value = this.dateField.value;
                            }
                        });
                        this.controls.add(this.dateField);
                    }
                    daysField_init() {
                        this.m_daysField = new PDJS.Shared.UI.Controls.Fields.NumericField({
                            insertAt: "div[role=days]",
                            label: "Value",
                            labelVisible: false,
                            numericType: "int32",
                            change: () => {
                                this.value = this.daysField.value;
                            }
                        });
                        this.controls.add(this.daysField);
                    }
                    select_change() {
                        this.setModeValue();
                        this.setModeDisplay();
                    }
                    setModeDisplay() {
                        if (this.mode == "date") {
                            this.dateFieldNode.show();
                            this.daysFieldNode.hide();
                            this.source.changeValueType("date");
                        }
                        if (this.mode == "days") {
                            this.dateFieldNode.hide();
                            this.daysFieldNode.show();
                            this.source.changeValueType("int32");
                        }
                    }
                    setModeValue() {
                        if (this.mode == "date") {
                            this.value = this.dateField.value;
                            this.verse = this.dateField.value;
                        }
                        if (this.mode == "days") {
                            this.value = this.daysField.value;
                            this.verse = this.daysField.value;
                        }
                    }
                    setModeDefault() {
                        let numberValue = new Number(this.value);
                        let isNull = Jade.String.isNullOrWhiteSpace(this.value);
                        !isNaN(numberValue) && !isNull ?
                            this.selectNode.val("days") :
                            this.selectNode.val("date");
                        this.setModeDisplay();
                        if (this.mode == "days") {
                            this.daysField.value = parseInt(this.value);
                        }
                        else {
                            this.dateField.value = this.value;
                        }
                    }
                }
                Filters.FilterValueDate = FilterValueDate;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValueList extends Filters.FilterValue {
                    get field() {
                        return this.m_field;
                    }
                    get list() {
                        return this.source.valueList || [];
                    }
                    get selections() {
                        return this.getConvertedValue();
                    }
                    handleError(e) {
                        super.handleError(e);
                        if (e.propertyName !== "value") {
                            return;
                        }
                        this.field.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: e.message
                        }));
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-value-list"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                    }
                    onEnabledStateChanged() {
                        this.field.enabled = this.enabled;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.MultiSelectField({
                            label: "Value",
                            labelVisible: false,
                            items: this.getFieldData(),
                            height: "200px",
                            binding: { label: "label", value: "value" },
                            check: () => {
                                this.setValue();
                                this.setVerse();
                            }
                        });
                        this.controls.add(this.field);
                    }
                    getFieldData() {
                        let data = [];
                        this.list.forEach(item => {
                            data.push(_.extend(item, {
                                checked: this.selections.indexOf(item.value) > -1
                            }));
                        });
                        return data;
                    }
                    getConvertedValue() {
                        let result = [];
                        if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                            try {
                                result = this.value.split(",");
                            }
                            catch (_a) {
                                result = [];
                            }
                        }
                        return result;
                    }
                    setValue() {
                        let values = this.field.selected.map((item) => {
                            return item.value;
                        });
                        this.value = values.join(",");
                    }
                    setVerse() {
                        let verses = this.field.selected.map((item) => {
                            return item.label;
                        });
                        this.verse = verses.join(", ");
                    }
                }
                Filters.FilterValueList = FilterValueList;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValueNumeric extends Filters.FilterValue {
                    constructor(options) {
                        super(options);
                    }
                    get field() {
                        return this.m_field;
                    }
                    get value() {
                        return this.source.value || [];
                    }
                    set value(value) {
                        this.source.value = value;
                    }
                    handleError(e) {
                        super.handleError(e);
                        this.field.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: e.message
                        }));
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-value-int32"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.field.value = this.value;
                    }
                    onEnabledStateChanged() {
                        this.field.enabled = this.enabled;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Value",
                            labelVisible: false,
                            input: (e) => {
                                this.value = e.value;
                                this.verse = e.value;
                            }
                        });
                        this.controls.add(this.field);
                    }
                }
                Filters.FilterValueNumeric = FilterValueNumeric;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Views;
        (function (Views) {
            var Filters;
            (function (Filters) {
                class FilterValueString extends Filters.FilterValue {
                    get field() {
                        return this.m_field;
                    }
                    commit() {
                        this.value = this.field.value;
                    }
                    handleError(e) {
                        super.handleError(e);
                        if (e.propertyName !== "value") {
                            return;
                        }
                        this.field.errors.add(new PDJS.Shared.UI.Controls.Fields.FieldValidationError({
                            message: e.message
                        }));
                    }
                    template() {
                        return `<div class="-pdjs-view-filter-value-string"></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.field_init();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.field.value = this.value || "";
                    }
                    onEnabledStateChanged() {
                        this.field.enabled = this.enabled;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.field.enabled = this.enabled;
                    }
                    field_init() {
                        this.m_field = new PDJS.Shared.UI.Controls.Fields.StringField({
                            label: "Value",
                            labelVisible: false,
                            input: () => {
                                this.value = this.field.value;
                            }
                        });
                        this.controls.add(this.field);
                    }
                }
                Filters.FilterValueString = FilterValueString;
            })(Filters = Views.Filters || (Views.Filters = {}));
        })(Views = Shared.Views || (Shared.Views = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var System;
    (function (System) {
        class Settings {
            constructor(options) {
                this.m_state = new Jade.StateBag(options);
            }
            static get current() {
                return this.m_current;
            }
            get state() {
                return this.m_state;
            }
            get applicationId() {
                return this.state.get("applicationId");
            }
            get applicationName() {
                return this.state.get("applicationName", "VISIV");
            }
            get applicationUrl() {
                return this.state.get("applicationUrl");
            }
            get applicationVersion() {
                return this.state.get("applicationVersion");
            }
            get authenticationMode() {
                return this.state.get("authenticationMode", 0);
            }
            get entityTemplateId() {
                return this.state.get("entityTemplateId", 0);
            }
            get isLocalAuthMode() {
                return this.state.get("isLocalAuth", false);
            }
            get supportUrl() {
                return this.state.get("supportUrl");
            }
            get virtualDirectory() {
                return this.state.get("virtualDirectory", 0);
            }
            get shortcutViews() {
                return this.state.get("shortcutViews", []);
            }
            get shortcutEntityTypes() {
                return this.state.get("shortcutEntityTypes", []);
            }
            get manageWindowId() {
                return `${PDJS.Application.instance.id}-manage`;
            }
            static load(options) {
                if (this.m_current == null) {
                    this.m_current = new Settings(options);
                }
            }
        }
        System.Settings = Settings;
    })(System = PDJS.System || (PDJS.System = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var System;
    (function (System) {
        class Environment {
            constructor(options) {
                PDJS.System.Settings.load(options.settings);
                PDJS.Profiles.Profile.load(options.profile);
                this.m_version = options.version;
            }
            static get current() {
                return this.m_current;
            }
            get version() {
                return this.m_version;
            }
            set version(value) {
                this.m_version = value;
            }
            get settings() {
                return PDJS.System.Settings.current;
            }
            get profile() {
                return PDJS.Profiles.Profile.current;
            }
            static load(options) {
                if (this.m_current == null) {
                    this.m_current = new Environment(options);
                }
                PDJS.Application.onStart(() => {
                    this.versionChangeCheck();
                });
            }
            static setScrollBarSize() {
                let scrollbarsCss = $("style[id=scrollbars-css]");
                let scrollBarSize = this.current
                    .profile.preferences.scrollBarSize;
                scrollbarsCss.empty();
                scrollbarsCss.html(`
                *::-webkit-scrollbar {
                    height: ${scrollBarSize}px !important;
                    width: ${scrollBarSize}px !important;
                }
            `);
            }
            static getProductLogoPath() {
                let color = getComputedStyle(document.body)
                    .getPropertyValue('--visiv-theme-base-1-back-color');
                let icon = tinycolor(color).isDark() ?
                    "visiv_dark.png" : "visiv_light.png";
                return Jade.IconSet.get("pdjs").resolve(icon, Jade.IconSetSizeSpecificDirectory.misc);
            }
            static versionChangeCheck() {
                let version = localStorage.getItem("platform.version");
                let versionChanged = version == null ||
                    version !== PDJS.System.Environment.current.version.full;
                if (versionChanged) {
                    PDJS.ApplicationEventsHub.versionChangedPublish();
                    localStorage.setItem("platform.version", PDJS.System.Environment.current.version.full);
                    return;
                }
            }
        }
        System.Environment = Environment;
    })(System = PDJS.System || (PDJS.System = {}));
})(PDJS || (PDJS = {}));
