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;
            }
            if (this.isHeaderError()) {
                return;
            }
            if (this._options != null && this.options.config != null) {
                this._context = this.options.config.contextData;
            }
            this.parseData();
            this.notify();
        }
        get options() {
            return this._options;
        }
        get context() {
            return this._context;
        }
        parseData() {
            var options = this.options;
            try {
                this._data = options.jqXHR.responseJSON;
            }
            catch (ex) {
                this._data = [];
            }
        }
        notify() {
            var isErrorDataAnArray = _.isArray(this._data);
            var fieldErrors = _.filter(this._data, (item) => {
                return item.key != null;
            });
            var fieldlessErrors = _.filter(this._data, (item) => {
                return item.key == null;
            });
            var hasFieldErrors = isErrorDataAnArray && fieldErrors.length > 0;
            var hasFieldlessErrors = isErrorDataAnArray && fieldlessErrors.length > 0;
            var isErrorObject = _.has(this._data, "message");
            var isRequestAborted = this.options.jqXHR.statusText === "abort";
            if (this.hasControl()) {
                this.context.control.enable();
            }
            if (hasFieldErrors && this.hasContext()) {
            }
            if (hasFieldlessErrors) {
                this.showErrorsDialog(fieldlessErrors);
                return;
            }
            if (isErrorObject) {
                this.showErrorsDialog(this._data);
                return;
            }
            if (!hasFieldErrors && !hasFieldlessErrors && !isErrorObject && !isRequestAborted) {
                this.showCatchAllErrorDialog();
            }
        }
        hasFieldErrors() {
            return this._data != null
                && _.isArray(this._data)
                && _.find(this._data, (item) => {
                    return item.key != null;
                });
        }
        hasContext() {
            return this.context != null;
        }
        hasContainer() {
            return this.hasContext()
                && this.context().container != null;
        }
        hasControl() {
            return this.hasContext()
                && this.context.control != null
                && this.context.control.length > 0;
        }
        isRedirect() {
            var redirect = this.options
                .jqXHR
                .getResponseHeader('Http-Redirect');
            if (redirect != null) {
                window.location.href = redirect;
            }
            return redirect != null;
        }
        isHeaderError() {
            var errorMessage = this.options
                .jqXHR
                .getResponseHeader('error-message');
            if (errorMessage != null) {
                Jade.UI.MessageDialog.open({
                    dialogStyle: Jade.UI.MessageDialogStyle.Error,
                    dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                    title: "Application Error",
                    message: errorMessage,
                    select: (e) => {
                        e.close();
                    }
                });
            }
            return errorMessage != null;
        }
        showErrorsDialog(errors) {
            if (!_.isArray(errors)) {
                errors = [{ message: errors.message }];
            }
            Jade.UI.ErrorDialog.open({
                dialogStyle: Jade.UI.MessageDialogStyle.Error,
                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                title: "Application Error",
                errors: errors,
                select: (e) => {
                    e.close();
                }
            });
        }
        showCatchAllErrorDialog() {
            Jade.UI.MessageDialog.open({
                dialogStyle: Jade.UI.MessageDialogStyle.Error,
                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                title: "Application Error",
                message: `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.`
            });
        }
    }
    PDJS.AjaxErrorHandler = AjaxErrorHandler;
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class Application extends Jade.Application {
        constructor(options) {
            super(options);
        }
        static get instance() {
            return Application.internalInstance;
        }
        get databaseId() {
            return Jade.String.format("PDDB_{0}_{1}", this.id, PDJS.Shared.Environment.current.user.id.toString());
        }
        get isLocalAuth() {
            return true;
        }
        onInit(options) {
            this.id = options.applicationId;
            Jade.Data.Database.create(this.databaseId);
            super.onInit(options);
        }
    }
    PDJS.Application = Application;
})(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;
            }
        });
        if (PDJS.Shared.Environment.current.isLocalAuthMode) {
            Jade.Application
                .instance
                .contexts
                .global
                .events
                .subscribe(PDJS.Shared.SessionState.SESSION_EXPIRED_EVENT, () => {
                PDJS.Shared.Security.LoginDialog.open();
            });
            Jade.Application
                .instance
                .contexts
                .global
                .events
                .subscribe(PDJS.Shared.SessionState.SESSION_RESUME_EVENT, (reload) => {
                if (PDJS.Shared.Security.LoginDialog.opened) {
                    PDJS.Shared.Security.LoginDialog.instance.close();
                }
                if (reload === true) {
                    window.location.reload();
                }
            });
            PDJS.Shared.SessionState.instance.init();
        }
    });
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    class StartUp {
        static get moduleName() {
            return this.m_moduleName;
        }
        static set moduleName(value) {
            this.m_moduleName = value;
        }
        static get virtualDirectory() {
            return this.m_virtualDirectory;
        }
        static set virtualDirectory(value) {
            this.m_virtualDirectory = value;
        }
        static start(success, failure) {
            PDJS.Ajax.call({
                url: `/${this.virtualDirectory}/Shared/Start/${this.moduleName}`,
                success: (e) => {
                    this.startEnvironment(e);
                    this.startProspectDirector(e);
                    this.startPD(e);
                    this.startPDJS(e);
                    success(e);
                },
                error: (e) => {
                    failure();
                },
            });
        }
        static startEnvironment(e) {
            PDJS.Shared.Environment.current.load(e);
        }
        static startProspectDirector(e) {
            PDJS.JS.ProspectDirector.RUNTIME.CURRENT_FOLDER_ID = null;
            PDJS.JS.ProspectDirector.RUNTIME.start({
                USER_ID: e.user.id,
                USER_NAME: e.user.accountName,
                VIRTUAL_DIRECTORY: e.environment.virtualDirectory
            });
        }
        static startPD(e) {
            PDJS.JS.PD.boot({
                APPLICATION_ID: e.environment.applicationId,
                USER_ID: e.user.id,
                USER_NAME: e.user.accountName,
                VIRTUAL_DIRECTORY: e.environment.virtualDirectory,
                AUTH_MODE: e.environment.authenticationMode
            });
        }
        static startPDJS(e) {
            new PDJS.Application({
                name: this.moduleName,
                virtualDirectory: `/${e.environment.virtualDirectory}`,
                applicationId: e.environment.applicationId,
                label: this.moduleName
            });
        }
        static startHub(virtualDirectory, success, failure) {
            success = success || (() => { });
            failure = failure || (() => { });
            this.virtualDirectory = virtualDirectory;
            this.moduleName = "hub";
            this.start(() => {
                this.renderContent();
                success();
            }, failure);
        }
        static startManage(virtualDirectory, success, failure) {
            success = success || (() => { });
            failure = failure || (() => { });
            this.virtualDirectory = virtualDirectory;
            this.moduleName = "manage";
            this.start(() => {
                this.renderContent();
                new PDJS.Manage.ApplicationBar({
                    container: ".-pd-framework-menu"
                });
                success();
            }, failure);
        }
        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 Canvas;
    (function (Canvas) {
        Jade.ContextManager.onContextChange((e) => {
            CanvasJS.Actual.Environment.reset();
            CanvasJS.Design.Environment.reset();
        });
    })(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;
                    }
                    CanvasJS.Actual.Environment.document.controls.clear();
                    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) {
                    this.m_document = new Actual.DocumentView({
                        $source: new Canvas.Core.Documents.ActualDocument(state),
                        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");
                }
                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");
                }
            }
            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);
                    if (this.source.errors.length > 0) {
                        this.controls.clear();
                        this.node.empty();
                        this.controls.add(new Actual.ElementViewError({
                            componentName: this.source.componentName,
                            errors: this.source.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);
                    Tipped.create(this.node, this.getErrorMessage(), {
                        skin: "white"
                    });
                    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: () => {
                                    this.m_informationBar.update();
                                }
                            });
                        }
                        else {
                            setTimeout(() => {
                                this.refresh();
                            }, 100);
                        }
                    }
                    onBrowserResize() {
                        if (this.anchorRight != null || this.anchorBottom != null) {
                            this.refresh();
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.chartNode.css({
                            position: "absolute",
                            top: 0,
                            right: 0,
                            bottom: 0,
                            left: 0,
                            boxSizing: "border-box",
                            padding: 0,
                            margin: 0
                        });
                        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;
                        }
                        let boardContent = () => {
                            return `<div style="padding:10px;text-align:center;border-top: 1px solid #DDDDDD"><b>Last Updated:</b><br/>${kendo.toString(new Date(this.source.cacheLastUpdated), "g")}</div>`;
                        };
                        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: Jade.IconSet.get("pdjs").resolve("refresh.png", Jade.IconSetSizeSpecificDirectory.x16),
                                label: "Refresh",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    this.showLoadingMessage();
                                    this.source.getCachedData({ force: true });
                                }
                            }));
                        }
                        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: () => {
                                        this.m_informationBar.update();
                                    }
                                });
                            }
                        });
                        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 buttonNode() {
                        return this.node.find("button");
                    }
                    get acceptsFocus() {
                        return this.source.enabled;
                    }
                    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>`;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.text(this.source.label);
                        this.buttonNode.prop("disabled", !this.source.enabled);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            Tipped.create(this.node, this.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                    }
                    onClick(e) {
                        if (this.source.enabled && this.source.hasOnClickAction) {
                            PDJS.Shared.Actions.Action.invoke(this.source.onClickAction);
                        }
                    }
                };
                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) {
                            Tipped.create(this.linkNode, this.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                    }
                    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 ImageButton 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);
                        this.imageNode.prop("src", this.getImageUrl());
                        this.imageNode.prop("disabled", this.source.enabled);
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .5
                        });
                        this.imageNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            Tipped.create(this.imageNode, this.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                    }
                    onClick(e) {
                        if (this.source.enabled && this.source.hasOnClickAction) {
                            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(`~${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.ImageButton = ImageButton;
            })(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,
                            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();
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        if (this.source.data == null) {
                            this.showLoadingMessage();
                            this.source.getCachedData({
                                success: () => {
                                    this.m_informationBar.update();
                                }
                            });
                        }
                        else {
                            this.loadReport();
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.reportNode.css({
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: this.source.informationBarVisible ? "25px" : "0",
                            backgroundColor: "#FFFFFF",
                            borderColor: this.source.borderColor,
                            borderStyle: this.source.borderStyle,
                            borderWidth: this.source.borderWidth
                        });
                        this.loadReport();
                    }
                    loadReport() {
                        if (this.iframeElement != null && this.iframeElement.contentDocument != null) {
                            this.iframeElement.contentDocument.clear();
                            this.iframeElement.contentDocument.open();
                            this.iframeElement.contentDocument.write(this.source.data + "<script> function printContent() { window.print(); }</script>");
                            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: "#FFFFFF",
                                    height: "26px",
                                    width: "26px",
                                    right: 0,
                                    top: 0,
                                    border: "1px solid #CCCCCC"
                                });
                            }
                        });
                        if (this.source.actionMenuRefresh) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                icon: Jade.IconSet.get("pdjs").resolve("refresh.png", Jade.IconSetSizeSpecificDirectory.x16),
                                label: "Refresh",
                                click: () => {
                                    this.m_menu.popUp.hide();
                                    this.showLoadingMessage();
                                    this.source.getCachedData({ force: true });
                                }
                            }));
                        }
                        if (this.source.actionMenuPrint) {
                            this.m_menu.items.add(new Canvas.Shared.ElementMenuItemAction({
                                icon: Jade.IconSet.get("pdjs").resolve("print.png", Jade.IconSetSizeSpecificDirectory.x16),
                                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",
                                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);
                                }
                            }));
                        }
                        this.m_menu.items.add(new Canvas.Shared.ElementMenuItemBoard({
                            content: `<div style="padding:10px;text-align:center;border-top: 1px solid #DDDDDD"><b>Last Updated:</b><br/>${kendo.toString(new Date(this.source.cacheLastUpdated), "g")}</div>`
                        }));
                        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: () => {
                                        this.m_informationBar.update();
                                    }
                                });
                            }
                        });
                        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,
                            borderColor: noBorder ? "#DDDDDD" : this.source.borderColor == null ? "transparent" : `${this.source.borderColor}`,
                            borderStyle: noBorder ? "none" : 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`,
                            backgroundColor: this.source.backgroundColor == null ? "transparent" : `${this.source.backgroundColor}`
                        });
                        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);
                                if (e.hasScriptAlerts) {
                                    Jade.UI.MultiMessageDialog.open({
                                        dialogStyle: Jade.UI.MessageDialogStyle.Success,
                                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                        title: "Request Success",
                                        header: "The request completed successfully with the following alerts generated by the application:",
                                        messages: e.scriptAlerts,
                                        select: (e) => {
                                            e.close();
                                        }
                                    });
                                }
                            },
                            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);
                                Jade.UI.MultiMessageDialog.open({
                                    dialogStyle: Jade.UI.MessageDialogStyle.Error,
                                    dialogButtons: Jade.UI.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.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 buttonNode() {
                        return this.node.find("button");
                    }
                    get acceptsFocus() {
                        return this.source.activeEnabledState;
                    }
                    template() {
                        return `<button style="height:100%;width:100%;box-sizing:border-box;" tabIndex="${this.source.activeTabIndex}">${this.source.label}</button>`;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.onClick, this));
                        if (this.source.hasTooltip) {
                            Tipped.create(this.node, this.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.buttonNode.prop("disabled", !this.source.activeEnabledState);
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        Tipped.remove(this.node);
                    }
                    onClick(e) {
                        Tipped.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>`;
                            Tipped.create(this.labelNode, errors, {
                                skin: "validation-error"
                            });
                            this.node.addClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("sign_warning.png", Jade.IconSetSizeSpecificDirectory.x16)})`
                            });
                        }
                        else {
                            Tipped.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.showText();
                        this.comboBox.focusText();
                    }
                    onInit(e) {
                        super.onInit(e);
                        this.comboBox_init();
                        this.navigate_init();
                    }
                    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
                            };
                        }
                    }
                    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;
                    }
                    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,
                            onValidate: _.bind((isValid) => {
                                this.onSubmit();
                            }, this)
                        });
                        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,
                            onValidate: _.bind((isValid) => {
                                this.onSubmit();
                            }, this)
                        });
                        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,
                            onValidate: _.bind((isValid) => {
                                this.onSubmit();
                            }, this)
                        });
                        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;
                    }
                    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}" />
            `);
                        if (this.source.multiLine) {
                            this.textNode.hide();
                        }
                        else {
                            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();
                            Tipped.create(this.node, this.formField.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                        else {
                            this.node.hide();
                        }
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                        Tipped.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.Dialog {
                    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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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, windowOptions) {
                        return new BatchFieldDialog(options, windowOptions);
                    }
                    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({
                                command: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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");
                    }
                    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>`;
                    }
                    focus() {
                        this.buttonNode.focus();
                    }
                    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) {
                            Tipped.create(this.node, this.source.tooltip, {
                                skin: "white",
                                showOn: "mouseenter",
                                hideOn: false,
                                hideAfter: 200,
                                hideDelay: 0,
                                maxWidth: 300
                            });
                        }
                    }
                    onClick(e) {
                        if (this.source.enabled) {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Information,
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNo,
                                title: "Execute Decision",
                                message: "Are you sure you want to execute this decision?",
                                select: (e) => {
                                    if (e.button === Jade.UI.MessageDialogButton.yes) {
                                        this.executeDecision();
                                    }
                                    e.close();
                                }
                            });
                        }
                    }
                    executeDecision() {
                        let service = new PDJS.Services.Process.ProcessService();
                        service.executeDecision({
                            decisionId: this.source.decisionId,
                            entityId: this.source.entityId,
                            success: (e) => {
                                switch (true) {
                                    case e.data.hasScriptErrors:
                                        this.showErrorsDialog(e.data.scriptErrors);
                                        break;
                                    case e.data.hasScriptAlerts:
                                        this.showSuccessDialog(e.data.scriptAlerts);
                                        break;
                                    default:
                                        window.location.reload();
                                        break;
                                }
                            }
                        });
                    }
                    showErrorsDialog(errors) {
                        Jade.UI.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "Decision Execution Errors",
                            header: "Decision execution failed due to the following errors:",
                            messages: errors, select: (e) => {
                                e.close();
                            }
                        });
                    }
                    showSuccessDialog(alerts) {
                        Jade.UI.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Success,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "Decision Execution Success",
                            header: "Decision execution succeeded with the following alerts:",
                            messages: alerts,
                            select: (e) => {
                                e.close();
                                window.location.reload();
                            }
                        });
                    }
                };
                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;top:0;left:0;right:0;bottom: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;top:0;left:0;right:0;bottom: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({
                            border: "1px solid #CCCCCC"
                        });
                    }
                };
                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;top:0;left:0;right:0;bottom: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({
                            border: "1px solid #CCCCCC"
                        });
                    }
                };
                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
                        });
                        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;top:0;left:0;right:0;bottom:0;border:1px solid #CCCCCC;" 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 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();
                        },
                        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 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
                        });
                    }
                    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 hasOnClickAction() {
                        return this.onClickAction != null
                            && this.onClickAction.id != null;
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get activeTabIndex() {
                        return this.tabIndex < 0 ? -1 : this.tabIndex + (Jade.Application.instance.contexts.current.depth * 1000);
                    }
                    get tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                };
                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");
                    }
                    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");
                    }
                    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 this.tabIndex < 0 ? -1 : this.tabIndex + (Jade.Application.instance.contexts.current.depth * 1000);
                    }
                    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 ImageButton extends Core.ElementModel {
                    constructor(options) {
                        super(options);
                        this.resolver = new CanvasJS.TypeResolver({
                            actualScript: "PDJS.Canvas.Actual.Common.ImageButton",
                            designScript: "PDJS.Canvas.Design.Common.ImageButton",
                            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 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.ImageButton = ImageButton;
            })(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");
                    }
                    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);
                    }
                }
                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");
                    }
                    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");
                    }
                    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 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 {
                    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.reloadExplorerPublish();
                                    }
                                }, 750);
                            },
                            error: (e) => {
                                if (_.isFunction(options.onError)) {
                                    options.onError(e);
                                }
                            }
                        });
                    }
                }
                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 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"] = 0] = "Boolean";
                    CanvasVariableType[CanvasVariableType["Date"] = 1] = "Date";
                    CanvasVariableType[CanvasVariableType["Number"] = 2] = "Number";
                    CanvasVariableType[CanvasVariableType["String"] = 3] = "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_list = [];
                        if (data != null) {
                            this.m_list = JSON.parse(JSON.stringify(data));
                        }
                    }
                    get ids() {
                        let result = [];
                        this.m_list.map(item => {
                            result[result.length] = item.id;
                        });
                        return result;
                    }
                    add(variable) {
                        if (variable.id == null || variable.name == null) {
                            return;
                        }
                        let index = this.getIndex(variable.id);
                        if (index > -1) {
                            this.m_list[index] = variable;
                        }
                        else {
                            this.m_list.push(variable);
                        }
                    }
                    remove(id) {
                        let index = this.getIndex(id);
                        if (index > -1) {
                            this.m_list.splice(index, 1);
                        }
                    }
                    get(id) {
                        let result = null;
                        if (this.contains(id)) {
                            result = _.first(this.m_list.filter(item => { item.id === id; }));
                        }
                        return result;
                    }
                    getIndex(id) {
                        let result = -1;
                        if (this.contains(id)) {
                            this.m_list.forEach((item, index) => {
                                result = (item.id === id) ? index : result;
                            });
                        }
                        return result;
                    }
                    contains(id) {
                        return this.ids.filter(key => { key === id; }) != null;
                    }
                    clear() {
                        this.m_list = [];
                    }
                    toArray() {
                        return this.m_list.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 formId() {
                        return this.state.get("formId");
                    }
                    set formId(value) {
                        this.state.set("formId", value);
                    }
                    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 tooltip() {
                        return this.state.get("tooltip");
                    }
                    set tooltip(value) {
                        this.state.set("tooltip", value);
                    }
                    get hasTooltip() {
                        return !Jade.String.isNullOrWhiteSpace(this.tooltip);
                    }
                    get activeEnabledState() {
                        return !this.isDisabled;
                    }
                    get tabIndex() {
                        return this.document.tabIndexes.indexOf(this.id);
                    }
                    get activeTabIndex() {
                        return this.tabIndex < 0 ? -1 : this.tabIndex + (Jade.Application.instance.contexts.current.depth * 1000);
                    }
                };
                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
                        });
                    }
                    get activeEnabledState() {
                        return !this.isDisabled && this.enabled;
                    }
                    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 ruleScript() {
                        return this.state.get("ruleScript");
                    }
                    set ruleScript(value) {
                        this.state.set("ruleScript", 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");
                    }
                    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.activeEnabledState ? (this.isRequired ? "#FF0000" : this.labelColor) : "#AAAAAA";
                    }
                    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
                        });
                    }
                    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 this.tabIndex < 0 ? -1 : this.tabIndex + (Jade.Application.instance.contexts.current.depth * 1000);
                    }
                    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 this.tabIndex < 0 ? -1 : this.tabIndex + (Jade.Application.instance.contexts.current.depth * 1000);
                    }
                    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 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");
                    }
                    get currentStageBorderColor() {
                        return this.state.get("currentStageBorderColor");
                    }
                    get currentStageBorderWidth() {
                        return this.state.get("currentStageBorderWidth");
                    }
                    get currentStageForeColor() {
                        return this.state.get("currentStageForeColor");
                    }
                    get selectedStageBackColor() {
                        return this.state.get("selectedStageBackColor");
                    }
                    get selectedStageBorderColor() {
                        return this.state.get("selectedStageBorderColor");
                    }
                    get selectedStageBorderWidth() {
                        return this.state.get("selectedStageBorderWidth");
                    }
                    get selectedStageForeColor() {
                        return this.state.get("selectedStageForeColor");
                    }
                    get showDecisionDestinations() {
                        return this.state.get("showDecisionDestinations");
                    }
                    get visitedStageBackColor() {
                        return this.state.get("visitedStageBackColor");
                    }
                    get visitedStageBorderColor() {
                        return this.state.get("visitedStageBorderColor");
                    }
                    get visitedStageBorderWidth() {
                        return this.state.get("visitedStageBorderWidth");
                    }
                    get visitedStageForeColor() {
                        return this.state.get("visitedStageForeColor");
                    }
                    get currentKeyBackColor() {
                        return this.state.get("currentKeyBackColor");
                    }
                    get currentKeyBorderColor() {
                        return this.state.get("currentKeyBorderColor");
                    }
                    get currentKeyBorderWidth() {
                        return this.state.get("currentKeyBorderWidth");
                    }
                    get currentKeyForeColor() {
                        return this.state.get("currentKeyForeColor");
                    }
                    get visitedKeyBackColor() {
                        return this.state.get("visitedKeyBackColor");
                    }
                    get visitedKeyBorderColor() {
                        return this.state.get("visitedKeyBorderColor");
                    }
                    get visitedKeyBorderWidth() {
                        return this.state.get("visitedKeyBorderWidth");
                    }
                    get visitedKeyForeColor() {
                        return this.state.get("visitedKeyForeColor");
                    }
                    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");
                    }
                    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);
                    }
                }
                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");
                    }
                    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");
                    }
                    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 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
                        });
                    }
                }
                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"
                });
            });
            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.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.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.Errors({}));
                    this.loadDocument();
                    this.loadToolBox();
                    CanvasJS.Design.Environment.surface.node.css({
                        backgroundColor: "#F8F8F8"
                    });
                    this.loadHotKeys();
                    this.window.kendo.onEscKey = (e) => {
                        (new Design.DocumentCloseCommand()).execute();
                    };
                }
                onCreateContext(e) {
                    super.onCreateContext(e);
                    let context = Jade.Application.instance.contexts.getContextById(e.contextId);
                    if (context != null) {
                        context.tags.push("canvas");
                    }
                }
                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);
                            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;
                    return null;
                }
            }
            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);
                }
                onActivate(e) {
                    super.onActivate(e);
                    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
                    });
                }
            }
            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.Dialog {
                constructor(options, windowOptions = {}) {
                    super(options, windowOptions);
                }
                get okButton() {
                    return this.node.find("button[command=ok]");
                }
                get cancelButton() {
                    return this.node.find("button[command=cancel]");
                }
                get applyButton() {
                    return this.node.find("button[command=apply]");
                }
                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");
                }
                get showApplyButton() {
                    return this.state.get("args.showApplyButton", false);
                }
                template() {
                    return `
            <div class="feature-blend-dialog">
                <div role="feature" data-controls></div>
                <div role="buttons" class="-pdjs-dialog-button-deck">
                    <button command="apply" class="-pdjs-dialog-button" style="display:none;">Apply</button>
                    <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.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();
                    });
                    this.applyButton.on(Jade.BrowserEvent.CLICK, () => {
                        this.apply();
                    });
                }
                getRequestData() {
                    return null;
                }
                getWindowOptions() {
                    let result = this.state.get("windowOptions");
                    result = _.extend({
                        title: this.state.get("title"),
                        maximized: false,
                        height: 550,
                        width: 500
                    }, result);
                    return result;
                }
                onInputReturnKeystroke() {
                    this.okButton.focus();
                    this.okButton.click();
                }
                getEditor() {
                    return new Features.FeatureEditor({
                        layoutType: this.layoutType,
                        onLoadSuccess: (e) => {
                            let dialogTitle = e.output.dialogTitle;
                            if (dialogTitle) {
                                this.setTitle(dialogTitle);
                            }
                        }
                    });
                }
                editor_init() {
                    this.m_editor = this.getEditor();
                    this.controls.add(this.m_editor);
                }
                save() {
                    this.editor.commit({
                        success: (e) => {
                            this.close({
                                command: "ok",
                                data: e
                            });
                        }
                    });
                }
                apply() {
                    this.editor.commit();
                }
            }
            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({
                                command: "ok",
                                data: e
                            });
                        }
                    });
                    ;
                }
                static open(options, windowOptions = {}) {
                    return new ElementEditorDialog(options, windowOptions);
                }
            }
            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: "#FFFFFF"
                    });
                    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)
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                sender.destroyContext();
                                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}`,
                        args: {
                            targetType: element.source.componentType,
                            targetData: element.source.toJSON(),
                            layoutType: editorSettings.layoutType
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                sender.destroyContext();
                                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);
                            }
                        }
                    }, {
                        height: editorSettings.height,
                        width: editorSettings.width,
                    });
                }
            }
            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",
                        label: "Auto Arrange",
                        icon: "layout_vertical.png",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Canvas.Design.Dialogs.AutoArrangeDialog.open({
                        callbacks: {
                            ok: () => {
                                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.MessageDialog.open({
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNoCancel,
                        dialogStyle: Jade.UI.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.button) {
                                case Jade.UI.MessageDialogButton.yes:
                                    this.autoTabIndex(true, inColumns);
                                    break;
                                case Jade.UI.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.JS.ProspectDirector.Web.UI.FeatureSets.Editors.ColorEditorDialog.open({
                        config: {
                            title: target === ICustomColorCommandTarget.backgroundColor ? "Background Color" : "Border Color"
                        },
                        data: {
                            hex: "#FFFFFF"
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                this.setColor(target, e);
                            }
                        }
                    });
                }
                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.DocumentVariablesCommand());
                    e.commands.add(new Design.FormFieldRequiredCommand({
                        id: "form-field/required/enable",
                        label: "Required",
                        icon: "breakpoint.png",
                        isRequired: true
                    }));
                    e.commands.add(new Design.FormFieldRequiredCommand({
                        id: "form-field/required/disable",
                        label: "Not Required",
                        icon: "not-required.png",
                        isRequired: false
                    }));
                    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",
                        icon: "navigate_plus.png",
                        scaling: Design.LineScaleType.increase,
                        target: Design.LineScaleTarget.shape
                    }));
                    e.commands.add(new Design.LineScaleCommand({
                        id: "line/shape/scale-up",
                        label: "Scale Up",
                        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",
                        icon: "navigate_minus.png",
                        scaling: Design.LineScaleType.decrease,
                        target: Design.LineScaleTarget.shape
                    }));
                    e.commands.add(new Design.LineCapShapeCommand({
                        id: "line/start/shape",
                        label: "Shape",
                        target: Design.LineCapShapeTarget.startCap
                    }));
                    e.commands.add(new Design.LineCapShapeCommand({
                        id: "line/end/shape",
                        label: "Shape",
                        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"
                    };
                }
                onExecute(e) {
                    if (CanvasJS.Design.Environment.document.source.hasChanges) {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            title: "Close",
                            message: `Close without saving changes?`,
                            select: (e) => {
                                e.close();
                                if (e.button == Jade.UI.MessageDialogButton.ok) {
                                    this.closeDocument();
                                }
                            }
                        });
                    }
                    else {
                        this.closeDocument();
                    }
                }
                closeDocument() {
                    let service = new PDJS.Services.Canvas.DocumentService();
                    let document = CanvasJS.Design.Environment.document.source;
                    service.closeDesignDocument({
                        sessionId: document.sessionId,
                        success: () => {
                            CanvasJS.Design.Environment.dialog.close();
                        }
                    });
                }
            }
            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 DocumentSaveCommand extends Jade.Command {
                getDefaultValuesForProps() {
                    return {
                        id: "document/save",
                        label: "Save",
                        icon: "floppy_disk.png",
                        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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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: (e) => {
                                e.close();
                                if (e.button == Jade.UI.MessageDialogButton.yes) {
                                    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.MultiMessageDialog.open({
                                    header: "The following errors prevents the document from being saved:",
                                    messages: e.data.saveErrors,
                                    dialogStyle: Jade.UI.MessageDialogStyle.Error,
                                    dialogButtons: Jade.UI.MessageDialogButtonStyle.OK
                                });
                                return;
                            }
                            CanvasJS.Design.Environment.dialog.close({
                                command: "ok",
                                data: e.data
                            });
                        }
                    });
                }
            }
            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",
                        label: "Settings",
                        icon: "clipboard_checks.png",
                        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",
                        icon: "function.png",
                        enabled: true,
                        display: "label icon",
                        iconSetId: "pdjs"
                    };
                }
                onExecute(e) {
                    PDJS.Canvas.Design.Dynamics.VariablesDialog.open({
                        callbacks: {
                            ok: () => {
                            }
                        }
                    });
                }
            }
            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",
                        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 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",
                        label: "Show Gridlines",
                        icon: "layout.png",
                        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.css({
                            backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("grid-background.png", Jade.IconSetSizeSpecificDirectory.misc)})`
                        });
                    }
                    else {
                        CanvasJS.Design.Environment.document.node.css({
                            backgroundImage: "none"
                        });
                    }
                }
            }
            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) {
            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 Shape",
                        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.MessageDialog.open({
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNoCancel,
                        dialogStyle: Jade.UI.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.button) {
                                case Jade.UI.MessageDialogButton.yes:
                                    this.addToExistingTabOrder();
                                    break;
                                case Jade.UI.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
                    });
                }
            }
            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() {
                        let chartOptions = null;
                        if (this.kendo != null && this.nodeWidth > 0 && this.nodeHeight > 0) {
                            chartOptions = this.getChartOptions();
                            this.kendo.setOptions(chartOptions);
                            this.kendo.refresh();
                        }
                    }
                    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 source = this.source.toJSON();
                        let chartState = $.extend(true, source, this.getChartData(source));
                        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
                            }
                        };
                    }
                };
                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:#000000;">${result}</span>`;
                            }
                            if (hasScalarFunction) {
                                result = `<span style="color:#0000FF;">${data.scalarFunctionName} of ${result} </span>`;
                            }
                            if (hasAggregateFunction) {
                                result = `<span style="color:#AA0000;">${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.Dialog {
                    constructor(options, windowOptions = {}) {
                        super(options, windowOptions);
                    }
                    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 `
            <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();
                        });
                    }
                    getWindowOptions() {
                        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.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                title: "No Anchors Selected",
                                message: `No anchors have been selected. Select at least one anchor and try again.`
                            });
                            return;
                        }
                        this.close({
                            command: "ok",
                            data: {
                                selections: this.grid.selections
                            }
                        });
                    }
                    static open(options, windowOptions = {}) {
                        return new AnchorSelectionDialog(options, windowOptions);
                        ;
                    }
                }
                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({
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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.button == Jade.UI.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.selectedConstraint !== null
                            && this.selectedConstraint.role == "condition";
                    }
                    onExecute(e) {
                        let depth = this.selectedConstraint.getDepth();
                        if (depth < 10) {
                            this.list.addCondition({
                                operatorName: "AND"
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtonStyle: Jade.UI.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,
                            height: "100px",
                            width: "100px",
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            title: "Remove Constraints",
                            message: "Remove all constraints?",
                            select: (e) => {
                                e.close();
                                if (e.button == Jade.UI.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}`,
                            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)
                                    }
                                }
                            },
                            callbacks: {
                                ok: (sender, e) => {
                                    this.selectedConstraint.state.set(e.target);
                                    this.list.applyNodeTemplateToAllAdjacent(this.selectedConstraint.id);
                                    this.constraints.commit();
                                }
                            }
                        }, {
                            height: 170,
                            width: 350
                        });
                    }
                    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.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,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            title: "Clear Document Types",
                            message: "Remove all document types?",
                            select: (e) => {
                                e.close();
                                if (e.button == Jade.UI.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,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            title: "Remove Fields",
                            message: "Remove all fields?",
                            select: (e) => {
                                e.close();
                                if (e.button == Jade.UI.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(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: "Copy",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    showEditorDialog(fieldType, okCallback) {
                        PDJS.Shared.Features.FeatureDialogForJson.open({
                            title: `Edit Field | ${this.field.columnName}`,
                            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"
                                    }
                                }
                            },
                            callbacks: {
                                ok: (sender, e) => {
                                    okCallback(sender, e.target);
                                }
                            }
                        }, {
                            height: 450,
                            width: 500
                        });
                    }
                }
                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 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.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 Jade.UI.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 Canvas;
    (function (Canvas) {
        var Design;
        (function (Design) {
            var Charts;
            (function (Charts) {
                class AnchorsEditorToolbar extends Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/anchors:anchor/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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 message() {
                        return this.state.get("message", "");
                    }
                    set message(value) {
                        this.state.set("message", value);
                    }
                    get messageNode() {
                        return this.node.find("div[role=message]");
                    }
                    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);
                    }
                }
                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;
                    }
                    get styleButton() {
                        return this.node.find("BUTTON[role=style]");
                    }
                    template() {
                        let icon = Jade.IconSet.get("pd")
                            .resolve("WINDOW_FONT.PNG", Jade.IconSetSizeSpecificDirectory.x16);
                        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();
                            },
                            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 Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/edit"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/duplicate"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/clear-all"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/categories:field/move-up"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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", 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 Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:condition/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:condition/toggle-operator"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:filter/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:filter/edit"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:filter/duplicate"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/constraints:constraint/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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 Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/documents:document-type/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/documents:document-type/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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;
                    }
                    get styleButton() {
                        return this.node.find("BUTTON[role=style]");
                    }
                    template() {
                        let icon = Jade.IconSet.get("pd")
                            .resolve("WINDOW_FONT.PNG", Jade.IconSetSizeSpecificDirectory.x16);
                        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();
                            },
                            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 Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/edit"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/duplicate"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/clear-all"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/legend:field/move-up"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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",
                                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.MessageDialog.open({
                                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                        dialogButtons: Jade.UI.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.button == Jade.UI.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;
                    }
                    get styleButton() {
                        return this.node.find("BUTTON[role=style]");
                    }
                    template() {
                        let icon = Jade.IconSet.get("pd")
                            .resolve("WINDOW_FONT.PNG", Jade.IconSetSizeSpecificDirectory.x16);
                        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();
                            },
                            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 Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/add"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/edit"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/duplicate"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/clear-all"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "canvas/design/chart/values:field/move-up"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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);
                    }
                    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.Dialog {
                    constructor(options, windowOptions = {}) {
                        super(options, windowOptions);
                    }
                    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 `
            <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();
                        });
                    }
                    getWindowOptions() {
                        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 ?
                            "" : `${depth}`;
                        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.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                title: "No Fields Selected",
                                message: `No fields have been selected. Select at least on field and try again.`
                            });
                            return;
                        }
                        this.close({
                            command: "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 buttonNode() {
                        return this.node.find("button");
                    }
                    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();
                        this.buttonNode.text(this.source.label);
                        this.buttonNode.prop("disabled", !this.source.enabled);
                    }
                };
                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: "#DDDDDD",
                            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 ImageButton = class ImageButton extends Design.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>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.imageNode.prop("src", this.getImageUrl());
                        this.node.css({
                            opacity: this.source.enabled ? 1 : .5
                        });
                        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(`~${imageUrl}`);
                            }
                            else if (imageUrl.indexOf("~") === 0) {
                                result = Jade.Path.resolve(imageUrl);
                            }
                            else {
                                result = Jade.Path.resolve(`~/resources/${imageUrl}`);
                            }
                        }
                        return result;
                    }
                };
                ImageButton = __decorate([
                    Jade.UI.Controls.toolingTags("image-button")
                ], ImageButton);
                Common.ImageButton = ImageButton;
            })(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,
                            backgroundColor: this.source.backgroundColor,
                            borderColor: noBorder ? "#DDDDDD" : 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%;">
                        <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;color:#AAAAAA;">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: "#FFFFFF",
                            borderColor: noBorder ? "#DDDDDD" : 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%;">
                        <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,
                            borderColor: noBorder ? "#DDDDDD" : this.source.borderColor == null ? "transparent" : `${this.source.borderColor}`,
                            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`,
                            backgroundColor: this.source.backgroundColor == null ? "transparent" : `${this.source.backgroundColor}`
                        });
                        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%;">
                        <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;color:#AAAAAA;">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: "Theme Colors"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemColorPalette({
                            commandId: "canvas/standard:element/background-color",
                            palette: Jade.UI.Controls.ContextMenuItemColorPalettes.themeColors,
                            closeOnClick: true
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemHeader({
                            label: "Standard Colors"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemColorPalette({
                            commandId: "canvas/standard:element/background-color",
                            palette: Jade.UI.Controls.ContextMenuItemColorPalettes.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: "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: "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: "triangle.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: "Theme Colors"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemColorPalette({
                            commandId: "canvas/standard:element/border-color",
                            palette: Jade.UI.Controls.ContextMenuItemColorPalettes.themeColors
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemHeader({
                            label: "Standard Colors"
                        }));
                        this.items.add(new Jade.UI.Controls.ContextMenuItemColorPalette({
                            commandId: "canvas/standard:element/border-color",
                            palette: Jade.UI.Controls.ContextMenuItemColorPalettes.standardColors
                        }));
                        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:black;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 Dialogs;
            (function (Dialogs) {
                class AutoArrangeDialog extends Jade.UI.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 `<div style="position:absolute;top:10px;right:10px;bottom:10px;left:10px;">
                        <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="-jadejs-button">OK</button>
                            <button data-command="cancel" class="-jadejs-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();
                    }
                    getWindowOptions() {
                        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.IntegerField({
                                label: "Column Count",
                                numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer
                            });
                        this.controls.add(this.m_columnCount);
                    }
                    columnWidth_init() {
                        this.m_columnWidth =
                            new PDJS.Shared.UI.Controls.Fields.IntegerField({
                                label: "Column Width",
                                numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer
                            });
                        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.IntegerField({
                                label: "Column Spacing",
                                numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer
                            });
                        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.IntegerField({
                                label: "Row Spacing",
                                numericType: PDJS.Shared.UI.Controls.NumericTextBoxType.integer
                            });
                        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.window.destroyContext();
                        this.close({
                            command: "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 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.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 `<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) {
                        this.setCommandState();
                    }
                    getWindowOptions() {
                        return {
                            title: "Manage | Variables",
                            height: 400,
                            width: 600
                        };
                    }
                    onResize() {
                        if (this.m_splitter) {
                            this.m_splitter.resize();
                        }
                    }
                    static open(options) {
                        return new VariablesDialog(options);
                    }
                    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.window.destroyContext();
                        this.close({
                            command: "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 Jade.UI.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
                            }
                        });
                    }
                }
                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
                                    });
                                }
                            },
                            resizable: true,
                            dataSource: {
                                data: [],
                                storeAsLocalVariable: true
                            },
                            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;
                        Jade.Application
                            .instance
                            .contexts
                            .revolveContext({
                            tags: ["canvas"],
                            fn: () => {
                                let document = CanvasJS.Design.Environment.document;
                                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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "pdjs/canvas/variables:variable/create"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "pdjs/canvas/variables:variable/edit"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "pdjs/canvas/variables:variable/delete"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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 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
                        });
                    }
                    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) {
                        Dynamics.VariableList.variables.clear();
                        this.updateGrid();
                        this.setCommandState();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/clear",
                            label: "Clear",
                            icon: "eraser.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                }
                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",
                            args: {
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Canvas.CanvasVariableArbiter",
                                targetType: "ProspectDirector.Web.UI.Canvas.CanvasVariable",
                                properties: {
                                    variables: JSON.stringify(Dynamics.VariableList.variables.toArray())
                                }
                            },
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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 {
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.selections.length > 0;
                    }
                    onExecute(e) {
                        let variable = _.first(this.selections);
                        Dynamics.VariableList.variables.remove(variable.id);
                        this.updateGrid();
                        this.setCommandState();
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "variable/delete",
                            label: "Delete",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdjs"
                        };
                    }
                }
                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",
                            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())
                                }
                            },
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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 buttonNode() {
                        return this.node.find("button");
                    }
                    template() {
                        return `<button style="height:100%;width:100%;box-sizing:border-box;">${this.source.label}</button>`;
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.buttonNode.text(this.source.label);
                    }
                }
                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();
                    }
                    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");
                    }
                    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();
                        this.buttonNode.text(this.source.activeLabel);
                    }
                };
                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;top:0;left:0;right:0;bottom: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",
                            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 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/close"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/settings"
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            commandId: "pdjs/canvas/standard:document/variables"
                        }));
                    }
                }
                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",
                            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: "Begin",
                                    menu: ["start-cap-shape"]
                                }),
                                new Jade.UI.Controls.RibbonBarButtonSmall({
                                    icon: Jade.IconSet.get("pdjs").resolve("shapes.png", Jade.IconSetSizeSpecificDirectory.x16),
                                    label: "End",
                                    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 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",
                            icon: "rotate_left.png",
                            commandId: "pdjs/canvas/standard:shape/rotate",
                            value: 0
                        }));
                        this.controls.add(new Jade.UI.Controls.RibbonBarButton({
                            label: "Rotate Right",
                            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 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);
                    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",
                        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",
                        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
                        });
                        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.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() {
                        Tipped.create(this.anchor, `<div id="popup-${this.ID}" style="height:350px;width: 400px;"></div>`, {
                            skin: "white",
                            padding: false,
                            showOn: false,
                            hideOn: false,
                            stem: false,
                            position: { target: "topright", tooltip: "bottomright" },
                            zIndex: 10004,
                            detach: false,
                            offset: { x: -1, y: -3 }
                        });
                        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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Information,
                            dialogButtons: Jade.UI.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.button == Jade.UI.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 ToolBox;
            (function (ToolBox) {
                class ToolBoxAction extends CanvasJS.Design.ToolBoxAction {
                    createStates(args) {
                        let states = [];
                        let x = args.x;
                        let y = args.y;
                        args.items.forEach(item => {
                            let state = this.createState(_.clone(item));
                            if (state != null) {
                                states.push(_.extend(state, {
                                    id: Jade.Guid.new(),
                                    x: x,
                                    y: y
                                }));
                                x += 20;
                                y += 20;
                            }
                        });
                        this.initElements(states);
                    }
                    createState(item) {
                        return {};
                    }
                    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 element = this.createElement(state);
                            if (element) {
                                elements.push(element);
                            }
                        });
                        this.appendElements(elements);
                    }
                    createElement(state) {
                        return 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({
                            callbacks: {
                                ok: (sender, result) => {
                                    sender.close();
                                    this.batchFieldType = result.batchFieldType;
                                    this.createStates({
                                        items: [this.instance],
                                        x: e.x,
                                        y: e.y
                                    });
                                }
                            }
                        });
                    }
                    createState(item) {
                        return _.extend(item, {
                            selectIdentities: this.batchFieldType == ToolBox.BatchFieldType.Identities,
                        });
                    }
                    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.Dialog {
                    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 `<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>`;
                    }
                    getWindowOptions() {
                        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({
                            command: "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,
                            callbacks: {
                                ok: (sender, result) => {
                                    sender.close();
                                    this.createStates({
                                        items: result,
                                        x: e.x,
                                        y: e.y
                                    });
                                }
                            }
                        });
                    }
                    createState(item) {
                        let state = _.clone(this.fieldMap[item.fieldType]);
                        let result = _.extend(state, {
                            columnId: item.columnId,
                            columnFormat: item.columnFormat,
                            defaultLabel: item.columnName
                        });
                        return result;
                    }
                    createElement(state) {
                        return 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.Dialog {
                    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) {
                        this.grid_onActivate();
                        this.okButton.on("click", _.bind(this.okButton_onClick, this));
                        this.cancelButton.on("click", _.bind(this.cancelButton_onClick, this));
                    }
                    template() {
                        return `<div class="-pdjs-FormFieldSeletionDialog">
                        <div data-role="grid"></div>
                        <div data-role="deck">
                            <button class="-jadejs-button" data-role="ok">OK</button>
                            <button class="-jadejs-button" data-role="cancel">Cancel</button>
                        </div>
                    </div>`;
                    }
                    getWindowOptions() {
                        return {
                            title: "Form Field Selection",
                            height: 500,
                            width: 650
                        };
                    }
                    okButton_onClick(e) {
                        this.returnSelected();
                    }
                    cancelButton_onClick(e) {
                        this.close();
                    }
                    grid_onActivate() {
                        let options = this.state.toJSON();
                        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({
                            command: "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 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;top:0;left:0;right:0;bottom:0;border:1px solid #CCCCCC;" 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 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 style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis"></div>`;
                }
                update() {
                    this.updateUI();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.css({
                        position: "absolute",
                        bottom: "5px",
                        left: 0,
                        right: 0,
                        height: "25px",
                        boxSizing: "border-box",
                        lineHeight: "25px",
                        backgroundColor: "transparent",
                        paddingTop: "5px"
                    });
                    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 += `<span role="refresh" style="padding-left:10px;color:#007acc;text-decoration:underline;cursor:pointer;">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></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.css({
                        position: "absolute",
                        height: "16px",
                        width: "16px",
                        boxSizing: "border-box",
                        backgroundColor: "transparent",
                        paddingTop: "5px",
                        backgroundImage: `url(${Jade.IconSet.get("pdjs").resolve("bars.png", Jade.IconSetSizeSpecificDirectory.misc)})`,
                        backgroundPosition: "center center",
                        backgroundRepeat: "no-repeat",
                        cursor: "pointer"
                    });
                    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 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"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.node.on(Jade.BrowserEvent.CLICK, _.bind(() => {
                        this.clickCallback();
                        this.menu.popUp.hide();
                    }, this));
                }
                onStateChanged() {
                    super.onStateChanged();
                    this.node.css({
                        height: "25px",
                        padding: "5px 5px 5px 26px",
                        fontSize: "12px",
                        fontFamily: "Arial",
                        border: "0 solid #EEEEEE",
                        margin: "0",
                        boxSizing: "border-box",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                        display: "block",
                        width: "100%",
                        cursor: "pointer"
                    });
                    if (this.icon != null) {
                        this.node.css({
                            backgroundImage: `url(${this.icon})`,
                            backgroundRepeat: "no-repeat",
                            backgroundPosition: "5px center"
                        });
                    }
                    if ($("style[data-control-style=-pdjs-element-menu-item]").length == 0) {
                        document.head.insertAdjacentHTML("beforeend", `
                <style data-control-style="-pdjs-element-menu-item">
                    .-pdjs-element-menu-item:hover {
                        background-color: #EEEEEE;
                    }
                </style>`);
                    }
                    this.node.text(this.label);
                }
            }
            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>${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"
                    });
                    Tipped.create(this.anchor, this.node, {
                        skin: "white-no-padding",
                        radius: false,
                        shadow: false,
                        stem: false,
                        position: "bottomright",
                        showOn: "click",
                        hideAfter: 500,
                        hideDelay: 500,
                        fadeOut: 100,
                        showDelay: 0,
                        hideOn: "click-outside",
                        hideOthers: true,
                        detach: false,
                        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;
                        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 = labels.color;
                            result.labels.font = labels.fontSize + " " + labels.fontName;
                            result.labels.rotation = labels.rotation;
                            result.labels.visible = labels.visible;
                        }
                        if (line) {
                            result.line.color = line.color;
                            result.line.width = line.width;
                            result.line.visible = line.visible;
                        }
                        if (title) {
                            result.title.color = title.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 = majorGridLines.color;
                            result.majorGridLines.dashType = majorGridLines.dashType;
                            result.majorGridLines.visible = majorGridLines.visible;
                            result.majorTicks.visible = majorGridLines.tickMarks;
                        }
                        if (minorGridLines) {
                            result.minorGridLines.color = minorGridLines.color;
                            result.minorGridLines.dashType = minorGridLines.dashType;
                            result.minorGridLines.visible = minorGridLines.visible;
                            result.minorTicks.visible = minorGridLines.tickMarks;
                        }
                        return result;
                    }
                    getChartArea() {
                        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 = chartArea.backColor;
                        result.border.color = chartArea.borderColor;
                        result.border.dashType = chartArea.borderStyle;
                        result.border.width = chartArea.borderWidth;
                        return result;
                    }
                    getLegend() {
                        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 = labels.color;
                            result.labels.font = `${labels.fontSize}  ${labels.fontName}`;
                        }
                        return result;
                    }
                    getPlotArea() {
                        var result = { border: {} };
                        let plotArea = this.style.plotArea;
                        if (plotArea == null) {
                            return result;
                        }
                        result.background = plotArea.backColor;
                        result.border.color = plotArea.borderColor;
                        result.border.width = plotArea.borderWidth;
                        return result;
                    }
                    getSeriesDefaults() {
                        var _a, _b;
                        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 = labels.backColor;
                            result.labels.border.color = labels.borderColor;
                            result.labels.border.width = labels.borderWidth;
                            result.labels.color = labels.color;
                            result.labels.font = `${labels.fontSize} ${labels.fontName}`;
                            result.labels.padding = labels.padding;
                            result.labels.visible = labels.visible;
                        }
                        if (tooltip) {
                            result.tooltip.background = tooltip.backColor;
                            result.tooltip.border.color = tooltip.borderColor;
                            result.tooltip.border.width = tooltip.borderWidth;
                            result.tooltip.color = tooltip.color;
                            result.tooltip.font = `${tooltip.fontSize} ${tooltip.fontName}`;
                            result.tooltip.padding = tooltip.padding;
                            result.tooltip.visible = tooltip.visible;
                        }
                        return result;
                    }
                    getTitle() {
                        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 = title.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;
                        }
                        let labels = (_a = this.style.valueAxis) === null || _a === void 0 ? void 0 : _a.labels;
                        let line = (_b = this.style.valueAxis) === null || _b === void 0 ? void 0 : _b.line;
                        let title = (_c = this.style.valueAxis) === null || _c === void 0 ? void 0 : _c.title;
                        let majorGridLines = (_d = this.style.valueAxis) === null || _d === void 0 ? void 0 : _d.majorGridLines;
                        let minorGridLines = (_e = this.style.valueAxis) === null || _e === void 0 ? void 0 : _e.minorGridLines;
                        if (labels) {
                            result.labels.color = labels.color;
                            result.labels.font = labels.fontSize + " " + labels.fontName;
                            result.labels.rotation = labels.rotation;
                            result.labels.visible = labels.visible;
                        }
                        if (line) {
                            result.line.color = line.color;
                            result.line.width = line.width;
                            result.line.visible = line.visible;
                        }
                        if (title) {
                            result.title.color = title.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 = majorGridLines.color;
                            result.majorGridLines.dashType = majorGridLines.dashType;
                            result.majorGridLines.visible = majorGridLines.visible;
                            result.majorTicks.visible = majorGridLines.tickMarks;
                        }
                        if (minorGridLines) {
                            result.minorGridLines.color = minorGridLines.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);
                        }
                        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 = Jade.IconSet.get("pdjs")
                            .resolve("nav_right.png", Jade.IconSetSizeSpecificDirectory.x16);
                    }
                    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;
                    }
                    template() {
                        return `<a href="#" />`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            top: "2px",
                            right: "23px",
                            bottom: "2px",
                            width: "20px",
                            display: "none",
                            backgroundImage: `url(${this.imageUrl})`,
                            backgroundPosition: "center center",
                            backgroundRepeat: "no-repeat"
                        });
                    }
                    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"
                        });
                    }
                    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 textValue() {
                        return this.input.textValue;
                    }
                    set textValue(value) {
                        this.input.textValue = value;
                    }
                    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)
                        });
                        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;
                        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,
                            height: 200,
                            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();
                            }
                        });
                    }
                    onShowDialog(e) {
                        PDJS.Shared.Dialogs.IconBrowserDialog.open({
                            callbacks: {
                                ok: (sender, data) => {
                                    this.selection = {
                                        icon: data.value,
                                        name: data.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();
                            }
                        });
                    }
                    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)],
                            callbacks: {
                                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-ctrl">
                        <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,
                                    callbacks: {
                                        ok: (sender, e) => {
                                            sender.destroyContext();
                                            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);
                        this.node.on(Jade.BrowserEvent.MOUSEENTER, () => {
                            if (this.isUnassigned) {
                            }
                        });
                        this.node.on(Jade.BrowserEvent.MOUSELEAVE, () => {
                            if (this.isUnassigned && this.stageId != null) {
                            }
                        });
                        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 `<table style="height:100%;width:100%;position:absolute;top:0;right:0;bottom:0;left:0;background-color:#FFFFFF;">
                        <tr>
                            <td style="text-align:center;vertical-align:center;">
                                <button tabIndex="${this.tabIndex}">Assign Process</button>
                            </td>
                        </tr>
                    </table>`;
                    }
                    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.Dialog {
                    constructor(options) {
                        super(options);
                    }
                    get entityTypeId() {
                        return this.state.get("entityTypeId");
                    }
                    get processList() {
                        return this.m_processList;
                    }
                    get statusList() {
                        return this.m_statusList;
                    }
                    get stageTree() {
                        return this.m_stageTree;
                    }
                    get okButton() {
                        return this.node.find("button[data-command=ok]");
                    }
                    get cancelButton() {
                        return this.node.find("button[data-command=cancel]");
                    }
                    template() {
                        return `
                <div style="position:absolute;top:10px;right:10px;bottom:10px;left:10px;">
                    <div role="inputs" data-controls style="position:absolute;top:0;right:0;left:0;height:100px;">
                    
                    </div>
                    <div style="position:absolute;top:100px;right:0;left:0;bottom:34px;">
                        <div style="height:26px;line-height:26px;font-family:arial;font-size:12px;color:red;">Assign Stage Of:</div>
                        <div role="process-stage-grid" style="position:absolute;top:26px;right:0;left:0;bottom:0;"></div>
                    </div>
                    <div style="position:absolute;bottom:0;height:24px;left:0;right:0;text-align:right;overflow:hidden;">
                        <button class="-jadejs-button" data-command="ok">OK</button>
                        <button class="-jadejs-button" data-command="cancel">Cancel</button>
                    </div>
                </div>`;
                    }
                    getWindowOptions() {
                        return {
                            title: "Process Assignment",
                            height: 450,
                            width: 450
                        };
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.stageTree_init();
                        this.processList_init();
                        this.statusList_init();
                        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) => {
                                if (value != null) {
                                    this.statusList.processId = value.id;
                                    this.stageTree.processId = value.id;
                                }
                                else {
                                    this.statusList.processId = null;
                                    this.stageTree.processId = null;
                                }
                            }
                        });
                        this.controls.add(this.processList);
                    }
                    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.m_stageTree = new Forms.EntityProcessTree({
                            insertAt: "div[role=process-stage-grid]",
                            height: "100%",
                            width: "100%"
                        });
                        this.controls.add(this.m_stageTree);
                    }
                    okButton_onClick(e) {
                        if (this.isValid()) {
                            this.close({
                                command: "ok",
                                data: {
                                    processId: this.m_processList.processId,
                                    processName: this.m_processList.processName,
                                    keyIcon: this.m_stageTree.keyIcon,
                                    keyName: this.m_stageTree.keyName,
                                    stageId: this.m_stageTree.stageId,
                                    stageName: this.m_stageTree.stageName,
                                    statusId: this.m_statusList.statusId,
                                    statusIcon: this.m_statusList.statusIcon,
                                    statusName: this.m_statusList.statusName
                                }
                            });
                        }
                    }
                    cancelButton_onClick(e) {
                        this.close({
                            command: "cancel"
                        });
                    }
                    isValid() {
                        let result = true;
                        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.m_stageTree.stageId == null) {
                            result = false;
                            Jade.UI.MessageDialog.open({
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                message: "A process stage must be selected.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                        return result;
                    }
                    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 Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Forms;
            (function (Forms) {
                class EntityProcessTree extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get processId() {
                        return this.state.get("processId");
                    }
                    set processId(value) {
                        this.state.set("processId", value);
                    }
                    get height() {
                        return this.state.get("height", "100%");
                    }
                    set height(value) {
                        this.state.set("height", value);
                    }
                    get width() {
                        return this.state.get("width", "100%");
                    }
                    set width(value) {
                        this.state.set("width", value);
                    }
                    get selection() {
                        return this.m_selection;
                    }
                    get treeNode() {
                        return this.node.find("div[role=tree]");
                    }
                    get stageId() {
                        return this.selection != null
                            ? this.selection.id : null;
                    }
                    get stageIcon() {
                        return this.selection != null
                            ? this.selection.icon : null;
                    }
                    get stageName() {
                        return this.selection != null
                            ? this.selection.name : null;
                    }
                    get keyIcon() {
                        return this.selection != null
                            ? this.selection.keyIcon : null;
                    }
                    get keyName() {
                        return this.selection != null
                            ? this.selection.keyName : null;
                    }
                    template() {
                        return `
                    <div style="border:1px solid #AAAAAA;position:relative;background-color:#FFFFFF;overflow:auto;">
                        <div role="tree" class="-pdjs-tree" style="padding-top:5px;"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_processService =
                            new PDJS.Services.Process.ProcessService();
                        this.tree_init();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.css({
                            height: this.height,
                            width: this.width
                        });
                        if (this.state.hasChanged("processId")) {
                            this.m_selection = null;
                            this.tree_load();
                        }
                    }
                    tree_init() {
                        let that = this;
                        this.m_tree = this.treeNode.kendoTreeView({
                            dataSource: {
                                transport: {
                                    read: function (e) {
                                        let item = e.data;
                                        if (item != null && item.id != null) {
                                            let node = that.m_tree.findByUid(item.dataItem.uid);
                                            that.m_processService.getStages({
                                                keyId: item.id,
                                                success: (response) => {
                                                    e.success([]);
                                                    _.each(response.data, (data) => {
                                                        that.m_tree.append({
                                                            id: data.id,
                                                            text: data.name,
                                                            imageUrl: Jade.IconSet.get("pd").resolve(data.icon, Jade.IconSetSizeSpecificDirectory.x16),
                                                            hasChildren: false,
                                                            icon: data.icon,
                                                            type: "stage"
                                                        }, node);
                                                    });
                                                }
                                            });
                                        }
                                    }
                                }
                            },
                            select: _.bind(this.tree_select, this)
                        }).data("kendoTreeView");
                        this.tree_load();
                    }
                    tree_load() {
                        this.m_tree.dataSource.data([]);
                        if (this.processId == null) {
                            this.addNoProcessMessage();
                            return;
                        }
                        this.m_processService.getKeys({
                            processId: this.processId,
                            success: (response) => {
                                this.removeNoProcessMessage();
                                _.each(response.data, (data) => {
                                    this.m_tree.append(_.extend(data, {
                                        imageUrl: Jade.IconSet.get("pd").resolve(data.icon, Jade.IconSetSizeSpecificDirectory.x16),
                                        type: "key"
                                    }));
                                });
                            }
                        });
                    }
                    tree_select(e) {
                        let data = this.m_tree.dataItem(e.node);
                        if (data == null) {
                            this.m_selection = null;
                            return;
                        }
                        if (data.type != "stage") {
                            e.preventDefault();
                            return;
                        }
                        let key = data.parentNode();
                        this.m_selection = {
                            id: data.id,
                            icon: data.icon,
                            name: data.text,
                            keyId: key.id,
                            keyIcon: key.icon,
                            keyName: key.text
                        };
                    }
                    addNoProcessMessage() {
                        let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message == null) {
                            this.controls.add(new PDJS.Shared.UI.Controls.Message({
                                message: "No process selected."
                            }));
                        }
                    }
                    removeNoProcessMessage() {
                        let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                        if (message != null) {
                            this.controls.remove(message);
                        }
                    }
                }
                Forms.EntityProcessTree = EntityProcessTree;
            })(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 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();
                            }
                        });
                    }
                    onShowDialog() {
                        PDJS.Shared.Entities.EntityBrowserDialog.open({
                            viewStateId: this.viewStateId,
                            callbacks: {
                                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();
                            }
                        });
                    }
                    onShowDialog() {
                        Forms.UserFieldComboBoxDialog.open({
                            viewStateId: this.viewStateId,
                            callbacks: {
                                ok: (sender, e) => {
                                    let item = _.first(e);
                                    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.Dialog {
                    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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                    }
                    getWindowOptions() {
                        return {
                            title: "User Browser",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    static open(options) {
                        return new UserFieldComboBoxDialog(options);
                    }
                    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.window.destroyContext();
                            this.close({
                                command: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                title: "No User Selected",
                                message: "No user has been selected. Select a user and try again.",
                                select: (e) => {
                                    e.close();
                                }
                            });
                        }
                    }
                }
                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 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;top:0;right:0;bottom:0;left: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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Information,
                            dialogButtons: Jade.UI.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.button === Jade.UI.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) => {
                                switch (true) {
                                    case e.data.hasScriptErrors:
                                        this.showExecuteDecisionErrorsDialog(e.data.scriptErrors);
                                        break;
                                    case e.data.hasScriptAlerts:
                                        this.showExecuteDecisionSuccessDialog(e.data.scriptAlerts);
                                        break;
                                    default:
                                        window.location.reload();
                                        break;
                                }
                            }
                        });
                    }
                    showExecuteDecisionErrorsDialog(errors) {
                        Jade.UI.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "Decision Execution Errors",
                            header: "Decision execution failed due to the following errors:",
                            messages: errors, select: (e) => {
                                e.close();
                            }
                        });
                    }
                    showExecuteDecisionSuccessDialog(alerts) {
                        Jade.UI.MultiMessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Success,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "Decision Execution Success",
                            header: "Decision execution succeeded with the following alerts:",
                            messages: alerts,
                            select: (e) => {
                                e.close();
                                window.location.reload();
                            }
                        });
                    }
                }
                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 || "#000000"
                            });
                        }
                        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 || "#000000"} !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 || "#000000"
                            });
                        }
                        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 || "#000000"
                            });
                        }
                        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 #CCCCCC" : "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 #CCCCCC" : 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);
                        Tipped.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() {
                        Tipped.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);
                        });
                        Tipped.create(this.node, tooltipNode, {
                            skin: "white"
                        });
                    }
                }
                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.node.css({
                            borderRadius: "50%",
                            backgroundColor: this.backgroundColor,
                            borderColor: this.borderColor,
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.css({
                            borderRadius: "50%",
                            backgroundColor: this.backgroundColor,
                            borderColor: this.borderColor,
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle
                        });
                    }
                }
                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 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 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.endCapWidth;
                        let y2 = topY;
                        let x3 = l.endCapWidth;
                        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);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            backgroundColor: this.backgroundColor,
                            borderColor: this.borderColor,
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.node.css({
                            backgroundColor: this.backgroundColor,
                            borderColor: this.borderColor,
                            borderWidth: this.borderWidth,
                            borderStyle: this.borderStyle
                        });
                    }
                }
                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",
                            icon: "pencil_and_square.png"
                        });
                    }
                    onStateChanged(e) {
                        super.onStateChanged(e);
                        this.visible = this.enabled;
                    }
                    onExecute(e) {
                        Views.ViewDesignerDialog.open({
                            viewStateId: this.viewStateId,
                            callbacks: {
                                ok: (sender) => {
                                    sender.destroyContext();
                                    if (this.grid != null) {
                                        this.grid.build();
                                    }
                                },
                                cancel: (sender) => {
                                    sender.destroyContext();
                                }
                            }
                        });
                    }
                }
                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 Canvas;
    (function (Canvas) {
        var Shared;
        (function (Shared) {
            var Views;
            (function (Views) {
                class ViewDesignerDialog extends Jade.UI.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 `<div style="position:absolute;top:10px;right:10px;bottom:10px;left:10px;">
                        <div role="toolbar" style='position:absolute;height:30px;top:0;left:0;right:0;border-width:0px;overflow:hidden;'></div>
                        <div role="grid" style="position:absolute;top:40px;right:0;bottom:36px;left:0;border: 1px solid #CCCCCC;">
                        </div>
                        <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                            <button data-command="ok" class="-jadejs-button">OK</button>
                            <button data-command="cancel" class="-jadejs-button">Cancel</button>
                        </div>
                    </div>`;
                    }
                    static open(options) {
                        return new ViewDesignerDialog(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.grid_init();
                        this.toolbar_init();
                        this.m_service =
                            new PDJS.Services.Views.ViewService();
                        this.m_service.getViewState({
                            viewStateId: this.viewStateId,
                            success: (e) => {
                                this.m_viewState = e.data.state;
                            }
                        });
                    }
                    getWindowOptions() {
                        return {
                            title: "View Designer",
                            height: 600,
                            width: 800
                        };
                    }
                    okButton_onClick(e) {
                        this.close({
                            command: "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: () => {
                                this.toolbar_init();
                            }
                        });
                    }
                    toolbar_init() {
                        this.m_toolbar = new PDJS.JS.PD.Web.UI.Controls.Toolbar({
                            container: this.toolbarNode,
                            segments: [
                                new PDJS.JS.PD.Manage.Modules.ViewDesignToolbar(() => {
                                    return {
                                        viewGrid: this.grid
                                    };
                                })
                            ]
                        });
                    }
                }
                Views.ViewDesignerDialog = ViewDesignerDialog;
            })(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) {
        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 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 = 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;
                    }
                    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;
                    }
                    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
                                });
                            }
                        });
                    }
                    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 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 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);
                }
                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;
                        }
                    });
                }
                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();
                }
                get upload() {
                    return this.m_upload;
                }
                commit(entityId, folderId, success, error) {
                    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 = "black";
                            this.statusText = "Pending Upload";
                            break;
                        case isUploading:
                            this.statusIcon = "hourglass.png";
                            this.statusColor = "blue";
                            this.statusText = "Uploading...";
                            break;
                        case uploadFailed:
                            this.statusIcon = "error.png";
                            this.statusColor = "red";
                            this.statusText = "Upload Failed";
                            break;
                        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 ? "Warning" : "Warnings"}`;
                            break;
                        case isReady || isValidated:
                            this.statusIcon = "ok.png";
                            this.statusColor = "darkgreen";
                            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}">
                        <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 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 -= 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("percent");
                }
                set type(value) {
                    this.state.set("percent", 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() {
                    return _.extend(this.state.toJSON(), {
                        filters: this.filters.toJSON(),
                        conditions: this.conditions.toJSON()
                    });
                }
                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(childTypeId) {
                    return new EntityFilter("ParentFilter", {
                        childTypeId: childTypeId
                    });
                }
                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;
        })(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() {
                    return _.extend(this.state.toJSON(), {
                        useAutoValue: this.autoValueId != null
                    });
                }
                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 value = !Jade.String.isNullOrWhiteSpace(this.verse) ?
                        this.verse : 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.Shared.Environment.current;
            }
            template() {
                return `
                <div class="-pdjs-fwk-app-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: "~/application/icons/misc/24x24/home.png",
                    url: Jade.Path.resolve("~/Hub/Home")
                }));
                if (this.env.userMenu.entityTypes.length > 0) {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "~/application/icons/misc/24x24/plus.png",
                        onClick: (e) => {
                            this.m_createPanel.toggle();
                        }
                    }));
                }
                if (this.env.userMenu.views.length == 0) {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "~/application/icons/misc/24x24/binocular.png",
                        url: Jade.Path.resolve("~/Hub/ViewBrowser/Global")
                    }));
                }
                else {
                    this.controls.add(new Hub.ApplicationBarItem({
                        icon: "~/application/icons/misc/24x24/binocular.png",
                        onClick: (e) => {
                            this.m_viewPanel.toggle();
                        }
                    }));
                }
                this.controls.add(new Hub.GlobalSearch({
                    width: 200,
                    backgroundColor: "rgba(255, 255, 255, .4)"
                }));
                this.controls.add(new Hub.ApplicationBarItem({
                    backgroundColor: "rgba(0, 0, 0, .4)",
                    icon: "~/application/icons/misc/24x24/user.png",
                    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: this.env.theme.textColor
                });
                this.node.css({
                    backgroundColor: this.env.theme.backgroundColor
                });
                this.titleNode.text(this.env.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 icon() {
                return this.state.get("icon");
            }
            get url() {
                return this.state.get("url", "#");
            }
            get width() {
                return this.state.get("width", 40);
            }
            get backgroundColor() {
                return this.state.get("backgroundColor", null);
            }
            get onClickCallback() {
                return this.state.get("onClick", () => { });
            }
            get target() {
                return this.state.get("target");
            }
            template() {
                if (this.url == null) {
                    return `<div><div>`;
                }
                else {
                    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`,
                    backgroundColor: this.backgroundColor == null ? "" : this.backgroundColor,
                    backgroundPosition: "center center",
                    backgroundRepeat: "no-repeat"
                });
                if (this.icon != null) {
                    this.node.css({
                        backgroundImage: `url(${icon})`
                    });
                }
                if (this.url != null && this.url != "#") {
                    let url = Jade.Path.resolve(this.url);
                    this.node.attr("href", url);
                }
                else if (this.onClickCallback != null) {
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        e.stopImmediatePropagation();
                        this.onClickCallback(e);
                    });
                }
                if (this.target != null) {
                    this.node.attr("target", this.target);
                }
            }
        }
        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() {
                        return `<div class="-pdjs-ui-panel-menu"></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) => {
                                if ($(e.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 env() {
                return PDJS.Shared.Environment.current;
            }
            onActivate(e) {
                super.onActivate(e);
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: "Create New"
                }));
                this.env.userMenu.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,
                                promptToOpen: true
                            });
                        }
                    }));
                });
            }
        }
        Hub.CreatePanel = CreatePanel;
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        class GlobalSearch extends Hub.ApplicationBarItem {
            template() {
                return `<div style="box-sizing:border-box;"></div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                let searchBox = new PDJS.Shared.UI.Controls.MaskedTextBox({
                    defaultMaskText: "Search...",
                    onMaskFocus: (e) => {
                        searchBox.showText();
                        searchBox.focusText();
                    },
                    onTextFocus: (e) => {
                        searchBox.focusText();
                    },
                    onTextBlur: (e) => {
                        if (Jade.String.isNullOrWhiteSpace(searchBox.textValue)) {
                            searchBox.showMask();
                        }
                    },
                    onTextKeyPress: (e) => {
                        let isSearchCommand = e.keyCode == Jade.KeyCode.Enter;
                        if (!isSearchCommand || Jade.String.isNullOrWhiteSpace(searchBox.textValue)) {
                            return;
                        }
                        let isValidSearch = searchBox.textValue.length > 1;
                        if (isValidSearch) {
                            window.location.href = Jade.Path.resolve(`~/hub/search?searchTerm=${searchBox.textValue}`);
                        }
                    }
                });
                this.controls.add(searchBox);
                searchBox.node.css({
                    top: "8px",
                    left: "10px",
                    right: "10px"
                });
                searchBox.textAndMaskNode.css({
                    borderColor: this.backgroundColor
                });
                searchBox.maskNode.css({
                    backgroundImage: `url(${Jade.IconSet.get("pd").resolve("ICON_SEARCH_16X16.GIF", Jade.IconSetSizeSpecificDirectory.misc)}`,
                    backgroundPosition: "right 5px center",
                    backgroundRepeat: "no-repeat"
                });
                this.node.css({
                    padding: "10px",
                    backgroundColor: this.backgroundColor
                });
            }
        }
        Hub.GlobalSearch = GlobalSearch;
    })(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.Shared.Environment.current;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.css({
                    top: `${this.top}px`
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: this.env.user.displayName
                }));
                this.addRecentEntities();
                this.addRecentViews();
                this.addPersonalization();
                this.addAdministration();
                this.addHelp();
                this.addLogout();
            }
            addRecentEntities() {
                if (this.env.userMenu.recentEntities.length == 0) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Recent"
                }));
                this.env.userMenu.recentEntities.forEach((entry) => {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        label: entry.name,
                        description: entry.description,
                        url: Jade.Path.resolve("~/explore/" + entry.id)
                    }));
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addRecentViews() {
                if (this.env.userMenu.recentViews.length == 0) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Recent Views"
                }));
                this.env.userMenu.recentViews.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: "Favorites",
                    url: Jade.Path.resolve("~/Hub/Personalization/Favorites")
                }));
                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"
                            },
                            callbacks: {
                                "ok": (sender, e) => {
                                }
                            }
                        });
                        this.hide();
                    }
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addAdministration() {
                if (!this.env.user.isAdmin) {
                    return;
                }
                let target = `${PDJS.Application.instance.id}-manage`;
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Administration"
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Users",
                    url: Jade.Path.resolve("~/Manage/#/module/users"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Groups",
                    url: Jade.Path.resolve("~/Manage/#/module/groups"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Entity Management",
                    url: Jade.Path.resolve("~/Manage/#/module/entity-management"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Entity Types",
                    url: Jade.Path.resolve("~/Manage/#/module/entity-types"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Property Extensions",
                    url: Jade.Path.resolve("~/Manage/#/module/data-model/properties"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "More...",
                    url: Jade.Path.resolve("~/Manage/#/module/overview"),
                    target: target
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
            }
            addHelp() {
                if (Jade.String.isNullOrWhiteSpace(this.env.userMenu.supportUrl)) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Help",
                    url: Jade.Path.resolve(this.env.userMenu.supportUrl),
                    largeText: true
                }));
            }
            addLogout() {
                if (!this.env.isLocalAuthMode) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Sign Out",
                    url: Jade.Path.resolve("~/Shared/Account/Logout"),
                    largeText: true
                }));
            }
        }
        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 env() {
                return PDJS.Shared.Environment.current;
            }
            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.env.userMenu.views.length < 0) {
                    return;
                }
                this.env.userMenu.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) {
        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["ReloadExplorer"] = "ReloadExplorer";
                Events["FilesMoved"] = "FilesMoved";
            })(Events = Explorer.Events || (Explorer.Events = {}));
        })(Explorer = Hub.Explorer || (Hub.Explorer = {}));
    })(Hub = PDJS.Hub || (PDJS.Hub = {}));
})(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;
            }
        }
        Shared.EventsHubBase = EventsHubBase;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class EventsHub extends PDJS.Shared.EventsHubBase {
                static contentLoadedPublish(args) {
                    this.global.publish(Explorer.Events.ContentLoaded, args);
                }
                static contentRequestedPublish(args) {
                    this.global.publish(Explorer.Events.ContentRequested, args);
                }
                static reloadExplorerPublish(args = {}) {
                    this.global.publish(Explorer.Events.ReloadExplorer, args);
                }
                static contentLoadedSubscribe(handler) {
                    return this.global.subscribe(Explorer.Events.ContentLoaded, handler);
                }
                static contentRequestedSubscribe(handler) {
                    return this.global.subscribe(Explorer.Events.ContentRequested, handler);
                }
                static reloadExplorerSubscribe(handler) {
                    return this.global.subscribe(Explorer.Events.ReloadExplorer, 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.load({
                            entityId: e.entityId,
                            folderId: e.folderId,
                            record: e.record
                        });
                    });
                }
                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();
                            let page = this.m_formTypeMap[e.data.formTypeId];
                            if (page != null) {
                                let contentPage = new page({
                                    data: e.data
                                });
                                this.controls.add(contentPage);
                                if (args.record) {
                                    Explorer.Navigator.recordHistory(args);
                                }
                                Explorer.EventsHub.contentLoadedPublish({
                                    entityId: args.entityId,
                                    folderId: args.folderId,
                                    isHistory: !args.record
                                });
                            }
                        },
                        error: (e) => {
                            if (_.first(e.xhr.responseJSON).code == 4) {
                                e.errorHandled = true;
                                this.controls.clear();
                                this.controls.add(new PDJS.Shared.UI.Controls.Message({
                                    message: "This form type is deprecated. Contact your system administrator."
                                }));
                            }
                        }
                    });
                }
            }
            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 {
                constructor() {
                    let contextId = Jade.Guid.new();
                    Jade.Application.instance.contexts.createContext({
                        id: contextId,
                        name: "explorer"
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("canvas/form/changed", function (e) {
                        PDJS.JS
                            .ProspectDirector
                            .RUNTIME
                            .MODULES
                            .Navigator
                            .canvasFormChanged = {
                            contextId: contextId,
                            formId: e.formId
                        };
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("canvas/form/reset", function (e) {
                        PDJS.JS
                            .ProspectDirector
                            .RUNTIME
                            .MODULES
                            .Navigator
                            .canvasFormChanged = null;
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("canvas/destroyed", function (e) {
                        PDJS.JS
                            .ProspectDirector
                            .RUNTIME
                            .MODULES
                            .Navigator
                            .canvasFormChanged = null;
                    });
                }
                unload() {
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish("Explorer:Content:Unload");
                }
            }
            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();
                }
                tree_init() {
                    this.m_tree = new Explorer.ExplorerTree({
                        insertAt: "div[role=tree]",
                        entityId: this.entityId,
                        folderId: this.folderId
                    });
                    this.controls.add(this.m_tree);
                }
            }
            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
                    });
                }
                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;
        })(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) {
                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"
                            });
                        }
                    }
                    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);
                                }
                                _.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
                        });
                    }
                    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({
                            change: _.bind(this.tree_change, this),
                            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 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");
                }
                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);
                    Explorer.EventsHub.contentLoadedSubscribe((e) => {
                        if (e.isHistory) {
                            this.select(e.folderId);
                        }
                    });
                }
                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 Hub;
    (function (Hub) {
        var Explorer;
        (function (Explorer) {
            class Navigator {
                static get internal() {
                    this.ensureNavigator();
                    return this.m_internal;
                }
                static navigate(e) {
                    this.internal.go({
                        directive: () => {
                            Explorer.EventsHub.contentRequestedPublish({
                                entityId: e.entityId,
                                folderId: e.folderId,
                                record: e.record
                            });
                        },
                        error: e.reject
                    });
                }
                static recordHistory(e) {
                }
                static reloadHistory(entityId, folderId) {
                    if (entityId != null && folderId != null) {
                        this.navigate({
                            entityId: entityId,
                            folderId: folderId,
                            record: false
                        });
                    }
                }
                static ensureNavigator() {
                    if (this.m_internal == null) {
                        this.m_internal = new PDJS.Shared.Navigate.Navigator({
                            captureAnchorNavigation: true
                        });
                    }
                }
                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 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);
                    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 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 allowDeleteListItem() {
                    return this.getProperty("allowDeleteListItem");
                }
                get allowDeleteFile() {
                    return this.getProperty("allowDeleteFiles");
                }
                get allowCreateEntity() {
                    return this.getProperty("allowCreateEntity");
                }
                get tabs() {
                    return this.state.get("data.tabs", []);
                }
                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");
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .clear();
                }
                addHead() {
                    let m_head = new Explorer.ContentPageHeader({
                        insertAt: `.${this.headNodeClass}`,
                        entityName: this.entityName,
                        folderIcon: this.folderIcon,
                        folderName: this.folderName
                    });
                    this.controls.add(m_head);
                }
                addTabs() {
                    if (this.tabs.length == 0) {
                        return;
                    }
                    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
                        };
                    });
                    ;
                    let m_tabs = new PDJS.Shared.UI.Controls.TabStrip({
                        insertAt: `.${this.tabsNodeClass}`,
                        tabs: tabs,
                        binding: {
                            value: "folderId",
                            icon: "icon",
                            text: "text"
                        },
                        tabClick: item => {
                            let tab = item.state.toJSON();
                            Explorer.Navigator.navigate({
                                entityId: tab.entityId,
                                folderId: tab.folderId,
                                record: true,
                                reject: () => {
                                }
                            });
                        }
                    });
                    this.controls.add(m_tabs);
                }
                getProperty(id) {
                    return this.state.get(`data.properties.${id}`);
                }
            }
            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) {
            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;
                        });
                    }
                }
                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.DeleteCommand({}));
                        e.commands.add(new ContentList.ReportsCommand({}));
                        e.commands.add(new ContentList.AddToFavortiesCommand({}));
                    }
                }
                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) {
                let ContentListPageEvent;
                (function (ContentListPageEvent) {
                    ContentListPageEvent["onGridRefreshRequest"] = "grid/refresh-request";
                })(ContentListPageEvent = ContentList.ContentListPageEvent || (ContentList.ContentListPageEvent = {}));
                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();
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .subscribe(ContentListPageEvent.onGridRefreshRequest, (e) => {
                            this.m_grid.refresh(e || {});
                            this.setCommandState();
                        });
                        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,
                                            type: item.ObjectType
                                        };
                                    });
                                }
                            },
                            change: (e) => {
                                this.setCommandState();
                            },
                            dblclick: (e) => {
                                let commandId = "explorer/content-list:entity/properties";
                                if (this.doubleClickMode === 0) {
                                    if (PDJS.Shared.Environment.current.preferences.contentListDoubleClickBehavior === 1) {
                                        commandId = "explorer/content-list:entity/open-in-new-window";
                                    }
                                    else {
                                        commandId = "explorer/content-list:entity/open";
                                    }
                                }
                                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 });
                    }
                }
                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/open"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/open-in-new-window"
                        }));
                        e.addSeparator();
                        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/reports"
                        }));
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/add-to-favorites"
                        }));
                        e.addSeparator();
                        e.addItem(new Jade.UI.ContextMenuItemCommand({
                            commandId: "explorer/content-list:entity/properties"
                        }));
                    }
                }
                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 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 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/open"
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: "explorer/content-list:entity/open-in-new-window"
                        }));
                        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/delete"
                        }));
                    }
                }
                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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Send to Recycle Bin",
                            message: `Send the selected items to the Recycle Bin?`,
                            select: (e) => {
                                e.close();
                                if (e.button === Jade.UI.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() {
                        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) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .parent
                                    .events
                                    .publish(ContentList.ContentListPageEvent.onGridRefreshRequest, {
                                    clear: true
                                });
                                e.close();
                            }
                        });
                    }
                }
                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 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: "white-no-padding",
                                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,
                            promptToOpen: this.promptAfterCreate,
                            onCreate: (sender, e) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .parent
                                    .events
                                    .publish(ContentList.ContentListPageEvent.onGridRefreshRequest, {
                                    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: () => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(ContentList.ContentListPageEvent.onGridRefreshRequest);
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "entity/properties",
                            tooltip: "Properties",
                            label: "Properties",
                            icon: "preferences.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.type
                            }
                        });
                    }
                    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 entityName() {
                    return this.state.get("entityName");
                }
                get folderIcon() {
                    return this.state.get("folderIcon");
                }
                get folderName() {
                    return this.state.get("folderName");
                }
                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>
                        Viewing: ${this.entityName}
                    </span>
                </div>
            </div>
            `;
                }
            }
            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 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,
                            allowDeleteListItem: null,
                            allowEdit: null,
                            extensionId: null,
                            documentId: null,
                            items: null
                        });
                    }
                    get allowDeleteListItem() {
                        return this.state.get("allowDeleteListItem");
                    }
                    get allowEdit() {
                        return this.state.get("allowEdit");
                    }
                    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.Dialog {
                    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) {
                        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.setTitle("Duplicate | List Item");
                                break;
                            case this.rowIds.length > 1:
                                this.setTitle("Batch Edit | List Items");
                                break;
                            case this.rowIds.length == 1:
                                this.setTitle("Edit | List Item");
                                break;
                            case this.rowIds.length == 0:
                                this.setTitle("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 `<div class="${CanvasJS.Actual.CanvasCss.Element}">
                <div data-controls style="position:absolute;top:0;bottom:46px;right:0;left: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;border:0px solid #AAAAAA;border-top-width:1px;">
                    <button data-role="ok-button" class="-jadejs-button">OK</button>
                    <button data-role="cancel-button" class="-jadejs-button">Cancel</button>
                </div>
            </div>`;
                    }
                    getWindowOptions() {
                        return {
                            maximized: false,
                            height: 500,
                            width: 680
                        };
                    }
                    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.MultiMessageDialog.open({
                                        dialogStyle: Jade.UI.MessageDialogStyle.Error,
                                        dialogButtons: Jade.UI.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.MultiMessageDialog.open({
                                        dialogStyle: Jade.UI.MessageDialogStyle.Success,
                                        dialogButtons: Jade.UI.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({
                                                command: "ok",
                                                data: {
                                                    rowId: e.rowId
                                                }
                                            });
                                        }
                                    });
                                default:
                                    PDJS.Canvas.Actual.Forms.FormFieldAnimation.start(null, 1500, PDJS.Canvas.Actual.Forms.FormFieldAnimationType.success);
                                    this.close({
                                        command: "ok",
                                        data: {
                                            rowId: e.rowId
                                        }
                                    });
                                    break;
                            }
                        }, 500);
                    }
                    itemRequestError(e) {
                        PDJS.Canvas.Actual.Forms.FormFieldAnimation.stop(null);
                        this.okButton.prop("disabled", false);
                    }
                    static open(options, callback) {
                        let result = new DesignableListDialog(options);
                        if (_.isFunction(callback)) {
                            callback();
                        }
                        return result;
                    }
                }
                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);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.menu_init();
                        this.grid_init();
                        Jade.Application
                            .instance
                            .contexts
                            .current
                            .events
                            .subscribe(DeisgnableListPageEvent.onListItemRefreshRequest, (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;border:1px solid #CCCCCC;"></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: "[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": {
                                allowEdit: this.allowEdit,
                                allowDeleteListItem: this.allowDeleteListItem,
                                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) {
                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.items,
                            isCopy: true,
                            callbacks: {
                                ok: (sender, e) => {
                                    let rowId = e.rowId;
                                    setTimeout(() => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(DesignableList.DeisgnableListPageEvent.onListItemRefreshRequest, {
                                            clear: true,
                                            selections: [rowId]
                                        });
                                    }, 100);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/copy",
                            tooltip: "Duplicate",
                            label: "Duplicate",
                            icon: "copy.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.items.length == 1 && this.allowEdit;
                    }
                }
                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,
                            callbacks: {
                                ok: (sender, e) => {
                                    let rowId = e.rowId;
                                    setTimeout(() => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(DesignableList.DeisgnableListPageEvent.onListItemRefreshRequest, {
                                            clear: true,
                                            selections: [rowId]
                                        });
                                    }, 250);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/create",
                            tooltip: "New",
                            label: "New",
                            icon: "add.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.allowEdit;
                    }
                }
                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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete List Items",
                            message: "Delete the selected list items?",
                            select: (e) => {
                                e.close();
                                if (e.button === Jade.UI.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.allowDeleteListItem;
                    }
                    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) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(DesignableList.DeisgnableListPageEvent.onListItemRefreshRequest, {
                                    clear: true
                                });
                                e.close();
                            }
                        });
                    }
                }
                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) {
                        PDJS.Hub.Explorer.DesignableList.DesignableListDialog.open({
                            documentId: this.documentId,
                            entityId: this.entityId,
                            extensionId: this.extensionId,
                            folderId: this.folderId,
                            rowIds: this.itemIds,
                            isCopy: false,
                            callbacks: {
                                ok: (sender, e) => {
                                    setTimeout(() => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(DesignableList.DeisgnableListPageEvent.onListItemRefreshRequest);
                                    }, 100);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "list-item/edit",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    onStateChanged(e) {
                        this.enabled = this.items.length > 0 && this.allowEdit;
                    }
                }
                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();
                        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;border:1px solid #CCCCCC;"></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]}`
                            });
                        }
                        if (this.items.length > 1) {
                            this.downloadMultipleFiles();
                        }
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/download",
                            tooltip: "Download",
                            label: "Download",
                            icon: "download.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    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.Shared.Files.EditFiles.showProperties({
                            entityId: _.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();
                        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;border:1px solid #CCCCCC;"></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,
                            callbacks: {
                                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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            allowClose: true,
                            title: "Delete Files",
                            message: "Delete the selected files?",
                            select: (e) => {
                                e.close();
                                if (e.button === Jade.UI.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: "download.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    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),
                            callbacks: {}
                        });
                    }
                    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.Shared.Files.EditFiles.showProperties({
                            entityId: 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,
                            callbacks: {
                                ok: (sender, e) => {
                                    setTimeout(() => {
                                        this.showSuccessMessage(file);
                                    }, 100);
                                    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"
                        };
                    }
                    showSuccessMessage(file) {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Success,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            allowClose: true,
                            title: "Success",
                            message: `The file "${file.name}${file.extension}" has been replaced successfully.`,
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                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,
                            callbacks: {
                                ok: (sender, e) => {
                                    Explorer.EventsHub.reloadExplorerPublish();
                                    setTimeout(() => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest);
                                    }, 100);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "file/upload",
                            tooltip: "Upload",
                            label: "Upload",
                            icon: "upload.png",
                            enabled: false,
                            display: "icon label",
                            iconSetId: "pd"
                        };
                    }
                    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({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPE_ASSIGNMENT,
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            callbacks: {
                                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 {
                            Tipped.remove(this.iconNode);
                        }
                    }
                    editButton_onClick(e) {
                        FileFolder.FileFormDialog.open({
                            canvasDocument: this.source.canvasDocument,
                            lastCommitResponse: this.source.lastCommitResponse,
                            fileId: this.source.id,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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({
                            viewCustomId: PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPE_ASSIGNMENT,
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            callbacks: {
                                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)) {
                            Tipped.create(this.iconNode, message, {
                                skin: "validation-error",
                                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 IChangeDocumentTypeDialogOptions {
                }
                FileFolder.IChangeDocumentTypeDialogOptions = IChangeDocumentTypeDialogOptions;
                class ChangeDocumentTypeDialog extends Jade.UI.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 `
                <div style="position:absolute;top:10px;right:10px;bottom:10px;left:10px;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="-jadejs-button">Save</button>
                        <button data-command="cancel" class="-jadejs-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);
                    }
                    getWindowOptions() {
                        return {
                            title: "Change Document Type",
                            height: 450,
                            width: 700
                        };
                    }
                    toolbar_init() {
                        this.m_toolbar = new Jade.UI.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: "#1fee1c",
                            color: "#000000",
                            message: "Pending save.",
                            height: "22px"
                        });
                        this.controls.add(this.m_progressbar);
                    }
                    okButton_onClick(e) {
                        let files = this.fileContainer.files;
                        this.okButtonNode.prop("disabled", false);
                        let fileIndex = 0;
                        let uploadFileFn = () => {
                            if (files.count > fileIndex) {
                                let file = files.item(fileIndex);
                                file.source.commit(this.entityId, this.folderId, () => {
                                    fileIndex += 1;
                                    setTimeout(() => {
                                        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();
                                        }
                                        uploadFileFn();
                                    }, 100);
                                });
                            }
                        };
                        uploadFileFn();
                    }
                    setButtonState() {
                        this.okButtonNode.prop("disabled", !(this.fileContainer.noFilesPending && this.fileContainer.noFilesWithErrors));
                    }
                    checkAllFilesCommittedAndClose() {
                        if (this.fileContainer.allFilesCommited) {
                            this.close({
                                command: "ok",
                                data: []
                            });
                        }
                    }
                    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.MultiMessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/remove-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/select-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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.Dialog {
                    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 `<div style="position:absolute;top:0;right:0;bottom:10px;left:0;">
                         <div data-role="content" data-controls style="position:absolute;top:0;left:0;right:0;bottom:36px;overflow:auto;"></div>
                         <div data-role="deck" style="height:26px;position:absolute;left:0;right:0;bottom:0;text-align:right;padding-right:10px;padding-left:10px;">
                            <button data-command="ok" class="-jadejs-button">OK</button>
                            <button data-command="cancel" class="-jadejs-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);
                    }
                    getWindowOptions() {
                        return {
                            title: "Edit File",
                            height: 450,
                            width: 680
                        };
                    }
                    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({
                                        command: "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.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 `<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="-jadejs-button">OK</button>
                            <button data-command="cancel" class="-jadejs-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();
                    }
                    getWindowOptions() {
                        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",
                            taskStart: (e) => {
                                service.moveFiles({
                                    fileIds: this.fileIds,
                                    folderId: this.folderId,
                                    success: (e2) => {
                                        e.startPolling(e2.data);
                                    },
                                    error: (e2) => {
                                        e.abort(e2);
                                    }
                                });
                            },
                            taskSuccess: (e) => {
                                PDJS.Application
                                    .instance
                                    .contexts
                                    .current
                                    .parent
                                    .events
                                    .publish(FileFolder.FileFolderPageEvent.onGridRefreshRequest, {
                                    clear: true
                                });
                                Explorer.EventsHub.reloadExplorerPublish();
                                e.close();
                            }
                        });
                    }
                    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.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 `<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="-jadejs-button">OK</button>
                            <button data-command="cancel" class="-jadejs-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();
                    }
                    getWindowOptions() {
                        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,
                            uploadName: this.uploadName,
                            uploadId: this.uploadId,
                            success: (e) => {
                                this.showSuccessDialog();
                                this.close();
                            }
                        });
                    }
                    uploadInput_init() {
                        this.m_uploadInput = new PDJS.Shared.UI.Controls.UploadInput({
                            onUploadStart: (e) => {
                                this.setOkButtonEnabledState(false);
                            },
                            onUploadComplete: (e) => {
                                this.uploadId = e.target_name;
                                this.uploadName = e.name;
                                this.setOkButtonEnabledState(true);
                            }
                        });
                        this.controls.add(this.m_uploadInput);
                    }
                    setOkButtonEnabledState(enabled) {
                        this.okButtonNode.prop("disabled", !enabled);
                    }
                    showSuccessDialog() {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Success,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            allowClose: true,
                            title: "File Replaced",
                            message: `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.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] a: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 `
                <div style="position:absolute;top:10px;right:10px;bottom:10px;left:10px;overflow:hidden;">
                    <div data-role="toolbar" style="position:absolute;top:0;left:0;right:0;height:30px;"></div>
                    <div data-role="upload" 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="save" class="-jadejs-button">Save</button>
                            <button data-command="upload" class="-jadejs-button">Upload</button>
                            <button data-command="cancel" class="-jadejs-button">Cancel</button>
                        </div>
                    </div>
                </div>
            `;
                    }
                    getWindowOptions() {
                        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.MessageDialog.open({
                                    dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                    dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                    allowClose: true,
                                    message: e.message,
                                    select: (e) => {
                                        e.close();
                                    }
                                });
                            }
                        });
                        this.controls.add(this.upload);
                        this.updateCommandState();
                    }
                    toolbar_init() {
                        this.m_toolbar = new Jade.UI.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: "#1fee1c",
                            color: "#000000",
                            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 fileIndex = 0;
                        let uploadFileFn = () => {
                            if (this.upload.files.count > fileIndex) {
                                let file = this.upload.files.item(fileIndex);
                                file.source.commit(this.entityId, this.folderId, () => {
                                    fileIndex += 1;
                                    setTimeout(() => {
                                        this.m_progressbar.update({
                                            message: `Saving file "${file.source.name}${file.source.extension}"...`,
                                            percent: 100 * (fileIndex / this.upload.files.count)
                                        });
                                        if (fileIndex == this.upload.files.count) {
                                            this.onFileChange(file);
                                            this.updateProgressBarDisplay();
                                        }
                                        uploadFileFn();
                                    }, 100);
                                });
                            }
                        };
                        uploadFileFn();
                    }
                    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({
                                    command: "ok",
                                    data: []
                                });
                            }
                        }
                    }
                    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.MultiMessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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 Jade.UI.ToolBarSegment {
                    onAddItems(e) {
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/add-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/remove-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/clear-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            commandId: "explorer/file-upload:upload/select-files"
                        }));
                        e.registerItem(new Jade.UI.ToolBarButtonCommand({
                            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();
                            file.node.addClass("-pdjs-upload-in-progress");
                        }
                        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;
                            file.node.removeClass("-pdjs-upload-in-progress");
                        }
                        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) {
                        this.uploader.stop();
                        if (e.file != null) {
                            e.file.status = plupload.FileStatus.FAILED;
                        }
                        this.onErrorCallback({
                            code: e.status === 400 ? 400 : e.code,
                            file: e.file,
                            message: e.message || "Error",
                            response: e.response
                        });
                    }
                    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 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 tabType() {
                    return this.state.get("tabTypes");
                }
                set tabType(value) {
                    this.state.set("tabTypes", value);
                }
                get viewStateId() {
                    return this.state.get("data.viewStateId");
                }
                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;
                    });
                    let tabStrip = new PDJS.Shared.UI.Controls.TabStrip({
                        insertAt: `.${this.tabsNodeClass}`,
                        tabs: tabs,
                        tabClick: this.onTabClick
                    });
                    this.controls.add(tabStrip);
                }
                onTabClick(tab) {
                    switch (tab.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;
                    }
                }
            }
            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 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;
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addHead() {
                        this.m_head =
                            new PDJS.Shared.UI.Controls.ContentPageHeader({
                                insertAt: `.${this.headNodeClass}`,
                                icon: "find.png",
                                title: this.viewName,
                                subTitle: this.viewDescription
                            });
                        this.controls.add(this.m_head);
                    }
                    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,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.id,
                                        name: e.Name,
                                        parentId: e.ObjectParentId,
                                        folderId: e.d0_general_FolderId
                                    };
                                }
                            },
                            change: (e) => {
                                this.updateCommandState();
                            },
                            dblclick: (e) => {
                                let commandId = "views/browser-page:view/open";
                                switch (this.viewType) {
                                    case "Documents":
                                        commandId = "views/browser-page:file/open-location";
                                        break;
                                    case "Entities":
                                        commandId = "views/browser-page:entity/open";
                                        break;
                                }
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute(commandId);
                            },
                            contextMenu: () => {
                                this.contextMenu_init();
                            }
                        });
                        this.updateCommandState();
                    }
                    toolbar_init() {
                        let segments = [];
                        switch (this.viewType) {
                            case "Documents":
                                segments.push(new Browser.BrowserPageFileToolbar());
                                break;
                            case "Entities":
                                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;
                            case "Entities":
                                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
                            }
                        }, { force: true });
                    }
                }
                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,
                            viewId: null,
                            viewStateId: null
                        });
                    }
                    get grid() {
                        return this.state.get("$grid");
                    }
                    get folderId() {
                        return this.state.get("folderId");
                    }
                    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.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: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(e) {
                        this.enabled = this.selectedItems.length == 1;
                    }
                    getDefaultValuesForProps() {
                        let inNew = this.inNewWindow;
                        return {
                            id: "entity/open",
                            tooltip: inNew ? "Open In New Window" : "Open",
                            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(e) {
                        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: "Properties",
                            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(e) {
                        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(e) {
                        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(e) {
                        this.enabled = this.selectedItems.length == 1;
                    }
                    onExecute(e) {
                        PDJS.Shared.Files.EditFiles.showProperties({
                            entityId: _.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(e) {
                        this.enabled = this.selectedItems.length == 1;
                    }
                    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"
                            },
                            callbacks: {
                                ok: (sender, e) => {
                                    PDJS.Application
                                        .instance
                                        .contexts
                                        .global
                                        .events
                                        .publish("PersonalView:Properties:Change", {
                                        name: e.target.name,
                                        description: e.target.description
                                    });
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/properties",
                            tooltip: "Edit",
                            label: "Edit",
                            icon: "pencil.png",
                            enabled: false,
                            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.MessageDialog.open({
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            title: "Revert View",
                            message: "Undo all your changes and revert the view back to its original configuration?",
                            select: (e) => {
                                e.close();
                                this.revertView();
                            }
                        });
                    }
                    onStateChanged(e) {
                        this.enabled = this.selectedItems.length == 1;
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "view/revert",
                            tooltip: "Reset",
                            label: "Reset",
                            icon: "refresh.png",
                            enabled: false,
                            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 {
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.selectedItems.length == 1;
                    }
                    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"
                            },
                            callbacks: {
                                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: false,
                            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 = true;
                    }
                    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: false,
                            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;
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addHead() {
                        let head = new PDJS.Shared.UI.Controls.ContentPageHeader({
                            insertAt: `.${this.headNodeClass}`,
                            icon: "earth_find.png",
                            title: "Global Views",
                            subTitle: "A list of global views that have been published to the user community."
                        });
                        this.controls.add(head);
                    }
                    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 });
                    }
                }
                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"
                            },
                            callbacks: {
                                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;
                    }
                    onBrowserResize() {
                        this.m_grid.get_kendo().resize();
                    }
                    addHead() {
                        let head = new PDJS.Shared.UI.Controls.ContentPageHeader({
                            insertAt: `.${this.headNodeClass}`,
                            icon: "user_find.png",
                            title: "Personal Views",
                            subTitle: "A list of global views which you have customized and saved for reference."
                        });
                        this.controls.add(head);
                    }
                    addTabs() {
                        this.tabType = Views.TabTypes.personal;
                        super.addTabs();
                    }
                    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) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .commands
                                    .execute("views/personal-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 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 });
                    }
                }
                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; }),
                            callbacks: {
                                ok: () => {
                                    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.MessageDialog.open({
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            title: "Delete Views",
                            message: message,
                            select: (e) => {
                                if (e.button == Jade.UI.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"
                            },
                            callbacks: {
                                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"
                            },
                            callbacks: {
                                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.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) {
                        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 `<div class="${CanvasJS.Actual.CanvasCss.Element}">
                <div data-controls style="position:absolute;top:10px;bottom:46px;right:10px;left:10px;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="-jadejs-button">OK</button>
                    <button data-role="cancel-button" class="-jadejs-button">Cancel</button>
                </div>
            </div>`;
                    }
                    getWindowOptions() {
                        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({
                                    command: "ok"
                                });
                            },
                            error: (e) => {
                                let booya = "what?";
                            }
                        });
                    }
                    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["Module"] = "-pdjs-manage-module";
            CssClass["ModuleSectionTitle"] = "-pdjs-manage-module-section-title";
        })(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 ApplicationBar extends Jade.UI.Control {
            get env() {
                return PDJS.Shared.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-fwk-app-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: "rgba(0, 0, 0, .4)",
                    icon: Jade.IconSet.get("pdjs").resolve("grid-blocks.png", Jade.IconSetSizeSpecificDirectory.misc),
                    url: "#/module/overview"
                }));
                this.titleNode.css({
                    color: this.env.theme.textColor
                });
                this.node.css({
                    backgroundColor: this.env.theme.backgroundColor
                });
                this.titleNode.text(`${this.env.applicationName} - Management`);
                this.controls.add(new Manage.ApplicationBarItem({
                    icon: "~/application/icons/misc/24x24/home.png",
                    url: Jade.Path.resolve("~/Hub/Home"),
                    target: "_blank"
                }));
                this.controls.add(new Manage.DocumentationSearch({
                    width: 200,
                    backgroundColor: "rgba(255, 255, 255, .4)"
                }));
                this.controls.add(new Manage.ApplicationBarItem({
                    insertAt: "div[role=dock-r]",
                    backgroundColor: "rgba(0, 0, 0, .4)",
                    icon: "~/application/icons/misc/24x24/user.png",
                    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 icon() {
                return this.state.get("icon");
            }
            get url() {
                return this.state.get("url", "#");
            }
            get width() {
                return this.state.get("width", 40);
            }
            get backgroundColor() {
                return this.state.get("backgroundColor", null);
            }
            get onClickCallback() {
                return this.state.get("onClick", () => { });
            }
            get target() {
                return this.state.get("target");
            }
            template() {
                if (this.url == null) {
                    return `<div><div>`;
                }
                else {
                    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`,
                    backgroundColor: this.backgroundColor == null ? "" : this.backgroundColor,
                    backgroundPosition: "center center",
                    backgroundRepeat: "no-repeat"
                });
                if (this.icon != null) {
                    this.node.css({
                        backgroundImage: `url(${icon})`
                    });
                }
                if (this.url != null && this.url != "#") {
                    let url = Jade.Path.resolve(this.url);
                    this.node.attr("href", url);
                }
                else if (this.onClickCallback != null) {
                    this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                        e.stopImmediatePropagation();
                        this.onClickCallback(e);
                    });
                }
                if (this.target != null) {
                    this.node.attr("target", this.target);
                }
            }
        }
        Manage.ApplicationBarItem = ApplicationBarItem;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        class DocumentationSearch extends Manage.ApplicationBarItem {
            template() {
                return `<div style="box-sizing:border-box;"></div>`;
            }
            onActivate(e) {
                super.onActivate(e);
                let searchBox = new PDJS.Shared.UI.Controls.MaskedTextBox({
                    defaultMaskText: "Search Docs...",
                    onMaskFocus: (e) => {
                        searchBox.showText();
                        searchBox.focusText();
                    },
                    onTextFocus: (e) => {
                        searchBox.focusText();
                    },
                    onTextBlur: (e) => {
                        if (Jade.String.isNullOrWhiteSpace(searchBox.textValue)) {
                            searchBox.showMask();
                        }
                    },
                    onTextKeyPress: (e) => {
                        let isSearchCommand = e.keyCode == Jade.KeyCode.Enter;
                        if (!isSearchCommand || Jade.String.isNullOrWhiteSpace(searchBox.textValue)) {
                            return;
                        }
                        let isValidSearch = searchBox.textValue.length > 1;
                        if (isValidSearch) {
                            window.open(Jade.Path.resolve(`https://docs.3-gig.com/docs/search?term=${searchBox.textValue}`));
                            searchBox.textValue = "";
                            searchBox.showMask();
                        }
                    }
                });
                this.controls.add(searchBox);
                searchBox.node.css({
                    top: "8px",
                    left: "10px",
                    right: "10px"
                });
                searchBox.textAndMaskNode.css({
                    borderColor: this.backgroundColor
                });
                searchBox.maskNode.css({
                    backgroundImage: `url(${Jade.IconSet.get("pd").resolve("ICON_SEARCH_16X16.GIF", Jade.IconSetSizeSpecificDirectory.misc)}`,
                    backgroundPosition: "right 5px center",
                    backgroundRepeat: "no-repeat"
                });
                this.node.css({
                    padding: "10px",
                    backgroundColor: this.backgroundColor
                });
            }
        }
        Manage.DocumentationSearch = DocumentationSearch;
    })(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.Shared.Environment.current;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.css({
                    top: `${this.top}px`
                });
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuTitle({
                    label: this.env.user.displayName
                }));
                this.addPersonalization();
                this.addRecentModules();
                this.addHelp();
                this.addLogout();
            }
            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"),
                    target: "_blank"
                }));
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Favorites",
                    url: Jade.Path.resolve("~/Hub/Personalization/Favorites"),
                    target: "_blank"
                }));
                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"
                            },
                            callbacks: {
                                "ok": (sender, e) => {
                                }
                            }
                        });
                        this.hide();
                    }
                }));
            }
            addRecentModules() {
                if (this.env.userMenu.recentViews.length == 0) {
                    return;
                }
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                    label: "Recent Views"
                }));
                this.env.userMenu.recentViews.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());
            }
            addHelp() {
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuSeperator());
                this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                    label: "Help",
                    url: "https://docs.3-gig.com",
                    largeText: true,
                    target: "_blank"
                }));
            }
            addLogout() {
                if (!this.env.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
                }));
            }
        }
        Manage.UserPanel = UserPanel;
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Actions;
        (function (Actions) {
            class ActionDialog extends Jade.UI.Dialog {
                constructor(options, windowOptions) {
                    super(options, windowOptions);
                }
                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 `<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.editor_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);
                        if (this.originalAction.id) {
                            this.m_editor.load({
                                plugin: PDJS.Shared.Plugins.PluginManager.instance.getPlugin(this.originalAction.pluginId),
                                action: this.originalAction
                            });
                        }
                    }
                }
                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.ActionPlugins({
                        insertAt: "div[data-role=pane1]",
                        change: (e) => {
                            if (e != null) {
                                this.m_editor.load({
                                    plugin: e,
                                    action: this.originalAction
                                });
                            }
                        }
                    });
                    this.controls.add(this.m_plugins);
                }
                editor_init() {
                    this.m_editor = new Actions.ActionEditor({
                        insertAt: "div[data-role=pane2]"
                    });
                    this.controls.add(this.m_editor);
                }
                okButton_onClick() {
                    this.m_editor.save({
                        commitSuccess: (e) => {
                            this.close({
                                command: "ok",
                                data: e
                            });
                        }
                    });
                }
                cancelButton_onClick() {
                    this.close();
                }
                static open(options, windowOptions) {
                    return new ActionDialog(options, windowOptions);
                }
            }
            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 {
                get plugin() {
                    return this.state.get("plugin");
                }
                set plugin(value) {
                    this.state.set("plugin", value);
                }
                get originalAction() {
                    return this.state.set("originalAction", {});
                }
                set originalAction(value) {
                    this.state.set("originalAction", value);
                }
                load(args) {
                    var _a;
                    this.showEditor(false);
                    this.plugin = args.plugin;
                    this.action_init(args.plugin.id);
                    this.originalAction = args.action;
                    this.m_action.selection = this.getActionsListItems((_a = args.plugin) === null || _a === void 0 ? void 0 : _a.id).find(item => {
                        var _a;
                        return item.id == ((_a = this.originalAction) === null || _a === void 0 ? void 0 : _a.id);
                    });
                }
                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 role="action"></select></div>
                        <div role="editor"></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                }
                editor_init() {
                    this.m_editor = new PDJS.Shared.Features.FeatureEditor({
                        insertAt: "div[role=editor]",
                        layoutType: FeatureBlendJS.Views.FeatureBlendLayoutType.Simple
                    });
                    this.controls.add(this.m_editor);
                }
                action_init(pluginId) {
                    if (this.m_action != null) {
                        this.controls.remove(this.m_action);
                    }
                    this.m_action = new PDJS.Shared.UI.Controls.SingleSelectList({
                        insertAt: "div[role=action]",
                        defaultMask: "Select an action...",
                        data: this.getActionsListItems(pluginId),
                        onCreateListItem: (e) => {
                            return new Actions.ActionListItem({
                                data: e,
                                uidMap: "id",
                                labelMap: "name"
                            });
                        },
                        onSelectionChanged: (selection) => {
                            if (selection == null) {
                                this.showMessage(true);
                                this.showEditor(false);
                            }
                            else {
                                this.loadEditor(selection);
                                this.showEditor(true);
                                this.showMessage(false);
                            }
                        }
                    });
                    this.controls.add(this.m_action);
                }
                getActions(pluginId) {
                    let plugin = PDJS.Shared.Plugins.PluginManager.instance.getPlugin(pluginId);
                    var result = [];
                    if (plugin != null) {
                        result = _.map(plugin.actions.getActionDefinitions(), (action) => {
                            return action.toJSON();
                        });
                    }
                    return result;
                    ;
                }
                getActionsListItems(pluginId) {
                    return _.map(this.getActions(pluginId), action => {
                        return _.extend(action, {
                            label: action.name,
                            icon: "FLASH_YELLOW.png"
                        });
                    });
                }
                showMessage(show) {
                    let message = this.controls.getByType(PDJS.Shared.UI.Controls.Message).first();
                    if (message != null) {
                        this.controls.remove(message);
                    }
                    if (!show) {
                        return;
                    }
                    message = new PDJS.Shared.UI.Controls.Message({
                        insertAt: "div[role=editor]",
                        message: `Select a <b>${this.plugin.name}</b> action to edit above.`
                    });
                    this.controls.add(message);
                    message.node.css({
                        border: "1px solid #CCCCCC"
                    });
                }
                showEditor(show) {
                    if (show) {
                        this.m_editor.node.show();
                    }
                    else {
                        this.m_editor.node.hide();
                    }
                }
                loadEditor(args) {
                    this.m_editor.load({
                        "initialized": false,
                        "arbiter": {
                            json: JSON.stringify(args),
                            type: args.targetArbiter,
                            targetType: args.targetType
                        }
                    });
                }
            }
            Actions.ActionEditor = ActionEditor;
        })(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.SingleSelectListItem {
                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",
                            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 ActionPlugins 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-tree"></div>`;
                }
                select(pluginId) {
                    if (pluginId) {
                        this.selectedPluginId = pluginId;
                        this.m_list.select([pluginId]);
                        this.changeCallback(this.getSelectedPlugin());
                    }
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.loadPlugins();
                    this.list_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                }
                onStateChanged() {
                    this.m_list.select([this.selectedPluginId]);
                }
                list_init() {
                    this.m_list = new PDJS.Shared.UI.Controls.ListView({
                        items: this.getPluginItems(),
                        binding: { value: "id", label: "label", icon: "icon" },
                        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 => {
                        if (plugin.actions.hasActions) {
                            this.m_plugins.push(plugin.toJSON());
                        }
                    });
                    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_closed.png",
                            active: false,
                            selected: false,
                            visible: true
                        });
                    });
                    return data;
                }
                getSelectedPlugin() {
                    return PDJS.Shared.Plugins
                        .PluginManager
                        .instance
                        .getPlugin(this.selectedPluginId);
                }
            }
            Actions.ActionPlugins = ActionPlugins;
        })(Actions = Manage.Actions || (Manage.Actions = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var DataLoad;
        (function (DataLoad) {
            class NewJobDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "New | Job"
                    }), {
                        width: "400px",
                        maximized: false,
                        resizable: false
                    });
                }
                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 `<div class="-pdjs-data-load-new-job-dialog">
                        <div role="header">
                            Data Load Spreadsheet:
                        </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 spreadsheet
                                    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>`;
                }
                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);
                }
                onStateChanged() {
                    super.onStateChanged();
                }
                executeJob() {
                    let service = new PDJS.JS.PD.Manage.Services.DataLoadService();
                    this.enableOkBUtton(true);
                    service.createJob(this.upload.uploadId, this.upload.uploadName, this.validateOnly, (e) => {
                        this.close({
                            taskId: e.taskId
                        });
                        this.showTaskStatusDialog(e);
                    });
                }
                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) {
                    if (!this.validateOnly) {
                        this.showConfirmationDialog(() => {
                            this.executeJob();
                        });
                    }
                    else {
                        this.executeJob();
                    }
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                enableOkBUtton(enabled) {
                    enabled ?
                        this.okButtonNode.removeAttr("disabled") :
                        this.okButtonNode.attr("disabled", "disabled");
                }
                showConfirmationDialog(callback) {
                    Jade.UI.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.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.button === Jade.UI.MessageDialogButton.ok) {
                                callback(e);
                            }
                        }
                    });
                }
                showTaskStatusDialog(e) {
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Data Load Job Progress",
                        enableClose: false,
                        showDetail: true,
                        taskStart: (args) => {
                            args.startPolling(e);
                        },
                        taskSuccess: (e) => {
                            PDJS.JS.PD.context
                                .get_default()
                                .get_events()
                                .publish("jobs/complete", {
                                id: e.output.taskId
                            });
                        }
                    });
                }
                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 Views;
        (function (Views) {
            class RestrictAssignmentToDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(options, {
                        title: "Restrict Assignment To",
                        height: "400px",
                        width: "400px"
                    });
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get clearButtonNode() {
                    return this.node.find("button[data-command=clear]");
                }
                get multiSelectNode() {
                    return this.node.find("[data-role=multi-select]");
                }
                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 `
            <div class="-pdjs-restrict-assignement-to-dialog">
                <div data-role="instructions">
                    Restrict assignment of the document type to only the selected entity types listed below.
                </div>
                <div data-role="multi-select">
                </div>
                <div data-role="button-dock-left">
                    <button data-command="clear" class="-jadejs-button">Clear</button>
                </div>
                <div data-role="button-dock-right">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new RestrictAssignmentToDialog(options);
                }
                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 data-role="multi-select-item" data-id="${item.id}">
                                <input type="checkbox"/>
                                <div data-role="item-content-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({
                        command: "ok",
                        data: selections
                    });
                }
            }
            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",
                        entityTypeIds: this.source.getFeaturePrimaryValue([]),
                        callbacks: {
                            ok: (sender, e) => {
                                this.source.setFeaturePrimaryValue(e);
                                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 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 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 EntityType;
        (function (EntityType) {
            class EntityTypeActions extends PDJS.Shared.UI.Controls.PanelMenu {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                get entityTypeName() {
                    return this.state.get("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}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls></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",
                                entityTypeId: this.entityTypeId,
                                callbacks: {}
                            });
                        }
                    }));
                    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,
                                callbacks: {}
                            });
                        }
                    }));
                    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({
                                callbacks: {
                                    ok: () => { }
                                }
                            });
                        }
                    }));
                    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"
                    }));
                }
            }
            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("$explorer", null);
                    this.state.set("$editor", 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 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": {
                            $explorer: this.explorer,
                            $editor: this.editor,
                            $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({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                onExecute(e) {
                    super.onExecute(e);
                    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
                            }
                        },
                        callbacks: {
                            "ok": (sender, data) => {
                                this.addNodeSuccess(_.extend(data.target, { type: "folder" }));
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/add",
                        tooltip: "New",
                        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);
                }
            }
            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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Explorer Folder",
                        message: message,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.MessageDialogButton.ok) {
                                this.deleteNode();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/delete",
                        tooltip: "Delete",
                        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) {
                    this.editor.commit({
                        success: (e) => {
                            this.updateNode(e.target);
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/save",
                        tooltip: "Save",
                        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);
                }
            }
            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 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({
                        onCommitSuccess: (e) => {
                            PDJS.Shared
                                .MessageStack
                                .instance
                                .success("Changes Saved");
                            PDJS.JS.PD.monitor.getActiveSource().setClean();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                menu_init() {
                    this.m_menu = new Jade.UI.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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Explorer Model</div>
                        <div role="menu"></div>
                        <div 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 Jade.UI.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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/entity-type:node/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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 Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId");
                }
                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.editor_init();
                    this.actions_init();
                    this.explorer_init();
                    this.setCommandState();
                }
                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);
                }
                editor_init() {
                    this.m_editor = new EntityType.EntityTypeEditor({
                        insertAt: "div[data-id=pane-2]",
                        onCommit: (e) => {
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                actions_init() {
                    this.m_actions = new EntityType.EntityTypeActions({
                        insertAt: "div[data-id=pane-3]",
                        entityTypeId: this.entityTypeId
                    });
                    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() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type": {
                            $explorer: this.m_explorer,
                            $editor: this.m_editor,
                            $targetNodeId: null
                        }
                    }, { force: true });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/entity-type/context-menu": {
                            $explorer: this.m_explorer,
                            $editor: this.m_editor,
                            $targetNodeId: null
                        }
                    }, { force: true });
                }
                ensureExplorerModel() {
                    if (!this.m_explorerModel) {
                        this.m_explorerModel = new EntityType.ExplorerModel.ExplorerModel({
                            nodes: [this.state.get("explorerModel")]
                        });
                    }
                }
            }
            EntityType.EntityTypeModule = EntityTypeModule;
        })(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) {
                        PDJS.Canvas.Design.DesignerDialog.open({
                            documentId: this.source.getFeaturePrimaryValue(),
                            canvasType: this.canvasType,
                            documentTypeId: this.documentTypeId,
                            entityTypeId: this.entityTypeId,
                            extensionId: this.extensionId,
                            isFileBased: this.isFileBased,
                            isListBased: this.isListBased,
                            callbacks: {
                                ok: (sender, e) => {
                                }
                            }
                        });
                        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();
                }
                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);
                }
                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 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 ExpressionAssignmentDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(options, {
                        title: "Expression Assigment",
                        height: "450px",
                        width: "800px"
                    });
                }
                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));
                }
                template() {
                    return `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div role="toolbar" style="position:absolute;top:0;left:0;right:0;height:30px;overflow:hidden;"></div>
                <div role="tree" style="position:absolute;top:40px;left:0;right:0;bottom:34px;overflow:hidden;"></div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="close" class="-jadejs-button">Close</button>
                </div>
            </div>
            `;
                }
                onResize() {
                    if (this.m_explorerModel) {
                        this.m_explorerModel.resize();
                    }
                }
                static open(options) {
                    return new ExpressionAssignmentDialog(options);
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.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();
                    }
                }
            }
            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 style="position:absolute;top:0;right:0;bottom:0;left:0;border:1px solid #CCCCCC;">
                        <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();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("expression/assign", _.bind(this.setFolderExpressions, this));
                    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 style="background-image:url(${Jade.IconSet.get("pd").resolve(e.folderIcon, Jade.IconSetSizeSpecificDirectory.x16)});background-position:20px center;background-repeat:no-repeat;padding-left:40px;position:relative;line-height:20px;box-sizing:border-box;height:19px;">
                                        <input role="folder-checkbox" data-folder-id="${e.folderId}" type="checkbox" style="position: absolute;top:5px; left:3px;" ${e.selected ? "checked" : ""}/>
                                        ${e.folderName}
                                    </label>`;
                                }
                            },
                            {
                                field: "expressionName",
                                title: "Expression",
                                template: (e) => {
                                    return `<div style="color:${e.updated ? "blue" : "black"};">${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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "expression-assignment/dialog:expression/assign"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "expression-assignment/dialog:expression/remove"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "expression-assignment/dialog:expression/select-all"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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({
                        callbacks: {
                            ok: (sender, e) => {
                                sender.close();
                                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.Dialog {
                constructor(options) {
                    super(options, {
                        title: "Entity Type Relationships",
                        height: "450px",
                        width: "800px"
                    });
                }
                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();
                    });
                    this.okButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.okButton_onClick, this));
                }
                template() {
                    return `
            <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="-jadejs-button">OK</button>
                    <button data-command="close" class="-jadejs-button">Close</button>
                </div>
            </div>`;
                }
                static open(options) {
                    return new RelationshipsDialog(options);
                }
                okButton_onClick() {
                }
            }
            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 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]");
                    }
                    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">
                            <img src="${Jade.Path.resolve("~/application/icons/misc/cancel.png")}" />
                        </button>
                        <button ${this.source.readOnly ? "disabled" : ""} role="popup" title="Edit">...</button>
                    </div>
                </div>
            </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    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() {
                    }
                    clearButton_onClick() {
                    }
                    input_onBlur() {
                    }
                    showImage(show) {
                        show ? this.imageNode.show()
                            : this.imageNode.hide();
                    }
                    showPopUpButton(show) {
                        show ? this.popupButtonNode.show()
                            : this.popupButtonNode.hide();
                    }
                    showClearButton(show) {
                        show ? this.clearButtonNode.show()
                            : this.clearButtonNode.hide();
                    }
                }
                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) {
                class RelationshipsCommand extends Jade.Command {
                    constructor() {
                        super({});
                        this.state.set("$assignedList", null);
                        this.state.set("$relationshipsMap", null);
                        this.state.set("$typesList", null);
                    }
                    get assignedList() {
                        return this.state.get("$assignedList");
                    }
                    get relationshipsMap() {
                        return this.state.get("$relationshipsMap");
                    }
                    get typesList() {
                        return this.state.get("$typesList");
                    }
                    reloadRelationships() {
                        if (this.typesList.selected == null) {
                            this.assignedList.clear();
                            return;
                        }
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        service.getRelationships({
                            entityTypeId: this.typesList.selected.id,
                            success: (e) => {
                                this.assignedList.load(e.data.children);
                            }
                        });
                    }
                    reloadRelationshipsMap() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let selectedEntityType = this.typesList.selected;
                        service.getRelationshipTree({
                            success: (e) => {
                                this.relationshipsMap.load(e.data);
                                if (selectedEntityType) {
                                    this.relationshipsMap.select(selectedEntityType.id);
                                }
                            }
                        });
                    }
                    updateCommandState() {
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/relationships": {
                                $assignedList: this.assignedList,
                                $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 {
                    execute(value) {
                        super.execute(value);
                        Relationships.AvailableTypesDialog.open({
                            entityTypeId: this.typesList.selected.id,
                            entityTypeName: this.typesList.selected.name,
                            callbacks: {
                                ok: (sender, e) => {
                                    this.commitAdd(e);
                                }
                            }
                        });
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "child/relationship/add",
                            label: "Add",
                            icon: "plus.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pdv2",
                            tooltip: "Add child relationship."
                        };
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                    }
                    commitAdd(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.assignedList.add(items);
                                this.reloadRelationships();
                                this.reloadRelationshipsMap();
                            }
                        });
                    }
                }
                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 {
                    execute(value) {
                        super.execute(value);
                        let message = this.assignedList.selected.length > 1 ?
                            `Remove the selected entity types as children of ${this.typesList.selected.name}.` :
                            `Remove the ${_.first(this.assignedList.selected).name} as children of ${this.typesList.selected.name}.`;
                        Jade.UI.MessageDialog.open({
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            title: "Remove | Relationships",
                            message: message,
                            select: (e) => {
                                if (e.button == Jade.UI.MessageDialogButton.ok) {
                                    this.commitRemove();
                                }
                                e.close();
                            }
                        });
                    }
                    onStateChanged(state) {
                        super.onStateChanged(state);
                        this.enabled = this.assignedList.selected.length > 0;
                    }
                    getDefaultValuesForProps() {
                        return {
                            id: "child/relationship/remove",
                            label: "Remove",
                            icon: "delete.png",
                            enabled: true,
                            display: "icon",
                            iconSetId: "pdv2",
                            tooltip: "Remove child relationship."
                        };
                    }
                    commitRemove() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let item = _.first(this.assignedList.selected);
                        service.deleteRelationship({
                            parentId: this.typesList.selected.id,
                            childId: item.id,
                            success: (e) => {
                                this.assignedList.remove([item.id]);
                                this.reloadRelationships();
                                this.reloadRelationshipsMap();
                            }
                        });
                    }
                }
                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());
                        e.commands.add(new Relationships.RemoveRelationshipCommand());
                    }
                }
                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 Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    set viewStateId(value) {
                        this.state.set("viewStateId", value);
                    }
                    get splitter1Node() {
                        return this.node.children("div[role=splitter-1]");
                    }
                    get splitter2Node() {
                        return this.node.find("div[role=splitter-2]");
                    }
                    get headerNode() {
                        return this.node.find("div[role=children-header]");
                    }
                    get nameNode() {
                        return this.headerNode.find("span[role=name]");
                    }
                    resize() {
                        if (this.m_spliiter1) {
                            this.m_spliiter1.resize();
                        }
                        if (this.m_spliiter2) {
                            this.m_spliiter2.resize();
                        }
                    }
                    template() {
                        return `<div class="${Manage.CssClass.Module} -pdjs-manage-entity-types-relationships">
                        <div role="splitter-1">
                            <div data-id="pane-1"> 
                                <div role="splitter-2">
                                    <div data-id="pane-3"></div>
                                    <div data-id="pane-4">
                                        <div role="children-header">
                                            <div class="-pd-title-minimal">
                                                Children of <span role="name"></span>
                                            </div>
                                            <div role="buttons">
                                                <div role="buttons-wrapper"></div>
                                            </div>
                                        </div>
                                        <div role="children"></div>
                                    </div>
                                </div> 
                            </div>
                            <div data-id="pane-2"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.splitter1_init();
                        this.splitter2_init();
                        this.module_init();
                    }
                    typesList_init() {
                        this.m_typesList = new Relationships.TypesList({
                            insertAt: "div[data-id=pane-3]",
                            viewStateId: this.viewStateId,
                            change: (item) => {
                                if (item == null) {
                                    this.nameNode.text("");
                                    this.setCommandState();
                                    return;
                                }
                                this.nameNode.text(item.name);
                                this.getRelationships(item.id);
                                this.getRelationshipTree();
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_typesList);
                    }
                    assignedList_init() {
                        this.m_assignedList = new Relationships.AssignedList({
                            insertAt: "div[role=children]",
                            change: () => {
                                this.setCommandState();
                            }
                        });
                        this.controls.add(this.m_assignedList);
                    }
                    buttons_init() {
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons-wrapper]",
                            commandId: "pdjs/manage/relationships:child/relationship/add"
                        }));
                        this.controls.add(new PDJS.Shared.UI.Controls.CommandButton({
                            insertAt: "div[role=buttons-wrapper]",
                            commandId: "pdjs/manage/relationships:child/relationship/remove"
                        }));
                    }
                    module_init() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        service.index({
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.assignedList_init();
                                this.relationshipsTree_init();
                                this.typesList_init();
                                this.buttons_init();
                                this.getRelationshipTree();
                                this.setCommandState();
                            }
                        });
                    }
                    relationshipsTree_init() {
                        this.m_relationshipsMap = new Relationships.RelationshipsMap({
                            insertAt: "div[data-id=pane-2]"
                        });
                        this.controls.add(this.m_relationshipsMap);
                    }
                    getRelationships(entityTypeId) {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        service.getRelationships({
                            entityTypeId: entityTypeId,
                            success: (e) => {
                                this.m_assignedList.load(e.data.children);
                            }
                        });
                    }
                    getRelationshipTree() {
                        let service = new PDJS.Services.EntityTypes.RelationshipsService();
                        let selectedEntityType = this.m_typesList.selected;
                        service.getRelationshipTree({
                            success: (e) => {
                                this.m_relationshipsMap.load(e.data);
                                if (selectedEntityType) {
                                    this.m_relationshipsMap.select(selectedEntityType.id);
                                }
                            }
                        });
                    }
                    splitter1_init() {
                        this.m_spliiter1 = this.splitter1Node.kendoSplitter({
                            panes: [
                                { resizable: true, size: "50%", scrollable: false },
                                { resizable: true, size: "50%", scrollable: false }
                            ],
                            orientation: "horizontal"
                        }).data("kendoSplitter");
                    }
                    splitter2_init() {
                        this.m_spliiter2 = this.splitter2Node.kendoSplitter({
                            panes: [
                                { resizable: true, size: "65%", scrollable: false },
                                { resizable: true, size: "35%", scrollable: false }
                            ],
                            orientation: "vertical"
                        }).data("kendoSplitter");
                    }
                    setCommandState() {
                        let setState = this.m_assignedList != null;
                        if (!setState) {
                            return;
                        }
                        PDJS.Application
                            .instance
                            .contexts
                            .current
                            .commands.setState({
                            "pdjs/manage/relationships": {
                                $assignedList: this.m_assignedList,
                                $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 AssignedList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    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());
                    }
                    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);
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-child-list">
                        <div role="list"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                    }
                    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 assigned.",
                            change: (items) => {
                                this.changeCallback();
                            },
                            createItem: (e) => {
                                return new PDJS.Shared.UI.Controls.ListViewItem(e);
                            }
                        });
                        this.controls.add(this.m_list);
                    }
                }
                Relationships.AssignedList = AssignedList;
            })(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 AvailableList extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    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());
                    }
                    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);
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-parent-list">
                        <div>
                            <div class="-pdjs-header-box">
                                Available
                            </div>
                        </div>
                        <div role="list"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                    }
                    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);
                    }
                }
                Relationships.AvailableList = AvailableList;
            })(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 treeNode() {
                        return this.node.find("div[role=tree]");
                    }
                    load(nodes) {
                        nodes.forEach(node => {
                            node.entityTypeId = node.id;
                        });
                        this.m_tree.dataSource.data(nodes);
                    }
                    select(entityTypeId) {
                        this.treeNode.find(".k-state-selected")
                            .removeClass("k-state-selected");
                        let uids = [];
                        this.m_tree.dataSource.data().forEach((item) => {
                            item.entityTypeId == entityTypeId ?
                                uids.push(item.uid) : null;
                        });
                        uids.forEach(id => {
                            this.m_tree.select(this.treeNode.find(`tr[data-uid=${id}]`));
                        });
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-tree">
                         <div>
                            <div class="-pd-title-minimal">
                                Relationships Map
                            </div>
                        </div>
                        <div role="tree-container">
                            <div role="tree"></div>
                        </div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.isBrowserResizeAware = true;
                        this.tree_init();
                    }
                    onBrowserResize() {
                        if (this.m_tree != null) {
                            this.m_tree.resize();
                        }
                    }
                    tree_init() {
                        var getIcon = (icon) => {
                            return Jade.IconSet.get("pd").resolve(icon, Jade.IconSetSizeSpecificDirectory.x16);
                        };
                        this.m_tree = this.treeNode.kendoTreeList({
                            dataSource: {
                                schema: {
                                    model: {
                                        id: "nodeId",
                                        parentId: "parentId",
                                        expanded: true
                                    }
                                }
                            },
                            columns: [{
                                    field: "name",
                                    title: "Name",
                                    attributes: { style: "position:relative;" },
                                    template: (e) => {
                                        return `<label role="name-cell" style="background-image:url(${getIcon(e.icon)});">
                                    ${e.name}
                                </label>`;
                                    }
                                },
                                {
                                    field: "customId",
                                    title: "Custom ID"
                                }],
                            height: "100%",
                            resizable: true,
                            selectable: "multiple, row",
                            change: (e) => {
                                e.preventDefault();
                            }
                        }).data("kendoTreeList");
                    }
                }
                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() {
                        var _a;
                        return (_a = this.m_grid) === null || _a === void 0 ? void 0 : _a.getSelections().first();
                    }
                    get viewStateId() {
                        return this.state.get("viewStateId");
                    }
                    template() {
                        return `<div class="-pdjs-manage-entity-types-relationships-types-list">
                        <div>
                            <div class="-pd-title-minimal">
                                Entity Types
                            </div>
                        </div>
                        <div role="grid"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.list_init();
                    }
                    list_init() {
                        this.m_grid = new PD.Web.UI.Controls.ViewGrid({
                            container: `[id=${this.ID}] [role=grid]`,
                            viewStateId: this.viewStateId,
                            selectionMode: "single",
                            selectOnRightClick: true,
                            selection: {
                                mapping: (e) => {
                                    return {
                                        id: e.ObjectId,
                                        name: e.Name
                                    };
                                }
                            },
                            change: (e) => {
                                this.changeCallback(e.selection);
                            }
                        });
                    }
                }
                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.Dialog {
                    constructor(options, windowOptions = {}) {
                        super(_.extend({
                            title: "Assign | Type"
                        }, options), _.extend({
                            height: "400px",
                            width: "500px",
                            maximized: false,
                            resizable: true
                        }, windowOptions));
                    }
                    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="text"></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();
                    }
                    closeAndReturn() {
                        this.close({
                            command: "ok",
                            data: this.m_grid.getSelections().toArray().map(item => {
                                return {
                                    id: item.id,
                                    name: item.name
                                };
                            })
                        });
                    }
                    grid_init() {
                        this.m_grid = new PD.Web.UI.Controls.Grid({
                            container: "div[role=grid]",
                            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({
                                    icon: "graph_node.png",
                                    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 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 {
                get listId() {
                    return this.source.getFeatureValue("listId");
                }
                set listId(value) {
                    this.source.setFeatureValue("listId", value);
                }
                get listName() {
                    return this.source.getFeatureValue("listName");
                }
                set listName(value) {
                    this.source.setFeatureValue("listName", value);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.inputNode.prop("disabled", "disabled");
                    this.inputNode.prop("readonly", "readonly");
                    this.showImage(false);
                    this.inputNode.val(this.listName || "");
                }
                popupButton_onClick() {
                    PDJS.JS.PD.Manage.Modules.Extensions.SelectionListSelectorDialog.open({
                        callbacks: {
                            ok: (sender, e) => {
                                this.listId = e.id;
                                this.listName = e.name;
                                this.inputNode.val(e.name);
                            }
                        }
                    });
                }
            }
            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 Users;
        (function (Users) {
            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);
                }
                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();
                    PDJS.JS.PD.context
                        .get_default()
                        .get_events()
                        .subscribe("group/members-added", (e) => {
                        this.commit();
                        this.m_grid.refresh({
                            clear: true,
                            selections: e.members
                        });
                    });
                    PDJS.JS.PD.context
                        .get_default()
                        .get_events()
                        .subscribe("group/members-removed", (e) => {
                        this.commit();
                        this.m_grid.refresh({
                            clear: true
                        });
                    });
                }
                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) => {
                            PDJS.JS.PD
                                .context
                                .get_default()
                                .get_commands()
                                .setState({
                                "pd/groups": {
                                    members: e.selections.toArray(),
                                    membership: this.memberships
                                }
                            });
                        },
                        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 PD.Web.UI.Controls.Toolbar({
                        container: `div[id=${this.ID}] div[role=menu]`,
                        backgroundColor: "#FFFFFF",
                        segments: [
                            new PDJS.JS.PD.Manage.Modules.GroupMembershipToolbarSegment()
                        ]
                    });
                }
                commit() {
                    this.source.setFeatureValue("usersToAdd", this.memberships.add);
                    this.source.setFeatureValue("usersToRemove", this.memberships.remove);
                }
            }
            Users.GroupMembershipEditor = GroupMembershipEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Users.GroupMembershipEditor", GroupMembershipEditor);
            });
        })(Users = Manage.Users || (Manage.Users = {}));
    })(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");
                }
                load(jobId) {
                    this.jobId = jobId;
                    this.controls.clear();
                    this.addItems();
                }
                template() {
                    return `<div class="-pdjs-manage-jobs-actions">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addItems();
                }
                addItems() {
                    this.addGlobalItems();
                    this.addJobItems();
                }
                addGlobalItems() {
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Rules"
                    }));
                    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...",
                        click: (e) => {
                            PDJS.Manage.Rules.RuleEditing.create({
                                commit: () => {
                                }
                            });
                        }
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuHeading({
                        label: "Jobs"
                    }));
                    this.controls.add(new PDJS.Shared.UI.Controls.PanelMenuLink({
                        url: "#/module/scheduled-jobs-log",
                        label: "View Log"
                    }));
                }
                addJobItems() {
                    let historyList = this.addJobHistory();
                    let scheduleList = this.addJobSchedule();
                    if (this.jobId == null) {
                        return;
                    }
                    let service = new PDJS.Services.Jobs.JobService();
                    service.getJobInfo({
                        id: this.jobId,
                        success: (e) => {
                            e.data.history.forEach(data => {
                                data.dateStarted = new Date(data.dateStarted).toLocaleDateString(undefined, {
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                    hour: "numeric",
                                    minute: "2-digit"
                                });
                                historyList.addItem(data);
                            });
                            e.data.triggers.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"
                                });
                                scheduleList.addItem(item);
                            });
                        }
                    });
                }
                addJobHistory() {
                    let result = 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(result);
                    return result;
                }
                addJobSchedule() {
                    let result = 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(result);
                    label.node.css({
                        marginTop: "10px"
                    });
                    return result;
                }
            }
            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"
                        },
                        callbacks: {
                            "ok": (sender, data) => {
                                this.grid.refresh({
                                    selections: [data.target.id],
                                    clear: true
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/create",
                        tooltip: "New",
                        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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Jobs",
                        message: `Delete the selected jobs?`,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/delete",
                        tooltip: "Delete",
                        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);
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "Edit | Job",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Jobs.JobUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Jobs.JobArbiter",
                            targetId: _.first(this.selections).id
                        },
                        callbacks: {
                            "ok": (sender, data) => {
                                this.grid.refresh();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/update",
                        tooltip: "Edit",
                        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 ExecuteJobCommand extends Jobs.JobsCommand {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let service = new PDJS.Services.Jobs.JobService();
                    PDJS.Shared.TaskStatusDialog.open({
                        title: "Execute | 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();
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "job/execute",
                        tooltip: "Execute",
                        label: "Execute",
                        icon: "media_play.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
            }
            Jobs.ExecuteJobCommand = ExecuteJobCommand;
        })(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 Script",
                        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
                        },
                        callbacks: {
                            "ok": (sender, data) => {
                            }
                        }
                    });
                }
                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.UpdateJobCommand());
                    e.commands.add(new Jobs.ExecuteJobCommand());
                    e.commands.add(new Jobs.EditScriptCommand());
                    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/execute"
                    }));
                    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.Name,
                                    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 Jade.UI.Control {
                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]");
                }
                focus() {
                }
                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.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                        commandId: "pdjs/manage/jobs:job/execute"
                    }));
                    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 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
                        },
                        callbacks: {
                            "ok": (sender, data) => {
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "event/view",
                        tooltip: "View 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({
                        callbacks: {
                            ok: (sender, e) => {
                                this.executeDelete(e.scope);
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "log/clear",
                        tooltip: "Clear 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: "No scheduled jobs."
                        },
                        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 Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                focus() {
                    if (this.m_grid) {
                        this.m_grid.refresh();
                    }
                }
                resize() {
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} -pdjs-manage-jobs-log"></div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.module_init();
                }
                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.Dialog {
                constructor(options, windowOptions = {}) {
                    super(_.extend({
                        title: "Clear | Jobs Log"
                    }, options), _.extend({
                        width: 300,
                        maximized: false,
                        resizable: false
                    }, windowOptions));
                }
                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 `<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>`;
                }
                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({
                        command: "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 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 = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Licensing;
        (function (Licensing) {
            class LicenseContentFeature extends PDJS.Shared.Features.Interop.MacroEditor {
                constructor(options) {
                    super(options);
                }
                get editor() {
                    return this.m_editor;
                }
                get editorNode() {
                    return this.node.find("div[role=ace]");
                }
                template() {
                    return `<div>
                        <div role="ace" style="position:absolute;top:20px;right:0;bottom:0;left:0;"></div>
                    </div>`;
                }
                onEditorReady() {
                    this.editor_init();
                }
                editor_init() {
                    ace.config.set("basePath", Jade.Path.resolve("~/areas/shared/assets/external/ace"));
                    this.m_editor = ace.edit(this.editorNode.get(0));
                    this.editor.setReadOnly(true);
                    this.editor.setOption("displayIndentGuides", false);
                    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.renderer.setPadding(20);
                    this.editor.setHighlightActiveLine(false);
                    this.editor.setTheme("ace/theme/sqlserver");
                    this.editor.commands.removeCommand("find");
                    this.editor.commands.removeCommand("showSettingsMenu");
                    this.editor.session.setMode({ path: "ace/mode/xml", v: Date.now() });
                    this.editor.setValue(this.getValue("content") || "", 0);
                    this.editor.clearSelection();
                }
            }
            Licensing.LicenseContentFeature = LicenseContentFeature;
        })(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 LicensePropertiesFeature extends PDJS.Shared.Features.Interop.MacroEditor {
                constructor(options) {
                    super(options);
                }
                get properties() {
                    return this.getValue("properties");
                }
                template() {
                    return `<div>
                        <div role="grid" style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden;border:1px solid #CCCCCC;"></div>
                    </div>`;
                }
                onEditorReady() {
                    this.grid_init();
                }
                grid_init() {
                    let data = this.properties;
                    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: Object.keys(data).map(function (key) {
                                return { label: Jade.String.toTitleCase(key), value: data[key] };
                            })
                        },
                        messaging: {
                            noRecordsMessage: "Column not referenced by any search groups."
                        },
                        selectionMode: "none",
                        resizable: true,
                        columns: [
                            new PD.Web.UI.Controls.GridColumn({
                                field: "label",
                                title: "Property",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "value",
                                title: "Value",
                                width: "150px"
                            }),
                            new PD.Web.UI.Controls.GridFillColumn()
                        ]
                    });
                }
            }
            Licensing.LicensePropertiesFeature = LicensePropertiesFeature;
        })(Licensing = Manage.Licensing || (Manage.Licensing = {}));
    })(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) {
            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}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Actions</div>
                        <div data-controls></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({
                                callbacks: {
                                    ok: () => { }
                                }
                            });
                        }
                    }));
                    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("$explorer", null);
                    this.state.set("$editor", null);
                    this.state.set("$node", 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 selectedNode() {
                    return this.contextMenuNode || this.explorer.selectedProcessNode;
                }
                get contextMenuNode() {
                    this.ensureContextMenuNode();
                    return this.m_contextMenuNode;
                }
                get contextMenuNodeId() {
                    return this.state.get("$targetNodeId");
                }
                commit() {
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/process": {
                            $explorer: this.explorer,
                            $editor: this.editor
                        }
                    }, { force: true });
                }
                ensureContextMenuNode() {
                    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);
                    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.icon = "box_white_surprise.png";
                            break;
                        case "key":
                            this.label = "Add Stage";
                            this.icon = "gear.png";
                            break;
                        case "stage":
                            this.label = "Add Decision";
                            this.icon = "breakpoint.png";
                            break;
                        case "decision":
                            this.label = "Add 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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: `Delete | Node`,
                        message: message,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.MessageDialogButton.ok) {
                                this.deleteNode();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/delete",
                        tooltip: "Delete",
                        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) {
            class SaveNodeCommand extends Process.ProcessCommandBase {
                constructor() {
                    super({});
                }
                onExecute(e) {
                    this.editor.commit({
                        success: (e) => {
                            this.updateNode(e.target);
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "node/save",
                        tooltip: "Save",
                        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("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);
            class ProcessContextMenuCommands extends Jade.CommandGroup {
                constructor() {
                    super("manage/process/context-menu");
                }
                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.ProcessContextMenuCommands = ProcessContextMenuCommands;
            Jade.CommandGroups.add(ProcessContextMenuCommands);
        })(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 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({
                        onCommitSuccess: (e) => {
                            PDJS.Shared
                                .MessageStack
                                .instance
                                .success("Changes Saved");
                            PDJS.JS.PD.monitor.getActiveSource().setClean();
                        }
                    });
                    this.controls.add(this.m_editor);
                }
                menu_init() {
                    this.m_menu = new Jade.UI.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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "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}">
                        <div role="head" class="${Manage.CssClass.ModuleSectionTitle}">Process Model</div>
                        <div role="menu"></div>
                        <div data-controls></div>
                    </div>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.menu_init();
                    this.tree_init();
                    this.data_init();
                }
                data_init() {
                    let service = new PDJS.Services.Manage.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 Jade.UI.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) {
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "manage/process/context-menu:node/add"
                    }));
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "manage/process/context-menu:node/delete"
                    }));
                }
                onOpen(e) {
                    super.onOpen(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/process/context-menu": {
                            $targetNodeId: e.target.data("id")
                        }
                    }, { force: true });
                }
            }
            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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/process:node/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/process: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 Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get processId() {
                    return this.state.get("processId");
                }
                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>`;
                }
                onInit(e) {
                    super.onInit(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .createContext({
                        id: this.ID,
                        name: "Process Module"
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter_init();
                    this.editor_init();
                    this.explorer_init();
                    this.actions_init();
                    this.setCommandState();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .destroyContext({
                        id: this.ID
                    });
                }
                actions_init() {
                    this.m_actions = new Process.ProcessActions({
                        insertAt: "div[data-id=pane-3]",
                        processId: this.processId
                    });
                    this.controls.add(this.m_actions);
                }
                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
                    });
                    this.controls.add(this.m_editor);
                }
                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/process": {
                            $explorer: this.m_explorer,
                            $editor: this.m_editor
                        }
                    }, { force: true });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "manage/process/context-menu": {
                            $explorer: this.m_explorer,
                            $editor: this.m_editor
                        }
                    }, { force: true });
                }
            }
            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 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({
                        "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",
                        args: {
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessStatusUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessStatusArbiter",
                            properties: {
                                processId: this.processId
                            }
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                this.grid.items.add(new PDJS.Core.Process.ProcessStatus(e.target));
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.id]
                                });
                            }
                        }
                    }, {
                        height: 460
                    });
                }
                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 });
                            }
                        }
                    });
                }
                confirmDeletion() {
                    Jade.UI.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Process Status",
                        message: "Delete the selected process status?",
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.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",
                        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
                            }
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                let status = this.grid.items.getById(e.target.id);
                                if (status) {
                                    status.update(e.target);
                                    this.grid.refresh();
                                }
                            }
                        }
                    }, {
                        height: 460
                    });
                }
                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("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.Dialog {
                constructor(options) {
                    super(options, {
                        title: "Expression Assigment",
                        height: "450px",
                        width: "800px"
                    });
                }
                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 `
            <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="-jadejs-button">Close</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new ProcessStatusDialog(options);
                }
                getWindowOptions() {
                    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("manage/process/status:status/edit");
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.ToolBar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Process.ProcessStatusToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "manage/process/status": {
                            $grid: this.m_grid,
                            processId: this.processId
                        }
                    }, { force: true });
                }
            }
            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.Manage.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%",
                        columns: [
                            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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/process/status:status/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/process/status:status/edit"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "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);
                }
                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);
                }
                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();
                        }
                    });
                }
                onShowDialog() {
                    Process.DecisionStatusEditorDialog.open({
                        processId: this.processId,
                        callbacks: {
                            ok: (sender, e) => {
                                let item = e;
                                if (item != null) {
                                    this.selection = item;
                                }
                            }
                        }
                    });
                }
            }
            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.Dialog {
                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 `
            <div class="-pdjs-manage-process-decision-status-editor-dialog">
                <div role="grid"></div>
                <div role="deck">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new DecisionStatusEditorDialog(options);
                }
                getWindowOptions() {
                    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({
                            command: "ok",
                            data: status.toJSON()
                        });
                    }
                }
            }
            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"));
                    }
                    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 this.state.toJSON();
                }
                toKendoJSON() {
                    return _.extend({
                        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();
                    node.attr("data-id", processNode.id);
                    node.attr("data-type", processNode.type);
                    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() {
                    let result = null;
                    let item = this.tree.dataItem(this.tree.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);
                }
                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 = srcNode.data("type") || "unknown";
                    let dstType = dstNode.data("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 = srcNode.data("type") || "unknown";
                    let dstType = dstNode.data("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("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 ProcessesCommandBase 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({
                        "manage/processes": {
                            $grid: this.grid
                        }
                    }, { force: true });
                }
            }
            Process.ProcessesCommandBase = ProcessesCommandBase;
        })(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.ProcessesCommandBase {
                constructor() {
                    super({});
                }
                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"
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                this.grid.refresh({
                                    clear: true,
                                    selections: [e.target.id]
                                });
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/create",
                        tooltip: "New",
                        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.ProcessesCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    let processId = _.first(this.grid.selections).id;
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "Process",
                        args: {
                            targetId: processId,
                            targetType: "ProspectDirector.Web.Shared.Modules.Process.ProcessUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Process.ProcessArbiter"
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                this.grid.refresh();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/edit",
                        tooltip: "Edit",
                        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.ProcessesCommandBase {
                constructor() {
                    super({});
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.selections.length == 1;
                }
                onExecute(e) {
                    super.onExecute(e);
                    Jade.UI.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete | Process",
                        message: `Delete the selected process?`,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.MessageDialogButton.ok) {
                                this.executeDelete();
                            }
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "process/delete",
                        tooltip: "Delete",
                        label: "Delete",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                executeDelete() {
                    let service = new PDJS.Services.Manage.Process.ProcessService();
                    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.ProcessesCommandBase {
                constructor() {
                    super({});
                }
                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",
                        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("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: "manage/processes:process/edit"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "manage/processes:process/delete"
                    }));
                    e.addSeparator();
                    e.addItem(new Jade.UI.ContextMenuItemCommand({
                        commandId: "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 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", () => { });
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get selections() {
                    return this.m_grid.getSelections().toArray();
                }
                resize() {
                    if (this.m_grid) {
                        this.m_grid.redraw();
                    }
                }
                refresh(args = {}) {
                    if (this.m_grid) {
                        this.m_grid.refresh(args);
                    }
                }
                template() {
                    return `<div class="${Process.CssClass.ProcessesModuleGrid}">
                        <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.gridNode,
                        viewStateId: this.viewStateId,
                        selectionMode: "single",
                        height: "100%",
                        selectOnRightClick: true,
                        selection: {
                            mapping: (e) => {
                                return {
                                    id: e.ObjectId,
                                    name: e.Name
                                };
                            }
                        },
                        messaging: {
                            noRecordsMessage: "No processes exist."
                        },
                        dblclick: (e) => {
                            this.dblClickCallback(e.selections);
                        },
                        change: (e) => {
                            this.changeCallback(e.selections);
                        },
                        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 Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                set viewStateId(value) {
                    this.state.set("viewStateId", value);
                }
                resize() {
                    if (this.m_grid) {
                        this.m_grid.resize();
                    }
                }
                template() {
                    return `<div class="${Manage.CssClass.Module} ${Process.CssClass.ProcessesModule}">
                        <div role="toolbar"></div>
                        <div role="grid"></div>
                    </div>`;
                }
                onInit(e) {
                    super.onInit(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .createContext({
                        id: this.ID,
                        name: "Processes Module"
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.toolbar_init();
                }
                onComplete(e) {
                    super.onComplete(e);
                    this.setCommandState();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    PDJS.Application
                        .instance
                        .contexts
                        .destroyContext({
                        id: this.ID
                    });
                }
                grid_init() {
                    this.m_grid = new Process.ProcessesGrid({
                        insertAt: "div[role=grid]",
                        viewStateId: this.viewStateId,
                        change: (e) => {
                            this.setCommandState();
                        },
                        dblClick: (e) => {
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute("manage/processes:process/open");
                        }
                    });
                    this.controls.add(this.m_grid);
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.ToolBar({
                        insertAt: "div[role=toolbar]",
                        segments: [new Process.ProcessesToolbar()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                setCommandState() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands.setState({
                        "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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/processes:process/create"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/processes:process/edit"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "manage/processes:process/delete"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "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 RecycleBinConfirmationDialog extends Jade.UI.MultipleChoiceDialog {
                static open(options) {
                    return new RecycleBinConfirmationDialog({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        type: Jade.UI.MultipleChoiceDialogType.Radio,
                        title: "Referenced Entity Handling",
                        header: `<span style="color:darkred">WARNING: This recycle bin operation cannot be undone.</span><br/>
                         How would you like the system to proceed when a referenced entity is encountered during the deletion process:`,
                        items: [
                            {
                                title: "Skip and Proceed",
                                message: `Skip deletion of the entity 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 entity, delete the entity and proceed onto the next item to delete.`,
                                value: "delete"
                            }
                        ],
                        select: (e) => {
                            e.close();
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                if (e.selected.length == 1) {
                                    options.select(e.selected[0].value);
                                }
                            }
                        }
                    });
                }
            }
            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 ReportSelectionDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "Select Report"
                    }), {
                        height: "400px",
                        width: "600px",
                        maximized: false
                    });
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                }
                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: function (e) {
                            e.filters[e.filters.length] = {
                                id: "OnlyHTML"
                            };
                        }
                    });
                }
                okButton_onClick(e) {
                    this.closeAndReturn();
                }
                cancelButton_onClick(e) {
                    this.close();
                }
                closeAndReturn() {
                    if (this.m_selection != null) {
                        this.close({
                            command: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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() {
                    return this.list.map(item => item.type);
                }
                static get list() {
                    this.ensureTypes();
                    return this.m_list.slice(0);
                }
                static getType(extension) {
                    return _.first(this.list.filter(item => {
                        return item.type == extension;
                    }));
                }
                static isEditableType(extension) {
                    return this.getType(extension) != null;
                }
                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"
                        },
                        {
                            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",
                        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",
                        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({
                        callbacks: {
                            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",
                        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: `Create a new folder within the currently selected folder.`,
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: "New | Folder",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FolderUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FolderArbiter",
                            properties: {
                                parentId: this.currentFolder.id
                            }
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                sender.destroyContext();
                                this.updateUI(e.target);
                                this.folderContentChanged();
                            }
                        }
                    }, {
                        height: 400,
                        width: 450,
                    });
                }
                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",
                        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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        allowClose: true,
                        title: "Delete Selections",
                        message: `Delete the selected ${ids.length} items?`,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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);
                }
                getDefaultValuesForProps() {
                    return {
                        id: "resource/open",
                        label: "Open",
                        icon: "nav_redo.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdjs"
                    };
                }
                onStateChanged(state) {
                    super.onStateChanged(state);
                    this.enabled = this.selections.length === 1;
                }
                execute(e) {
                    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"
                    });
                }
                canOpenFileForEdit(file) {
                    let extension = Jade.Path.getFileExtension(file.name);
                    return Resources.EditableTypes.isEditableType(extension);
                }
            }
            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}`,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FolderUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FolderArbiter"
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                this.browser.refresh();
                                if (this.selection.name == e.target.name) {
                                    return;
                                }
                                this.explorer.refresh(e.target.parentId);
                                Resources.EventsHub.explorerRefreshPublish();
                            }
                        }
                    }, {
                        height: 500,
                        width: 450,
                    });
                }
                editFile() {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `File | ${this.selection.name}`,
                        args: {
                            targetId: this.selection.id,
                            targetType: "ProspectDirector.Web.Manage.Modules.Resources.FileMetadataUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Resources.FileArbiter"
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                PDJS.Manage.EventsHub.moduleChangeDataPublish({
                                    id: `resources-editor/${e.target.id}`,
                                    label: `${e.target.name}`
                                });
                                this.browser.refresh();
                                this.folderContentChanged();
                            }
                        }
                    }, {
                        height: 500,
                        width: 450,
                    });
                }
            }
            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",
                        icon: "folder_zip_up.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                execute(e) {
                    super.execute(e);
                    this.executeServiceCall();
                }
                executeServiceCall() {
                    Resources.UploadZipDialog.open({
                        callbacks: {
                            ok: (sender, e) => {
                                sender.destroyContext();
                                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 Jade.UI.Control {
                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);
                }
                focus() {
                    if (this.splitter) {
                        this.splitter.resize(true);
                    }
                    if (this.recorder) {
                        this.recorder.refresh();
                    }
                }
                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>`;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.module_init();
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter) {
                        this.splitter.destroy();
                    }
                }
                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();
                    Resources.EventsHub.locationChangedSubscribe((e) => {
                        this.updateCommandState();
                    });
                    Resources.EventsHub.resourceHighlightSubscribe((e) => {
                        this.updateCommandState();
                    });
                    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;
                    Resources.EventsHub.browserRefreshSubscribe(() => {
                        if (this.grid) {
                            this.draggable_init();
                            this.grid_droppable_init();
                        }
                    });
                    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();
                }
                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;
                }
                onInitialize() {
                    super.onInitialize();
                    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();
                    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/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);
                    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) {
                    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() {
                    var result = null;
                    if (_.isArray(this.path)) {
                        result = "";
                        this.path.forEach(item => {
                            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>
                                <img src="${this.getIcon16x16("navigate_left.png")}"/>
                            </button>
                        </div>
                        <div>
                            <button role="next" class="${Resources.CssClass.LocationButton} ${Resources.CssClass.LocationButtonNext}" disabled>
                                <img src="${this.getIcon16x16("navigate_right.png")}"/>
                            </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>
                                        <img src="${this.getIconMisc("arrow-right-trans.png")}"/>
                                    </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
                    });
                    Resources.EventsHub.locationChangeSubscribe(_.bind(this.onChange, this));
                    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) {
                    var imageUrl = this.getIconMisc("arrow-right-trans.png", "pdjs");
                    return `<div class="${Resources.CssClass.LocationPathItem}" data-id="${item.id}">
                        <div>${item.name}</div>
                        <div>
                            <img src="${imageUrl}"/>
                        </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();
                    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 Manage;
    (function (Manage) {
        var Resources;
        (function (Resources) {
            class DuplicateFilesDialog extends Jade.UI.MultipleChoiceDialog {
                static open(options) {
                    return new DuplicateFilesDialog({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        type: Jade.UI.MultipleChoiceDialogType.Radio,
                        title: "Duplicate Files Found",
                        header: "A duplicate file name has been found. How would you like to handle this duplicate and any other duplicates found?",
                        items: [
                            {
                                title: "Skip Duplicate Files",
                                message: `Any duplicate files found will be skipped and will not be moved or copied to the destination.`,
                                value: 1,
                                selected: true
                            },
                            {
                                title: "Overwrite Duplicate Files",
                                message: `Any duplicate files found in the destination will be overwritten by the files being moved or copied.`,
                                value: 2
                            }
                        ],
                        select: (e) => {
                            e.close();
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                if (e.selected.length == 1) {
                                    options.select(e.selected[0].value);
                                }
                            }
                        }
                    });
                }
            }
            Resources.DuplicateFilesDialog = DuplicateFilesDialog;
        })(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 DuplicateFoldersDialog extends Jade.UI.MultipleChoiceDialog {
                static open(options) {
                    return new DuplicateFoldersDialog({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        type: Jade.UI.MultipleChoiceDialogType.Radio,
                        title: "Duplicate Folders Found",
                        header: "A duplicate folder name has been found. How would you like to handle this duplicate folder and all other duplicate folders?",
                        items: [
                            {
                                title: "Skip Duplicate Folders",
                                message: `All duplicate folders and their contents will be skipped and will not be moved to the destination.`,
                                value: 1,
                                selected: true
                            },
                            {
                                title: "Merge Duplicate Folders",
                                message: `All duplicate folders found in the destination will have their contents merged with the folders being moved.`,
                                value: 2
                            }
                        ],
                        select: (e) => {
                            e.close();
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                if (e.selected.length == 1) {
                                    options.select(e.selected[0].value);
                                }
                            }
                        }
                    });
                }
            }
            Resources.DuplicateFoldersDialog = DuplicateFoldersDialog;
        })(Resources = Manage.Resources || (Manage.Resources = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskAlertDialog extends Jade.UI.Dialog {
            constructor(options, windowOptions = {}) {
                super(options, windowOptions);
            }
            get alert() {
                return this.state.get("alert", { code: -1 });
            }
            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.TaskAlertDialog {
                constructor(options, windowOptions = {}) {
                    super(_.extend({
                        title: `Move | Resolve Conflict`
                    }, options), _.extend({
                        actions: [],
                        width: "500px",
                        maximized: false,
                        resizable: true
                    }, windowOptions));
                }
                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 `<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>`;
                }
                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({
                                    command: "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.Dialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "New | File"
                    }), {
                        height: "350px",
                        width: "500px",
                        maximized: false,
                        resizable: false
                    });
                }
                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 `
            <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="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>`;
                }
                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({
                        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({
                            command: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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] > img");
                    }
                    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() {
                        let img = Jade.IconSet.get("pd")
                            .resolve("cancel.png", Jade.IconSetSizeSpecificDirectory.misc);
                        return `<div role="item">
                        <div role="check">
                            <input type="checkbox" tabIndex="${this.tabIndex}" />
                        </div>
                        <div role="template">${this.templateContent()}</div>
                        <div role="remove">
                            <img src="${img}"/>
                        </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.show() :
                            this.removeNode.hide();
                        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) {
                            let isCurrentlySelected = this.node.attr("data-selected") == "true";
                            this.selected = !isCurrentlySelected;
                            this.node.attr("data-selected", !isCurrentlySelected ? "true" : "false");
                            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();
                    }
                    get iconVisible() {
                        return this.state.get("iconVisible", true);
                    }
                    set iconVisible(value) {
                        this.state.set("iconVisible", value);
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.iconVisible ?
                            this.iconNode.show() :
                            this.iconNode.hide();
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        this.iconVisible ?
                            this.iconNode.show() :
                            this.iconNode.hide();
                    }
                    templateContent() {
                        return `<div class="-pdjs-list-view-item">
                        <div role="icon">
                            <img src="${this.iconPath}"/>
                        </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.Dialog {
                constructor(options, windowOptions = {}) {
                    super(options, _.extend({
                        height: "500px",
                        width: "800px",
                        maximized: false,
                        resizable: true
                    }, windowOptions));
                }
                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 `<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();
                    }
                }
                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));
                    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();
                    Resources.EventsHub.locationChangedSubscribe((e) => {
                        this.updateCommandState();
                    });
                    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
                    });
                    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.slice(0);
                    let loading = Jade.UI.MessageDialog.open({
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                        dialogStyle: Jade.UI.MessageDialogStyle.Information,
                        allowClose: false,
                        title: "Opening Files",
                        message: "Opening files, please wait...",
                        select: (e) => { }
                    });
                    let open = () => {
                        let file = files.pop();
                        window.location.hash = `/module/resources-editor/${file.id}`;
                        if (files.length > 0) {
                            setTimeout(() => { open(); }, 1000);
                        }
                        else {
                            loading.close();
                        }
                    };
                    this.close();
                    open();
                }
                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({
                                command: "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.MessageDialog.open({
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                dialogStyle: Jade.UI.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(options, {
                        title: "File | Select"
                    }));
                    this.m_selectedFiles = [];
                }
                get folderId() {
                    return this.state.get("folderId");
                }
                closeAndReturn() {
                    this.returnFiles();
                }
                onInit() {
                    this.selectionMode = PD.Web.UI.Controls.GridSelectionMode.single;
                }
                onDialogPrepared() {
                    Resources.EventsHub.locationChangePublish({
                        folderId: this.folderId,
                        record: true
                    });
                    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({
                        command: "ok",
                        data: this.m_selectedFiles
                    });
                }
                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 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.Dialog {
                constructor(options, windowOptions = {}) {
                    super(_.extend({
                        title: "Upload | Zip Package"
                    }, options), _.extend({
                        height: "100px",
                        width: "400px",
                        maximized: false,
                        resizable: true
                    }, windowOptions));
                }
                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 `<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({
                            command: "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.uploadName = e.name;
                            this.uploadId = e.target_name;
                            this.okButtonNode.removeAttr("disabled");
                        }
                    });
                    this.controls.add(this.m_upload);
                }
                static open(options = { callbacks: {} }) {
                    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("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 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);
                    }
                    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 FontSizeCommand extends Editor.EditorCommand {
                    getDefaultValuesForProps() {
                        return {
                            id: "editor/font-size",
                            label: "Font Size",
                            enabled: true,
                            display: "label",
                            iconSetId: "pdv2"
                        };
                    }
                    execute(e) {
                        this.editor.fontSize = `${e.selection}px`;
                    }
                    onInitialLoad() {
                        super.onInitialLoad();
                        let fontSize = this.editor.fontSize;
                        if (!Jade.String.isNullOrWhiteSpace(fontSize)) {
                            this.value = parseInt(fontSize);
                        }
                    }
                }
                Editor.FontSizeCommand = FontSizeCommand;
            })(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",
                            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,
                            callbacks: {
                                ok: (sender, e) => {
                                }
                            }
                        });
                    }
                }
                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",
                            icon: "floppy_disk.png",
                            enabled: true,
                            display: "icon label",
                            iconSetId: "pdv2"
                        };
                    }
                    setState(state) {
                        super.setState(state);
                        this.enabled = this.editor && this.editor.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.getValue() || "",
                            success: (e) => {
                                PDJS.Manage.EventsHub.moduleChangeDataPublish({
                                    id: this.moduleId,
                                    asterik: 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.getValue(),
                            folderId: this.folderId,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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",
                            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.getValue(),
                            folderId: this.folderId,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.destroyContext();
                                    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 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.showFind();
                    }
                }
                Editor.ToggleFindCommand = ToggleFindCommand;
            })(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 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.showIndents;
                    }
                    execute(e) {
                        this.checked = !this.checked;
                        this.editor.showIndents = this.checked;
                    }
                }
                Editor.ToggleIndentsCommand = ToggleIndentsCommand;
            })(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 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.showInvisibles;
                    }
                    execute(e) {
                        this.checked = !this.checked;
                        this.editor.showInvisibles = this.checked;
                    }
                }
                Editor.ToggleInvisiblesCommand = ToggleInvisiblesCommand;
            })(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 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.showLineNumbers;
                    }
                    execute(e) {
                        this.checked = !this.checked;
                        this.editor.showLineNumbers = this.checked;
                    }
                }
                Editor.ToggleLineNumbersCommand = ToggleLineNumbersCommand;
            })(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 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.showReplace();
                    }
                }
                Editor.ToggleReplaceCommand = ToggleReplaceCommand;
            })(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.FontSizeCommand());
                        e.commands.add(new Editor.OpenCommand());
                        e.commands.add(new Editor.SaveCommand());
                        e.commands.add(new Editor.SaveAsCommand());
                        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 = 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 Jade.UI.Control {
                    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 successCallback() {
                        return this.state.get("success", () => { });
                    }
                    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);
                    }
                    get moduleId() {
                        return this.state.get("moduleId", null);
                    }
                    set moduleId(value) {
                        this.state.set("moduleId", value);
                    }
                    focus() {
                        if (this.editor) {
                            this.editor.focus();
                        }
                    }
                    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();
                        this.fileId == null ?
                            this.loadNewResource() :
                            this.loadExistingResource();
                        Editor.EventsHub.saveAsSubscribe((e) => {
                            this.state.set({
                                fileId: e.fileId,
                                fileName: e.fileName,
                                folderId: e.folderId,
                                folderPath: e.folderPath
                            });
                            let newId = `resources-editor/${this.fileId}`;
                            let newRoute = `#/module/${newId}`;
                            PDJS.Manage.EventsHub.moduleChangeDataPublish({
                                id: this.moduleId,
                                label: this.fileName,
                                asterik: false,
                                newId: newId,
                                route: newRoute,
                                tooltip: this.folderPath
                            });
                            window.history.replaceState({}, "", newRoute);
                            this.moduleId = newId;
                            PDJS.Manage.Resources.
                                EventsHub.folderContentChangedPublish({
                                folderId: e.folderId
                            });
                            this.updateCommandState();
                        });
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.registerKeyboardShortcuts();
                    }
                    onDestroy(e) {
                        super.onDestroy(e);
                    }
                    editor_init() {
                        this.editor = new PDJS.Shared.UI.Controls.CodeEditor({
                            insertAt: "div[data-role=editor]",
                            change: () => {
                                PDJS.Manage.EventsHub.moduleChangeDataPublish({
                                    id: this.moduleId,
                                    asterik: true
                                });
                                this.updateCommandState();
                            }
                        });
                        this.controls.add(this.editor);
                    }
                    toolbar_init() {
                        this.toolbar = new PDJS.Shared.UI.Controls.Toolbar({
                            insertAt: "div[data-role=toolbar]",
                            segments: [new Editor.EditorToolbar()]
                        });
                        this.controls.add(this.toolbar);
                    }
                    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 });
                    }
                    loadNewResource() {
                        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.editor.setStyle(type.mime);
                                this.updateCommandState();
                                this.successCallback({
                                    fileId: this.fileId,
                                    fileName: this.fileName,
                                    folderPath: path
                                });
                            }
                        });
                    }
                    loadExistingResource() {
                        let service = new PDJS.Services.Resources.ResourcesService();
                        service.loadTextFile({
                            fileId: this.fileId,
                            success: (e) => {
                                this.editor.setValue(e.data.content, true);
                                this.editor.setStyle(e.data.mimeType);
                                this.editor.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.updateCommandState();
                                this.successCallback({
                                    fileId: this.fileId,
                                    fileName: this.fileName,
                                    folderPath: e.data.folderPath
                                });
                                PDJS.Manage.EventsHub.moduleChangeDataPublish({
                                    id: this.moduleId,
                                    label: this.fileName,
                                    asterik: false,
                                    tooltip: this.folderPath
                                });
                            },
                            error: (e) => {
                                this.errorCallback("File cannot be found.");
                                e.errorHandled = true;
                            }
                        });
                    }
                    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");
                        });
                    }
                }
                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`
                        }));
                        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 Editor.FontSizeItem({
                            commandId: `${prefix}:editor/font-size`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:editor/find`
                        }));
                        e.registerItem(new PDJS.Shared.UI.Controls.ToolbarCommandButton({
                            commandId: `${prefix}:editor/replace`
                        }));
                    }
                }
                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) {
                class EventsHub extends PDJS.Shared.EventsHubBase {
                    static saveAsPublish(args) {
                        this.current.publish(Editor.Events.SaveAs, args);
                    }
                    static saveAsSubscribe(handler) {
                        return this.current.subscribe(Editor.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 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);
                    }
                    createCopy() {
                        return new ToolbarItem(this.state.toJSON());
                    }
                    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();
                    }
                    onPropertiesChanged() {
                        let previous = this.commander.previous;
                        this.createTooltip();
                        this.node.css({
                            paddingRight: this.commander.visible && !this.overflowed ? "5px" : ""
                        });
                        previous.tooltip = this.commander.tooltip;
                    }
                    createTooltip() {
                        Tipped.remove(this.node);
                        let shouldCreate = this.commander.enabled &&
                            this.commander.visible;
                        if (!shouldCreate) {
                            return;
                        }
                        let content = `
                <div style="font-size:13px;line-height:20px;">
                    <b>${this.commander.label}</b><br/>
                    ${this.commander.tooltip}
                </div>`;
                        Tipped.create(this.node, content, {
                            skin: "white",
                            showOn: "mouseenter",
                            hideOn: "mouseleave",
                            hideAfter: 200,
                            hideDelay: 0,
                            showDelay: 750,
                            maxWidth: 300,
                            position: this.overflowed ? "left" : "bottommiddle"
                        });
                    }
                    hideTooltip() {
                        Tipped.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 Resources;
        (function (Resources) {
            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 = 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) {
            class RuleEditing {
                static create(e = {}) {
                    this.showFeatureDialog(e);
                }
                static edit(e) {
                    this.showFeatureDialog(e);
                }
                static editScript(scriptId) {
                    window.location.href = `#/module/rule-script-editor/${scriptId}`;
                }
                static showFeatureDialog(e) {
                    let title = e.ruleId == null ?
                        `New` : `${e.ruleName}`;
                    let callback = e.commit || (() => { });
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        title: `Rule Script | ${title}`,
                        height: "400px",
                        width: "450px",
                        args: {
                            targetId: e.ruleId,
                            targetType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Rules.RuleScriptArbiter"
                        },
                        callbacks: {
                            "ok": (sender, e) => {
                                callback(e);
                            }
                        }
                    });
                }
            }
            Rules.RuleEditing = RuleEditing;
        })(Rules = Manage.Rules || (Manage.Rules = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Reports;
        (function (Reports) {
            class RuleScriptSelectionDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(_.extend(options, {
                        title: "Select Rule Script"
                    }), {
                        height: "400px",
                        width: "600px",
                        maximized: false
                    });
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                }
                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({
                            command: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "No rule script has been selected. Select a rule script and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
                static open(options) {
                    return new RuleScriptSelectionDialog(options);
                }
            }
            Reports.RuleScriptSelectionDialog = RuleScriptSelectionDialog;
        })(Reports = Manage.Reports || (Manage.Reports = {}));
    })(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.attributes.isReadOnly;
                }
                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: "",
                            backgroundImage: ""
                        });
                        return;
                    }
                    this.labelNode.css({
                        color: "darkred",
                        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>");
                    Tipped.create(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_sizeToFit();
                        }, 200);
                    }
                }
                template() {
                    return `<div class="-fb-rich-text-editor">
                        <div role="container">
                            <textarea></textarea>
                        </div>
                    </div>`;
                }
                resize() {
                    this.editor_sizeToFit();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.editor_init();
                    setTimeout(() => { this.editor_sizeToFit(); }, 300);
                }
                editor_init() {
                    tinymce.init({
                        selector: `#${this.ID} > DIV > TEXTAREA`,
                        document_base_url: Jade.Path.resolve("~/scripts/pdjs/external/tinymce"),
                        apply_source_formatting: true,
                        plugins: "link hr textcolor colorpicker",
                        menubar: false,
                        statusbar: false,
                        toolbar: [
                            "undo redo | fontselect 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: `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.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_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);
                }
            }
            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 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.css({
                        color: this.isReadOnly ? "#AAAAAA" : "",
                        borderColor: this.isReadOnly ? "#CCCCCC" : ""
                    });
                    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 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({
                            callbacks: {
                                ok: (sender, e) => {
                                    this.m_editor.insertTag(e.tagName);
                                    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 Tags;
        (function (Tags) {
            class ExpressionsSelectionDialog extends Jade.UI.Dialog {
                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({
                            command: "cancel"
                        });
                    });
                    this.startUp();
                }
                getWindowOptions() {
                    return _.merge(super.getWindowOptions(), {
                        title: "Expression Selection",
                        height: 350,
                        width: 500
                    });
                }
                template() {
                    return `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div role="grid" style="position:absolute;top:0;left:0;right:0;bottom:36px;overflow:hidden;border: 1px solid #CCCCCC;"></div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new ExpressionsSelectionDialog(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 {
                                        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.window.destroyContext();
                        this.close({
                            command: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "Nothing has been selected. Make a selection and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
            }
            Tags.ExpressionsSelectionDialog = ExpressionsSelectionDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(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, windowOptions = {}) {
                    return new FeatureDialogForNhib(options, windowOptions);
                }
            }
            Features.FeatureDialogForNhib = FeatureDialogForNhib;
        })(Features = Shared.Features || (Shared.Features = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(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",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.ExpressionArbiter"
                        },
                        callbacks: {}
                    }, {
                        height: 400,
                        width: 500
                    });
                }
            }
            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",
                        args: {
                            targetType: "ProspectDirector.Web.Manage.Modules.Tags.TagUIO",
                            arbiterType: "ProspectDirector.Web.Manage.Modules.Tags.TagArbiter"
                        },
                        callbacks: {}
                    }, {
                        height: 400,
                        width: 500,
                    });
                }
            }
            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 TagsSelectionDialog extends Jade.UI.Dialog {
                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({
                            command: "cancel"
                        });
                    });
                    this.startUp();
                }
                getWindowOptions() {
                    return _.merge(super.getWindowOptions(), {
                        title: "Tag Selection",
                        height: 350,
                        width: 500
                    });
                }
                template() {
                    return `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div role="grid" style="position:absolute;top:0;left:0;right:0;bottom:36px;overflow:hidden;border:1px solid #CCCCCC;"></div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new TagsSelectionDialog(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 {
                                        tagName: 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.TAG_SELECTION,
                            success: (e) => {
                                this.viewStateId = e.data.viewStateId;
                                this.grid_init();
                            }
                        });
                    }
                }
                closeAndReturn() {
                    if (this.selection != null) {
                        this.window.destroyContext();
                        this.close({
                            command: "ok",
                            data: this.selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            title: "No Selection Made",
                            message: "Nothing has been selected. Make a selection and try again.",
                            select: (e) => {
                                e.close();
                            }
                        });
                    }
                }
            }
            Tags.TagsSelectionDialog = TagsSelectionDialog;
        })(Tags = Manage.Tags || (Manage.Tags = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        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);
                }
                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();
                    PDJS.JS.PD.context
                        .get_default()
                        .get_events()
                        .subscribe("user/memberships-added", (e) => {
                        this.commit();
                        this.m_grid.refresh({
                            clear: true,
                            selections: e.memberships
                        });
                    });
                    PDJS.JS.PD.context
                        .get_default()
                        .get_events()
                        .subscribe("user/memberships-removed", (e) => {
                        this.commit();
                        this.m_grid.refresh({
                            clear: true
                        });
                    });
                }
                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) => {
                            PDJS.JS.PD
                                .context
                                .get_default()
                                .get_commands()
                                .setState({
                                "pd/users": {
                                    groups: e.selections.toArray(),
                                    membership: this.memberships
                                }
                            });
                        },
                        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 PD.Web.UI.Controls.Toolbar({
                        container: `div[id=${this.ID}] div[role=menu]`,
                        backgroundColor: "#FFFFFF",
                        segments: [
                            new PDJS.JS.PD.Manage.Modules.UserMembershipToolbarSegment()
                        ]
                    });
                }
                commit() {
                    this.source.setFeatureValue("membershipsToAdd", this.memberships.add);
                    this.source.setFeatureValue("membershipsToRemove", this.memberships.remove);
                }
            }
            Users.UserMembershipEditor = UserMembershipEditor;
            Jade.Application.onStart(() => {
                FeatureBlendJS.FeatureBlend.addEditorType("PDJS.Manage.Users.UserMembershipEditor", UserMembershipEditor);
            });
        })(Users = Manage.Users || (Manage.Users = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Manage;
    (function (Manage) {
        var Views;
        (function (Views) {
            class ViewDeleteDialog extends Jade.UI.MultipleChoiceDialog {
                static open(options) {
                    return new ViewDeleteDialog({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        type: Jade.UI.MultipleChoiceDialogType.Radio,
                        title: "Linked View Handling",
                        header: `<span style="color:darkred">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: (e) => {
                            e.close();
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                if (e.selected.length == 1) {
                                    options.select(e.selected[0].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 ViewDesignEditor extends FeatureBlendJS.Views.MacroEditorBase {
                get menuNode() {
                    return this.node.children("div[role=menu]");
                }
                get gridNode() {
                    return this.node.children("div[role=grid]");
                }
                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();
                        }
                    });
                }
                menu_init() {
                    this.m_menu = new PD.Web.UI.Controls.Toolbar({
                        container: `#${this.ID} div[role=menu]`,
                        segments: [
                            new PDJS.JS.PD.Manage.Modules.ViewDesignToolbar(() => {
                                return {
                                    viewGrid: this.m_grid
                                };
                            })
                        ]
                    });
                }
            }
            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 SearchGroups extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.subscriptions.add(Views.SearchGroupEvent.onSearchGroupRefreshRequest, (e) => {
                        this.grid.refresh(e || {});
                    });
                }
                get grid() {
                    return this.state.get("grid");
                }
                set grid(value) {
                    this.state.add("grid", value);
                }
                get toolbar() {
                    return this.state.get("toolbar");
                }
                set toolbar(value) {
                    this.state.add("toolbar", value);
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId", null);
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.toolbar_init();
                }
                template() {
                    return `
                <div style="background-color:#EEEEEE !important;position:absolute;top:0;left:0;right:0;bottom:0;">
                    <div style="position:absolute;top:0;left:0;right:0;height:30px;background-color:#EEEEEE;" class="-pd-title-minimal">Groups</div>
                    <div style="position:absolute;top:40px;left:0;right:0;height:30px;background-color:#EEEEEE;" data-id="toolbar"></div>
                    <div style="position:absolute;top:80px;left:0;right:0;bottom:0;border:1px solid #DDDDDD;" 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.Name
                                    };
                                });
                            }
                        },
                        change: (e) => {
                            let searchGroup = _.first(e.selections.toArray());
                            let searchGroupId = searchGroup == null ? Jade.Guid.empty() : searchGroup.id;
                            Jade.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .setState({
                                "views/searchgroups": {
                                    searchGroupId: searchGroupId
                                }
                            });
                            Jade.Application
                                .instance
                                .contexts
                                .current
                                .events
                                .publish("searchgroup/select", searchGroupId);
                        },
                        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 Jade.UI.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.Dialog {
                constructor(options) {
                    super(options, {
                        title: "Search Groups",
                        height: "600px",
                        width: "800px",
                        maximized: true
                    });
                }
                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);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.splitter = this.splitterNode.kendoSplitter({
                        orientation: "horizontal",
                        panes: [
                            { size: "275px" },
                            {}
                        ],
                        resize: _.debounce(() => {
                            if (this.splitter != null) {
                                this.splitter.resize(true);
                            }
                        }, 50)
                    }).data("kendoSplitter");
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve("~/Manage/View/SearchGroups"),
                        success: (e) => {
                            this.loadControls(e);
                        }
                    });
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "views/searchgroups": {
                            entityTypeId: this.entityTypeId,
                            documentTypeId: this.documentTypeId
                        }
                    });
                    this.closeButtonNode.on("click", (e) => {
                        this.close();
                    });
                }
                onDestroy(e) {
                    super.onDestroy(e);
                    if (this.splitter != null && this.splitter.element != null) {
                        this.splitter.destroy();
                    }
                }
                template() {
                    return `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div style="position:absolute;top:0;left:0;right:0;bottom:34px;">
                    <div data-id="splitter" class="-pd-minimal-splitter" style="height:100%;">
                        <div data-role="groups"></div>
                        <div data-role="items"></div>
                    </div>
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="close" class="-jadejs-button">Close</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new SearchGroupsDialog(options);
                }
                loadControls(e) {
                    this.controls.add(new Views.SearchGroups({
                        insertAt: "[data-role=groups]",
                        viewStateId: e.searchGroupsViewStateId,
                        entityTypeId: this.entityTypeId,
                        documentTypeId: this.documentTypeId
                    }));
                    this.controls.add(new Views.SearchItems({
                        insertAt: "[data-role=items]",
                        viewStateId: e.searchGroupItemsViewStateId,
                        entityTypeId: this.entityTypeId,
                        documentTypeId: this.documentTypeId
                    }));
                }
            }
            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 SearchGroupsToolbarSegment extends Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "views/searchgroups:searchgroup/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "views/searchgroups:searchgroup/edit"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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();
                    Jade.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe("searchgroup/select", (id) => {
                        this.m_selectedSearchGroupId = id;
                        this.m_grid.refresh({
                            clear: true
                        });
                    });
                    this.subscriptions.add(Views.SearchItemEvent.onSearchItemRefreshRequest, (e) => {
                        this.m_grid.refresh(e || {});
                    });
                }
                get viewStateId() {
                    return this.state.get("viewStateId", null);
                }
                onActivate(e) {
                    this.grid_init();
                    this.toolbar_init();
                }
                template() {
                    return `
                <div style="background-color:#EEEEEE !important;position:absolute;top:0;left:0;right:0;bottom:0;">
                    <div style="position:absolute;top:0;left:0;right:0;height:30px;background-color:#EEEEEE;" class="-pd-title-minimal">Items</div>
                    <div style="position:absolute;top:40px;left:0;right:0;height:30px;background-color:#EEEEEE;" data-id="toolbar"></div>
                    <div style="position:absolute;top:80px;left:0;right:0;bottom:0;border:1px solid #DDDDDD;" 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) => {
                            let searchItemIds = _.map(e.selections.toArray(), (e) => {
                                return e.id;
                            });
                            Jade.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .setState({
                                "views/searchgroups": {
                                    searchItemIds: searchItemIds
                                }
                            });
                        },
                        needContext: (e) => {
                            e.filters[e.filters.length] = {
                                id: "Group",
                                params: {
                                    id: this.m_selectedSearchGroupId
                                }
                            };
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "views/searchgroups:searchitem/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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 AddSearchGroupCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        entityTypeId: null,
                        documentTypeId: null
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/add",
                        tooltip: "New",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                get entityTypeId() {
                    return this.state.get("entityTypeId", null);
                }
                get documentTypeId() {
                    return this.state.get("documentTypeId", null);
                }
                onExecute(e) {
                    if (this.entityTypeId == null && this.documentTypeId == null) {
                        return;
                    }
                    window["ProspectDirector"].Web.UI.FeatureSets.NHibTargetEditorDialog.open({
                        config: {
                            title: `Add Search Group`,
                            height: "500px",
                            width: "650px"
                        },
                        data: {
                            targetArbiter: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupArbiter",
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupUIO",
                            layoutType: window["ProspectDirector"].Web.UI.FeatureSets.Layouts.TabStripLayout,
                            properties: {
                                entityTypeId: this.entityTypeId,
                                documentTypeId: this.documentTypeId
                            }
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(Views.SearchGroupEvent.onSearchGroupRefreshRequest, {
                                    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) {
            let SearchItemEvent;
            (function (SearchItemEvent) {
                SearchItemEvent["onSearchItemRefreshRequest"] = "searchitem/refresh-request";
            })(SearchItemEvent = Views.SearchItemEvent || (Views.SearchItemEvent = {}));
            class AddSearchItemCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        searchGroupId: null
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "searchitem/add",
                        tooltip: "New",
                        label: "New",
                        icon: "plus.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                get searchGroupId() {
                    return this.state.get("searchGroupId", null);
                }
                onStateChanged(e) {
                    this.enabled = this.searchGroupId != null;
                }
                onExecute(e) {
                    if (this.searchGroupId == null) {
                        return;
                    }
                    PDJS.Manage.Views.SearchItemsSelectionDialog.open({
                        searchGroupId: this.searchGroupId,
                        callbacks: {
                            ok: (sender, e) => {
                                PDJS.Ajax.call({
                                    type: "POST",
                                    url: Jade.Path.resolve("~/Manage/View/AddSearchItems"),
                                    data: {
                                        searchGroupId: this.searchGroupId,
                                        ids: e.extensionColumnIds
                                    },
                                    success: (e2) => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(SearchItemEvent.onSearchItemRefreshRequest, e.extensionColumnIds);
                                    }
                                });
                            }
                        }
                    });
                }
            }
            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) {
            let SearchGroupEvent;
            (function (SearchGroupEvent) {
                SearchGroupEvent["onSearchGroupRefreshRequest"] = "searchgroup/refresh-request";
                SearchGroupEvent["onSearchGroupSelected"] = "searchgroup/selected";
            })(SearchGroupEvent = Views.SearchGroupEvent || (Views.SearchGroupEvent = {}));
            class EditSearchGroupCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        searchGroupId: null
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/edit",
                        tooltip: "Edit",
                        label: "Edit",
                        icon: "pencil.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                get searchGroupId() {
                    return this.state.get("searchGroupId", null);
                }
                onStateChanged(e) {
                    this.enabled = this.searchGroupId != null;
                }
                onExecute(e) {
                    window["ProspectDirector"].Web.UI.FeatureSets.NHibTargetEditorDialog.open({
                        config: {
                            title: `Edit Search Group`,
                            height: "500px",
                            width: "650px"
                        },
                        data: {
                            targetId: this.searchGroupId,
                            targetArbiter: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupArbiter",
                            targetType: "ProspectDirector.Web.Manage.Modules.Views.SearchGroupUIO",
                            layoutType: window["ProspectDirector"].Web.UI.FeatureSets.Layouts.TabStripLayout
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                Jade.Application
                                    .instance
                                    .contexts
                                    .current
                                    .events
                                    .publish(SearchGroupEvent.onSearchGroupRefreshRequest, {
                                    clear: false
                                });
                            }
                        }
                    });
                }
            }
            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 Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        searchGroupId: null
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "searchgroup/remove",
                        tooltip: "Remove",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                get searchGroupId() {
                    return this.state.get("searchGroupId", null);
                }
                onStateChanged(e) {
                    this.enabled = this.searchGroupId != null;
                }
                onExecute(e) {
                    if (this.searchGroupId == null) {
                        return;
                    }
                    Jade.UI.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        title: "Remove Search Group",
                        message: `Remove the selected search group?`,
                        select: (e) => {
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                PDJS.Ajax.call({
                                    type: "DELETE",
                                    url: Jade.Path.resolve("~/Manage/View/DeleteSearchGroup"),
                                    data: {
                                        id: this.searchGroupId
                                    },
                                    success: (e) => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(Views.SearchGroupEvent.onSearchGroupRefreshRequest, {
                                            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 RemoveSearchItemCommand extends Jade.Command {
                constructor(props) {
                    super(props);
                    this.state.set({
                        searchItemIds: null
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "searchitem/remove",
                        tooltip: "Remove",
                        label: "Remove",
                        icon: "delete.png",
                        enabled: false,
                        display: "icon label",
                        iconSetId: "pdv2"
                    };
                }
                get searchItemIds() {
                    return this.state.get("searchItemIds", []);
                }
                onStateChanged(e) {
                    this.enabled = this.searchItemIds.length > 0;
                }
                onExecute(e) {
                    Jade.UI.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OKCancel,
                        title: "Remove Search Item",
                        message: `Remove the selected search items?`,
                        select: (e) => {
                            if (e.button == Jade.UI.MessageDialogButton.ok) {
                                PDJS.Ajax.call({
                                    type: "DELETE",
                                    url: Jade.Path.resolve("~/Manage/View/DeleteSearchItems"),
                                    data: {
                                        ids: this.searchItemIds
                                    },
                                    success: (e) => {
                                        Jade.Application
                                            .instance
                                            .contexts
                                            .current
                                            .events
                                            .publish(Views.SearchItemEvent.onSearchItemRefreshRequest, {
                                            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 SearchItemsSelectionDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(_.extend({
                        title: "Search Item Selection"
                    }, options), {
                        height: "450px",
                        width: "600px"
                    });
                    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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;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="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-button">Cancel</button>
                </div>
            </div>
            `;
                }
                static open(options) {
                    return new SearchItemsSelectionDialog(options);
                }
                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 = _.map(this.m_grid.getSelections().toArray(), (item) => {
                        return item.id;
                    });
                    this.close({
                        command: "ok",
                        data: {
                            extensionColumnIds: selections
                        }
                    });
                }
            }
            Views.SearchItemsSelectionDialog = SearchItemsSelectionDialog;
        })(Views = Manage.Views || (Manage.Views = {}));
    })(Manage = PDJS.Manage || (PDJS.Manage = {}));
})(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 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.complete(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 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 DocumentTypes;
        (function (DocumentTypes) {
            class DocumentTypeService {
                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 EntityTypes;
        (function (EntityTypes) {
            class EntityTypesService {
                list(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypes/List",
                        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();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/EntityTypeRelationships/Index",
                        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 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();
                }
                getJobInfo(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/GetJobInfo",
                        method: Jade.HttpVerb.GET,
                        data: data
                    }).sendRequest();
                }
                index(data) {
                    Services.ServicePipeline.createRequest({
                        url: "~/Manage/Jobs/Index",
                        method: Jade.HttpVerb.GET,
                        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 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();
                    }
                    getStatusList(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/Process/GetStatuses",
                            method: Jade.HttpVerb.GET,
                            data: data
                        }).sendRequest();
                    }
                    getTree(data) {
                        Services.ServicePipeline.createRequest({
                            url: "~/Manage/Process/GetTree",
                            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 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();
                }
            }
            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 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) {
                    let promises = [];
                    let addFile = (folderId, file) => {
                        return new Promise((resolve, reject) => {
                            let uploadedFile = file;
                            this.addFile({
                                folderId: data.folderId,
                                uploadId: `${file.id}${file.extension}`,
                                fileMode: uploadedFile.fileMode || 0,
                                file: uploadedFile,
                                success: (e) => {
                                    file.fileId = e.data.id;
                                    resolve({
                                        file: file
                                    });
                                },
                                error: (e) => {
                                    var errors = e.xhr.responseJSON != null ?
                                        e.xhr.responseJSON : [];
                                    var error = _.first(errors) || {};
                                    e.errorHandled = true;
                                    reject({
                                        code: error.code || 0,
                                        file: file
                                    });
                                }
                            });
                        });
                    };
                    let handleResults = (results) => {
                        let fulfilled = results.filter(result => {
                            return result.status === "fulfilled";
                        }).map(item => item.value.file);
                        let rejected = results.filter(result => {
                            return result.status === "rejected";
                        }).map(item => item.reason);
                        if (rejected.length > 0) {
                            let uniqueCodes = _.uniqBy(rejected, (item) => {
                                return item.code;
                            }).map(item => item.code);
                            data.error({
                                data: {
                                    folderId: data.folderId,
                                    failed: rejected,
                                    succeeded: fulfilled,
                                    errorCodes: uniqueCodes
                                },
                                xhr: null
                            });
                        }
                        else {
                            data.success({
                                data: {
                                    ids: fulfilled.map(item => item.fileId)
                                },
                                xhr: null
                            });
                        }
                    };
                    data.files.forEach(file => {
                        promises.push(addFile(data.folderId, file));
                    });
                    let onFileSaveSuccess = (data.onFileSaveSuccess || (() => { }));
                    let onFileSaveFailure = (data.onFileSaveFailure || (() => { }));
                    promises.forEach((promise) => {
                        promise.then((value) => {
                            onFileSaveSuccess(value.file);
                        }, (value) => {
                            onFileSaveFailure(value.file);
                        });
                    });
                    Promise.allSettled(promises)
                        .then(handleResults);
                }
                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();
                }
            }
            Resources.ResourcesService = ResourcesService;
        })(Resources = Services.Resources || (Services.Resources = {}));
    })(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 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 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();
                }
                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();
                }
            }
            Tags.TagService = TagService;
        })(Tags = Services.Tags || (Services.Tags = {}));
    })(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) {
            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_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["SEARCH_GROUP_COLUMN_SELECTION"] = "searchColumnSelection";
                BuiltInViews["SEARCH_GROUP_ITEMS"] = "searchGroupItems";
                BuiltInViews["SEARCH_GROUPS"] = "searchGroups";
                BuiltInViews["SELECTION_LISTS"] = "selectionLists";
                BuiltInViews["SELECTION_LISTS_ALL"] = "selectionListsAll";
                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 {
                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 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 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 icon = Jade.IconSet.get("pdjs")
                    .resolve("loading-animated.gif", Jade.IconSetSizeSpecificDirectory.x24);
                toastrNode.css({
                    backgroundImage: `url(${icon})`,
                    backgroundColor: "#FFFFFF",
                    color: "#000000"
                });
                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 Environment {
            constructor(options) {
                this.m_state = new Jade.StateBag(options);
                this.m_state.bind("change", (e) => { this.onStateChanged(e); });
                this.m_preferences = PDJS.Shared.Personalization.Preferences.current;
            }
            static get current() {
                this.ensureInstance();
                return this.m_instance;
            }
            get state() {
                return this.m_state;
            }
            get applicationId() {
                return this.state.get("environment.applicationId");
            }
            get applicationName() {
                return this.state.get("environment.applicationName", "Prospect Director");
            }
            get applicationUrl() {
                return this.state.get("environment.applicationUrl");
            }
            get authenticationMode() {
                return this.state.get("environment.", 0);
            }
            get entityTemplateId() {
                return this.state.get("environment.entityTemplateId", 0);
            }
            get isLocalAuthMode() {
                return this.state.get("environment.isLocalAuth", false);
            }
            get virtualDirectory() {
                return this.state.get("environment.virtualDirectory", 0);
            }
            get user() {
                return this.state.get("user");
            }
            get userMenu() {
                return this.state.get("userMenu");
            }
            get theme() {
                return this.state.get("theme");
            }
            get preferences() {
                return PDJS.Shared.Personalization.Preferences.current;
            }
            load(options) {
                this.state.set(options);
                this.m_preferences.load(options.preferences);
            }
            onStateChanged(e) {
            }
            static ensureInstance() {
                if (!this.m_instance) {
                    this.m_instance = new Environment();
                }
            }
        }
        Shared.Environment = Environment;
    })(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);
            }
            warning(message, options) {
                return this.configureToastr(() => {
                    return toastr.warning(message);
                }, options);
            }
            success(message, options) {
                return this.configureToastr(() => {
                    return toastr.success(message);
                }, options);
            }
            info(message, options) {
                return this.configureToastr(() => {
                    return toastr.info(message);
                }, options);
            }
            exception(message, options) {
                return this.error(message, options);
            }
            configureToastr(invokeFn, options) {
                let result = null;
                toastr.options =
                    _.extend(this.defaults, options || {});
                result = invokeFn();
                toastr.options = this.defaults;
                return result;
            }
        }
        Shared.MessageStack = MessageStack;
    })(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 SessionState {
            constructor() {
            }
            static get interval() {
                return 2000;
            }
            get expires() {
                return 1200000;
            }
            get isCurrentlyExpired() {
                return this.m_expired;
            }
            set isCurrentlyExpired(value) {
                this.m_expired = value;
            }
            get isMonitoring() {
                return this.m_intervalId != null;
            }
            static get instance() {
                if (this.m_instance == null) {
                    this.m_instance = new SessionState();
                }
                return this.m_instance;
            }
            init() {
                if (PDJS.Shared.Environment.current.isLocalAuthMode) {
                    this.startMonitor();
                }
            }
            resetMonitor(reload = false) {
                this.isCurrentlyExpired = false;
            }
            triggerSessionExpiration() {
                this.isCurrentlyExpired = true;
                Jade.Application
                    .instance
                    .contexts
                    .global
                    .events
                    .publish(SessionState.SESSION_EXPIRED_EVENT);
                this.expireLastRequestCookie();
            }
            triggerSessionResume() {
                this.isCurrentlyExpired = false;
                Jade.Application
                    .instance
                    .contexts
                    .global
                    .events
                    .publish(SessionState.SESSION_RESUME_EVENT);
            }
            startMonitor() {
                if (this.m_intervalId != null) {
                    return;
                }
                if (this.hasReachedExpiration()) {
                    this.triggerSessionExpiration();
                }
                this.m_intervalId = window.setInterval(() => {
                    if (this.hasReachedExpiration()) {
                        this.triggerSessionExpiration();
                    }
                    else {
                        if (this.isCurrentlyExpired) {
                            this.triggerSessionResume();
                        }
                    }
                }, SessionState.interval);
            }
            hasReachedExpiration() {
                let startTime = null;
                let stamp = this.getCookie("Last-Request");
                try {
                    startTime = Date.parse(stamp);
                }
                catch (ex) {
                    console.log(ex);
                }
                if (isNaN(startTime)) {
                    return true;
                }
                let elapsedTime = Date.now() - startTime;
                return elapsedTime > this.expires;
            }
            getCookie(name) {
                let result = null;
                let match = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
                if (match != null) {
                    result = match.pop();
                }
                return result;
            }
            expireLastRequestCookie() {
                document.cookie = `Last-Request=expired;path=${PDJS.Application.instance.virtualDirectory}`;
            }
        }
        SessionState.SESSION_EXPIRED_EVENT = "Session:Expired";
        SessionState.SESSION_RESUME_EVENT = "Session:Resume";
        Shared.SessionState = SessionState;
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        class TaskStatusDialog extends Jade.UI.Dialog {
            constructor(options, windowOptions = {}) {
                super(_.extend({
                    title: "Task | Status",
                    pollUrl: "~/Shared/Task/Status",
                    pollFrequency: 500,
                    taskStart: null,
                    taskCancel: null,
                    showDetail: false,
                    allowClose: true,
                    enableClose: false,
                    callbacks: {}
                }, options), _.extend({
                    actions: []
                }, windowOptions));
            }
            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 `<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,
                    window: this.window
                });
            }
            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 ?
                    "250px" : "104px";
                let shouldRestore = !this.log.visible
                    && this.window.kendo.element.hasClass("k-window-maximized");
                this.setDimensions(height, this.window.kendo.element.width());
                this.window.setOptions({
                    height: height,
                    minHeight: height,
                    minWidth: "400px",
                    resizable: this.log.visible,
                    width: "400px",
                });
                if (shouldRestore) {
                    this.window.kendo.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 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) {
                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);
            }
            destroyContext() {
                this.window.destroyContext();
            }
            enableClose(enabled) {
                enabled ?
                    this.closeButton.removeAttr("disabled") :
                    this.closeButton.ttr("disabled", "disabled");
                this.closeButton.focus();
            }
            executeInParentContext(fn) {
                PDJS.Application.instance.contexts.revolveContext({
                    context: this.context.parent,
                    fn: () => {
                        fn();
                    }
                });
            }
            executeInDialogContext(fn) {
                PDJS.Application.instance.contexts.revolveContext({
                    context: this.context,
                    fn: () => {
                        fn();
                    }
                });
            }
            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,
                    callbacks: {
                        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;
                this.bar.backgroundColor =
                    status == "success" ? "#0adf0a" : "red";
            }
            onActivate(e) {
                super.onActivate(e);
                this.progressBar_init();
            }
            progressBar_init() {
                this.bar = new PDJS.Shared.UI.Controls.ProgressBar({
                    backgroundColor: "#FFFFFF",
                    showMessage: true,
                    color: "green",
                    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"}">
                    ${message != null ? message : ""}
                </div>`);
                content.css({
                    backgroundImage: `url(${this.m_bulletPath})`,
                    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.node.children("div").each((index, elem) => {
                    text += `${_.trim(elem.textContent)}\n`;
                });
                navigator.clipboard.writeText(text);
            }
            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;
            }
        }
        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 imageNode() {
                return this.node.children("img");
            }
            template() {
                return `<button role="clipboard">
                        <img src=-""/>
                    </button>`;
            }
            onActivate(e) {
                super.onActivate(e);
                this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                    this.clickCallback();
                });
                this.imageNode.attr("src", Jade.IconSet.get("pdjs")
                    .resolve("copy.png", Jade.IconSetSizeSpecificDirectory.x16));
                this.imageNode.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 imageNode() {
                return this.node.children("img");
            }
            template() {
                return `<button role="toggle" toggled="true">
                        <img src=-""/>
                    </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() {
                let icon = this.toggled ?
                    "navigate_up_black.png" :
                    "navigate_down_black.png";
                this.imageNode.attr("src", Jade.IconSet.get("pdjs")
                    .resolve(icon, Jade.IconSetSizeSpecificDirectory.x16));
                let title = this.toggled ?
                    "Show less detail" :
                    "Show more detail";
                this.imageNode.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");
            }
            get imgNode() {
                return this.statusNode.children("img");
            }
            template() {
                return `<div role="marquee">
                        <div></div>
                        <div>
                            <img />
                        </div>
                    </div>`;
            }
            update(message, status) {
                this.updateMessage(message);
                this.updateStatus(status);
            }
            updateStatus(status) {
                let icon = "";
                switch (status) {
                    case "error":
                        icon = "error.png";
                        break;
                    case "pending":
                        icon = "loading-animated.gif";
                        break;
                    case "success":
                        icon = "ok.png";
                        break;
                }
                this.imgNode.attr("src", Jade.IconSet
                    .get("pdjs").resolve(icon, Jade.IconSetSizeSpecificDirectory.x16));
            }
            updateMessage(message) {
                this.messageNode.text(message);
                this.messageNode.attr("title", this.message);
            }
        }
        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 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.Manage.Modules.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;
                    params = params || [];
                    result = new Actions.Action(this.toJSON({
                        parameter: this.parameters.map((parameter, index) => {
                            let param = index <= params.length ? {} : params[index];
                            let options = parameter.toJSON({
                                text: param === null || param === void 0 ? void 0 : param.text,
                                value: param === null || param === void 0 ? void 0 : param.value,
                            });
                            return new Actions.ActionParameter(options);
                        }),
                        execute: this.execute
                    }));
                    return result;
                }
                convertToParameters(params, fn) {
                    this.parameters = params.map(parameter => {
                        if (parameter.hasOwnProperty("id")) {
                            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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.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.id] = (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 id() {
                    return this.options.id;
                }
                get type() {
                    return this.options.type;
                }
                toJSON(data) {
                    return _.extend({
                        id: this.id,
                        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 text() {
                    return this.options.text;
                }
                get value() {
                    return this.options.value;
                }
                toJSON() {
                    return super.toJSON({
                        text: this.text,
                        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 Dialogs;
        (function (Dialogs) {
            class IconBrowserDialog extends Jade.UI.Dialog {
                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 `
                <div>
                    <div 
                        role="head" 
                        style="position:absolute;top:10px;height:25px;left:10px;right:10px;text-align:right;">
                    </div>
                    <div 
                        style="position:absolute;top:40px;bottom:44px;left:10px;right:10px;">
                        <div role="grid"></div>
                    </div>
                    <div 
                        style="position:absolute;bottom:10px;left:10px;right:10px;text-align:right;">
                        <button 
                            data-id="button-ok"  
                            class="-jadejs-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-jadejs-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();
                }
                getWindowOptions() {
                    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 style="line-height:26px;height:24px;width:100%;background-repeat:no-repeat;background-position:5px center;padding-left:26px;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({
                        command: "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.MultipleChoiceDialog {
                static show(select = () => { }) {
                    return Jade.UI.MultipleChoiceDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                        type: Jade.UI.MultipleChoiceDialogType.Radio,
                        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"
                            }],
                        select: (e) => {
                            select(e);
                        }
                    });
                }
            }
            Dialogs.UnsavedChangesDialog = UnsavedChangesDialog;
        })(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 UploadDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(options);
                }
                get message() {
                    return this.state.get("message", "Select file to upload.");
                }
                get okButtonNode() {
                    return this.node.find("button[data-id=button-ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-id=button-cancel]");
                }
                get uploadInput() {
                    return this.m_uploadInput;
                }
                template() {
                    return `
                <div>
                    <div 
                        role="head" 
                        style="position:absolute;top:10px;height:25px;left:10px;right:10px;text-align:left;font-size:12px;font-family:arial;">
                        ${this.message}
                    </div>
                    <div 
                        data-controls 
                        style="position:absolute;top:30px;bottom:44px;left:10px;right:10px;">
                    </div>
                    <div 
                        style="position:absolute;bottom:10px;left:10px;right:10px;text-align:right;">
                        <button 
                            data-id="button-ok"  
                            class="-jadejs-button"
                            style="margin-right:5px;">
                            OK
                        </button>
                        <button ,
                            data-id="button-cancel" 
                            class="-jadejs-button">
                            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.uploadInput_init();
                    this.okButtonNode.prop("disabled", true);
                }
                getWindowOptions() {
                    return {
                        height: 100,
                        width: 350,
                        title: "Upload"
                    };
                }
                uploadInput_init() {
                    this.m_uploadInput = new PDJS.Shared.UI.Controls.UploadInput({
                        onUploadComplete: () => {
                            this.okButtonNode.prop("disabled", false);
                        }
                    });
                    this.controls.add(this.m_uploadInput);
                }
                closeAndReturn() {
                    if (this.uploadInput.uploadId == null) {
                        return;
                    }
                    this.close({
                        command: "ok",
                        data: {
                            value: this.uploadInput.uploadUniqueName
                        }
                    });
                }
                static open(options) {
                    return new UploadDialog(options);
                }
            }
            Dialogs.UploadDialog = UploadDialog;
        })(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.Dialog {
                constructor(options) {
                    super(_.extend(options));
                }
                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);
                }
                get viewCustomId() {
                    return this.state.get("viewCustomId", PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPES);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get grid() {
                    return this.m_grid;
                }
                get selectionMode() {
                    return this.state.get("selectionMode", PD.Web.UI.Controls.GridSelectionMode.multiple);
                }
                get selections() {
                    return _.map(this.grid.getSelections().toArray(), "id");
                }
                template() {
                    return `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                }
                getWindowOptions() {
                    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();
                        }
                    });
                }
                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({
                                    command: "ok",
                                    data: e.data
                                });
                            },
                            error: (e) => {
                                this.close();
                            }
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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 EntityDialogs {
            static showCreate(options) {
                PDJS.Shared.Features.FeatureDialogForNhib.open({
                    args: {
                        arbiterType: "ProspectDirector.Web.Hub.Entities.EntityDialogArbiter",
                        targetType: "ProspectDirector.Web.Hub.Entities.EntityDialogUIO",
                        properties: {
                            entityTypeId: options.entityTypeId,
                            parentId: options.parentId ? options.parentId : null
                        }
                    },
                    callbacks: {
                        ok: (sender, e) => {
                            if (_.isFunction(options.onCreate)) {
                                options.onCreate(sender, e);
                            }
                            if (options.promptToOpen !== false) {
                                this.promptToExplore(e);
                            }
                        }
                    }
                }, { height: "500px", width: "680px" });
            }
            static showProperties(options) {
                PDJS.Shared.Features.FeatureDialogForNhib.open({
                    args: {
                        showApplyButton: true,
                        arbiterType: "ProspectDirector.Web.Hub.Entities.EntityDialogArbiter",
                        targetType: "ProspectDirector.Web.Hub.Entities.EntityDialogUIO",
                        properties: {
                            entityId: parseInt(options.entityId)
                        }
                    },
                    callbacks: {
                        ok: (sender, e) => {
                            sender.destroyContext();
                            if (_.isFunction(options.onSave)) {
                                options.onSave(sender, e);
                            }
                        }
                    }
                }, { height: "500px", width: "680px" });
            }
            static promptToExplore(data) {
                let entityTypeName = data.target.entityTypeName;
                let entityName = data.target.entityName;
                let entityId = data.target.entityID;
                Jade.UI.MessageDialog.open({
                    dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNo,
                    dialogStyle: Jade.UI.MessageDialogStyle.Success,
                    title: `${entityTypeName} Creation Success`,
                    message: `The new ${entityTypeName} "${entityName}" was created successfully. Would you like to open it now?`,
                    select: (e) => {
                        e.close();
                        switch (e.button) {
                            case Jade.UI.MessageDialogButton.yes:
                                window.location.href = Jade.Path.resolve(`~/Explore/${entityId}`);
                                break;
                            case Jade.UI.MessageDialogButton.no:
                                e.close();
                                break;
                        }
                    }
                });
            }
        }
        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({
                    args: {
                        showApplyButton: true,
                        arbiterType: "ProspectDirector.Web.Hub.Entities.EntityDialogArbiter",
                        targetType: "ProspectDirector.Web.Hub.Entities.EntityDialogUIO",
                        properties: {
                            entityId: parseInt(options.fileId)
                        }
                    },
                    callbacks: {
                        ok: (sender, e) => {
                            sender.destroyContext();
                            if (_.isFunction(options.onSave)) {
                                options.onSave(sender, e);
                            }
                        }
                    }
                }, { height: "500px", width: "680px" });
            }
        }
        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.Dialog {
                get filters() {
                    return this.state.get("filters", []);
                }
                set filters(value) {
                    this.state.set("filters", value);
                }
                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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                }
                getWindowOptions() {
                    return {
                        title: "Entity Browser",
                        height: 400,
                        width: 600,
                        maximized: false
                    };
                }
                static open(options) {
                    let result = new EntityBrowserDialog(options);
                    return result;
                }
                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 {
                                        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.window.destroyContext();
                        this.close({
                            command: "ok",
                            data: this.m_selection
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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();
                        }
                    });
                }
                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() {
                    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>`;
                }
                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() {
                    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 exist."
                        },
                        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 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, windowOptions = {}) {
                    return new FeatureDialogForJson(options, windowOptions);
                    ;
                }
            }
            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();
                        }
                    });
                }
                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();
                    }
                }
                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();
                        }
                    });
                }
                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) {
                            Jade.UI.ErrorDialog.open({
                                title: "Application Warning",
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                                errors: keyless.map(item => { return item.message; })
                            });
                        }
                        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);
                    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");
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.hide();
                        this.showImage(false);
                        this.setDisplayText();
                        this.node.addClass("-pdjs-ace-editor");
                    }
                    popupButton_onClick() {
                        Editors.AceEditorDialog.open({
                            ace: this.ace,
                            permissions: this.permissions,
                            callbacks: {
                                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 AceEditorDialog extends Jade.UI.Dialog {
                    constructor(options, windowOptions) {
                        super(options, windowOptions);
                    }
                    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="-jadejs-button">
                        OK
                    </button>
                    <button 
                        data-command="cancel"
                        class="-jadejs-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({
                                command: "ok",
                                data: {
                                    ace: this.ace
                                }
                            });
                        });
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.editor.loadAce(this.ace);
                    }
                    getDefaultOptions() {
                        return {
                            title: "Creator Permissions",
                            entityId: null,
                            identity: null,
                            windowOptions: {
                                actions: ["close"],
                                height: "300px",
                                minHeight: "300px",
                                width: "500px",
                                minWidth: "300px",
                                title: true,
                                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, windowOptions) {
                        return new AceEditorDialog(options, windowOptions);
                    }
                }
                Editors.AceEditorDialog = AceEditorDialog;
            })(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 textProperty() {
                        return this.source.state.get("textProperty");
                    }
                    get text() {
                        return this.source.getFeatureValue(this.textProperty);
                    }
                    set text(value) {
                        this.source.setFeatureValue(this.textProperty, value);
                    }
                    get defaultText() {
                        var _a;
                        return ((_a = this.action) === null || _a === void 0 ? void 0 : _a.name) != null ?
                            this.action.name : "None";
                    }
                    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;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.addClass("-fb-rule-script-selector-editor");
                        this.updateUI();
                        this.inputNode.prop("readonly", true);
                        this.inputNode.prop("tabindex", "-1");
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Actions.ActionDialog.open({
                            title: "Action Editor",
                            originalAction: this.action,
                            callbacks: {
                                ok: (sender, e) => {
                                    this.action = e;
                                    this.updateUI();
                                }
                            }
                        }, {
                            height: 500,
                            width: 700
                        });
                    }
                    clearButton_onClick() {
                        this.action = { id: null, pluginId: null, parameters: [] };
                        this.updateUI();
                    }
                    setIcon() {
                        if (this.action) {
                            this.imageNode.attr("src", Jade.IconSet.get("pd").resolve("FLASH_YELLOW.PNG", Jade.IconSetSizeSpecificDirectory.x16));
                            this.imageNode.attr("title", "Action");
                        }
                    }
                    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.inputNode.removeClass("-fb-no-selection");
                        }
                        else {
                            this.inputNode.val(this.defaultText);
                            this.inputNode.addClass("-fb-no-selection");
                        }
                    }
                    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);
                    }
                    updateUI() {
                        this.showImage(true);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasAction);
                        this.setIcon();
                        this.setInputText(this.text);
                        this.imageNode.css({
                            opacity: this.hasAction ? 1 : .5
                        });
                        this.hasAction ?
                            this.inputNode.removeClass("-pdjs-no-value") :
                            this.inputNode.addClass("-pdjs-no-value");
                    }
                }
                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 buttonNode() {
                        return this.node.children("button");
                    }
                    get inputNode() {
                        return this.node.children("input");
                    }
                    get swatchNode() {
                        return this.node.children("[role=swatch]");
                    }
                    get popup() {
                        return this.m_popup;
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue("");
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get allowTransparency() {
                        return this.source.state.get("allowTransparency", false);
                    }
                    get inputValue() {
                        return this.inputNode.val();
                    }
                    template() {
                        return `<div class="-fb-color-editor">
                        <div role="swatch">
                            <div></div>
                            <div></div>
                        </div>
                        <input type="text" maxlength="11" value="${this.value}" />
                        <button><img src="${Jade.IconSet.get("pdjs").resolve("navigate_down_black.png", Jade.IconSetSizeSpecificDirectory.x16)}"/></button>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.DOUBLECLICK, () => {
                            Tipped.show(this.buttonNode);
                        });
                        this.popup_init();
                        this.inputNode.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.updateInput(this.inputNode.val(), false);
                        });
                        this.inputNode.on(Jade.BrowserEvent.BLUR, (e) => {
                            let value = this.inputNode.val();
                            let updateText = Jade.String.isNullOrWhiteSpace(value) &&
                                this.allowTransparency;
                            this.updateInput(value, updateText);
                        });
                        this.updateInput(this.value, true);
                    }
                    popup_init() {
                        this.m_popup = new Editors.ColorEditorPopUp({
                            handle: this.buttonNode,
                            editor: this,
                            change: (e) => {
                                this.updateInput(e.color, true);
                            }
                        });
                        this.controls.add(this.m_popup);
                    }
                    updateInput(color, updateText) {
                        if (this.allowTransparency && Jade.String.isNullOrWhiteSpace(color)) {
                            color = "transparent";
                        }
                        let isValid = isValidColor(color, this.allowTransparency);
                        this.swatchNode.removeClass("-fb-swatch-error");
                        isValid ?
                            this.setValidSwatch(color) :
                            this.setInvalidSwatch();
                        this.value = color;
                        if (updateText === true) {
                            this.inputNode.val(color || "");
                        }
                    }
                    setValidSwatch(color) {
                        let transparent = color.toLowerCase() == "transparent";
                        let path = Jade.IconSet.get("pd")
                            .resolve("trasnparent-hint-4x4.png", Jade.IconSetSizeSpecificDirectory.misc);
                        this.swatchNode.css({
                            backgroundColor: color,
                            backgroundImage: transparent ? `url(${path})` : null,
                            backgroundRepeat: "repeat"
                        });
                    }
                    setInvalidSwatch() {
                        this.swatchNode.addClass("-fb-swatch-error");
                        this.swatchNode.css({
                            backgroundColor: "#FFFFFF",
                            backgroundImage: "",
                        });
                    }
                }
                Editors.ColorEditor = ColorEditor;
                function isValidColor(value, allowTransparency) {
                    let regex = allowTransparency ?
                        new RegExp("^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})|transparent$", "g") :
                        new RegExp("^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$", "g");
                    return Jade.String.isNullOrWhiteSpace(value) || regex.test(value || "");
                }
                Editors.isValidColor = isValidColor;
                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 ColorEditorPopUp extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_handle = options.handle;
                        this.m_editor = options.editor;
                    }
                    get editor() {
                        return this.m_editor;
                    }
                    get handle() {
                        return this.m_handle;
                    }
                    get colorPickerNode() {
                        return this.node.find("[role=picker]");
                    }
                    get colorPicker() {
                        return this.colorPickerNode
                            .data("kendoFlatColorPicker");
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get rInput() {
                        return this.node.find("input[role=R]");
                    }
                    get gInput() {
                        return this.node.find("input[role=G]");
                    }
                    get bInput() {
                        return this.node.find("input[role=B]");
                    }
                    get hexInput() {
                        return this.node.find("input[role=hex]");
                    }
                    get editorValue() {
                        return Editors.isValidColor(this.editor.value, true) ?
                            this.editor.value : "#FFFFFF";
                    }
                    template() {
                        return `
        <div class="-fb-color-editor-popup" style="display:none;">
            <div role="picker"></div>
            <div role="inputs">
                R: <input type="text" role="R" />
                G: <input type="text" role="G" />
                B: <input type="text" role="B" />
                Hex: <input type="text" role="hex" />
            </div>
        </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.rInput.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.rInput_onChange(e);
                        });
                        this.gInput.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.gInput_onChange(e);
                        });
                        this.bInput.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.bInput_onChange(e);
                        });
                        this.hexInput.on(Jade.BrowserEvent.KEYUP, (e) => {
                            this.hexInput_onChange(e);
                        });
                        this.popup_init();
                    }
                    rInput_onChange(e) {
                        this.updateHex();
                    }
                    gInput_onChange(e) {
                        this.updateHex();
                    }
                    bInput_onChange(e) {
                        this.updateHex();
                    }
                    hexInput_onChange(e) {
                    }
                    popup_init() {
                        Tipped.create(this.handle, this.node, {
                            skin: "white",
                            showOn: "click",
                            hideOn: "click-outside",
                            hideAfter: 500,
                            hideDelay: 0,
                            position: {
                                target: "bottomright",
                                tooltip: "topright"
                            },
                            offset: {
                                y: 6,
                                x: 7
                            },
                            stem: false,
                            maxWidth: 300,
                            onShow: () => {
                                this.popup_onShow();
                            }
                        });
                    }
                    popup_onShow() {
                        this.colorpicker_init();
                        this.colorPicker.value(this.editorValue);
                        this.updateColorInputs(this.editorValue);
                        this.hexInput.select();
                        this.hexInput.focus();
                    }
                    colorpicker_init() {
                        if (this.colorPicker == null) {
                            this.colorPickerNode.kendoFlatColorPicker({
                                preview: false,
                                value: this.editor.value,
                                change: (e) => {
                                    this.colorpicker_onChange(e);
                                }
                            }).data("kendoFlatColorPicker");
                        }
                    }
                    colorpicker_onChange(e) {
                        let value = (e.value || "#FFFFFF").toUpperCase();
                        this.changeCallback({
                            color: value
                        });
                        this.updateColorInputs(value);
                    }
                    updateColorInputs(value) {
                        var color = kendo.parseColor(value, true);
                        this.rInput.val(color.r);
                        this.gInput.val(color.g);
                        this.bInput.val(color.b);
                        this.hexInput.val(value);
                    }
                    updateHex() {
                        let r = parseInt(this.rInput.val());
                        let g = parseInt(this.gInput.val());
                        let b = parseInt(this.bInput.val());
                        let allValid = !Number.isNaN(r) &&
                            !Number.isNaN(g) &&
                            !Number.isNaN(b);
                        let hex = this.colorPicker.value();
                        if (allValid) {
                            hex = `#${r.toString(16).padStart(2, "0")}${g.toString(16)}${b.toString(16)}`;
                        }
                        this.colorPicker.value(hex);
                        hex = this.colorPicker.value();
                        this.hexInput.val(hex);
                        this.changeCallback({
                            color: hex
                        });
                    }
                }
                Editors.ColorEditorPopUp = ColorEditorPopUp;
            })(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 iconBinding() {
                        return this.source.state.get("iconBinding", 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",
                            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 DocumentTypeSelectorEditor extends Editors.PopUpEditor {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get nameProperty() {
                        return _.camelCase(this.source.state.get("nameProperty"));
                    }
                    get documentTypeName() {
                        return this.source.getFeatureValue(this.nameProperty, "");
                    }
                    set documentTypeName(value) {
                        this.source.setFeatureValue(this.nameProperty, value);
                    }
                    get fallbackNameProperty() {
                        return _.camelCase(this.source.state.get("fallbackNameProperty"));
                    }
                    get fallbackName() {
                        return this.source.getFeatureValue(this.fallbackNameProperty, "");
                    }
                    get documentTypeId() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set documentTypeId(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get hasDocumentType() {
                        return this.documentTypeId != null;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    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,
                            callbacks: {
                                ok: (sender, e) => {
                                    let file = _.first(e);
                                    this.documentTypeId = file.id;
                                    this.documentTypeName = file.name;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    clearButton_onClick() {
                        this.documentTypeId = null;
                        this.documentTypeName = null;
                        this.updateUI();
                    }
                    updateUI() {
                        let name = this.hasDocumentType ?
                            this.documentTypeName : this.fallbackName;
                        this.showImage(false);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasDocumentType);
                        this.inputNode.val(name);
                        this.hasDocumentType ?
                            this.inputNode.removeClass("-pdjs-no-value") :
                            this.inputNode.addClass("-pdjs-no-value");
                    }
                }
                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.Dialog {
                    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 `
            <div class="-pdjs-shared-feature-editors-expression-editor-dialog">
                <div role="grid"></div>
                <div>
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                    }
                    getWindowOptions() {
                        return {
                            title: "Select | Expression",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    static open(options, windowOptions) {
                        return new ExpressionEditorDialog(options, windowOptions);
                    }
                    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({
                                command: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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();
                            }
                        });
                    }
                }
                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");
                    }
                    get expressionName() {
                        return this.state.get("expressionName");
                    }
                    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.changeCallback({
                            expressionId: null,
                            expressionName: null
                        });
                    }
                    clearText() {
                        this.inputNode.val("No Expression Assigned");
                    }
                    template() {
                        return `<div class="-pdjs-shared-feature-editors-expression-editor-input">
                    <div>
                        <input type="text" readonly disabled />
                    </div>
                    <div>
                        <button ${this.readOnly || !this.enabled ? "disabled" : ""}>...</button>
                    </div>
                </div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.expressionName != null ?
                            this.inputNode.val(this.expressionName) :
                            this.clearText();
                    }
                    button_onClick() {
                        Editors.ExpressionEditorDialog.open({
                            callbacks: {
                                ok: (sender, data) => {
                                    let result = _.first(data);
                                    this.inputNode.val(result.name);
                                    this.changeCallback({
                                        expressionId: result.id,
                                        expressionName: result.name
                                    });
                                }
                            }
                        });
                    }
                }
                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">div>
                    <input type="text" />
                    <div role="sample"></
                </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({
                            callbacks: {
                                ok: (sender, data) => {
                                    this.inputNode.val(data.value);
                                    this.source.setFeaturePrimaryValue(data.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 IdentitySelectionEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get identityId() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set identityId(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-identity-selection-editor">
                        <div><input type="text" ${this.source.readOnly ? "disabled" : ""} /></div>
                        <div><button ${this.source.readOnly ? "disabled" : ""}>...</button></div>
                    </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.updateUI();
                    }
                    button_onClick() {
                        PDJS.Shared.Security.IdentityBrowserDialog.open({
                            filters: [PDJS.Core.Views.IdentityFilter.usersOnly()],
                            selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                            callbacks: {
                                ok: (sender, e) => {
                                    this.identityId = _.first(e).accountId;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    updateUI() {
                        this.inputNode.val(this.identityId);
                    }
                }
                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="number" ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}  />
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.val(this.source.getFeaturePrimaryValue(""));
                        this.inputNode.blur(Jade.BrowserEvent.BLUR, (e) => {
                            this.source.setFeaturePrimaryValue(this.inputValue);
                        });
                        this.inputNode.on(Jade.BrowserEvent.KEYDOWN, (e) => {
                            if (e.keyCode == Jade.KeyCode.Period) {
                                e.preventDefault();
                                e.cancelBubble = true;
                            }
                        });
                        this.inputNode.on(Jade.BrowserEvent.KEYPRESS, (e) => {
                            if (!(/^-?\d*(\.\d+)?$/).test(this.inputRawValue)) {
                                e.preventDefault();
                                e.cancelBubble = true;
                            }
                        });
                    }
                }
                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.Dialog {
                    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 `
            <div class="-fb-lde-selection-editor-dialog">
                <div role="grid"></div>
                <div>
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                    }
                    getWindowOptions() {
                        return {
                            title: "List Data Extension Selector",
                            height: 400,
                            width: 600,
                            maximized: false
                        };
                    }
                    static open(options, windowOptions) {
                        return new LdeSelectionDialog(options, windowOptions);
                    }
                    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({
                                command: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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.extensionsViewStateId;
                                this.grid_init();
                            },
                            error: (e) => {
                                this.close();
                            }
                        });
                    }
                }
                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 FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get extensionNameProperty() {
                        return _.camelCase(this.source.state.get("extensionNameProperty"));
                    }
                    get extensionName() {
                        return this.source.getFeatureValue(this.extensionNameProperty);
                    }
                    template() {
                        return `<div class="-fb-lde-selection-editor">
                    <div><input type="text" readonly disabled /></div>
                    <div><button ${this.source.readOnly || !this.source.enabled ? "disabled" : ""}>...</button></div>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.inputNode.val(this.extensionName);
                    }
                    button_onClick() {
                        Editors.LdeSelectionDialog.open({
                            callbacks: {
                                ok: (sender, data) => {
                                    let result = _.first(data);
                                    this.inputNode.val(result.name);
                                    this.source.setFeatureValue(this.extensionNameProperty, result.name);
                                    this.source.setFeaturePrimaryValue(result.id);
                                }
                            }
                        });
                    }
                }
                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());
                        });
                    }
                }
                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) => {
                                    e.iconVisible = false;
                                    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) {
                class ResourceSelectionEditor extends FeatureBlendJS.Views.MicroEditorBase {
                    get buttonNode() {
                        return this.node.find("button");
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    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);
                    }
                    template() {
                        return `<div class="-fb-resource-selection-editor">
                    <div><input type="text" readonly disabled /></div>
                    <div><button ${this.source.readOnly ? "disabled" : ""}>...</button></div>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.buttonNode.on(Jade.BrowserEvent.CLICK, () => {
                            this.button_onClick();
                        });
                        this.updateUI();
                    }
                    button_onClick() {
                        PDJS.Manage.Resources.SelectFileDialog.open({
                            extensions: [".html", ".htm"],
                            callbacks: {
                                ok: (sender, e) => {
                                    let file = _.first(e);
                                    this.resourceId = file.id;
                                    this.resourcePath = `${file.name}`;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    updateUI() {
                        this.inputNode.val(`${this.hasResource ? this.resourcePath : "No Resource Selected"}`);
                        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 supportsDefault() {
                        return this.defaultTextProperty != null;
                    }
                    get defaultTextProperty() {
                        return this.source.state.get("defaultProperty");
                    }
                    get textProperty() {
                        return this.source.state.get("textProperty");
                    }
                    get viewStateIdProperty() {
                        return this.source.state.get("viewStateIdProperty");
                    }
                    get text() {
                        return this.source.getFeatureValue(this.textProperty);
                    }
                    set text(value) {
                        this.source.setFeatureValue(this.textProperty, value);
                    }
                    get scriptName() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set scriptName(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    get defaultText() {
                        return this.supportsDefault ?
                            this.source.getFeatureValue(this.defaultTextProperty) :
                            "None";
                    }
                    get hasScript() {
                        return !Jade.String.isNullOrWhiteSpace(this.scriptName);
                    }
                    get viewStateId() {
                        return this.source.getFeatureValue(this.viewStateIdProperty);
                    }
                    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.scriptName)) {
                                this.clearButtonNode.show();
                            }
                        });
                    }
                    popupButton_onClick() {
                        PDJS.Manage.Reports.RuleScriptSelectionDialog.open({
                            viewStateId: this.viewStateId,
                            callbacks: {
                                ok: (sender, e) => {
                                    this.text = e.name;
                                    this.scriptName = e.id;
                                    this.updateUI();
                                }
                            }
                        });
                    }
                    clearButton_onClick() {
                        this.text = "";
                        this.scriptName = null;
                        this.updateUI();
                    }
                    setIcon() {
                        if (this.scriptName == null && this.supportsDefault) {
                            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");
                        }
                    }
                    setInputText(name) {
                        let isNull = Jade.String.isNullOrWhiteSpace(this.scriptName);
                        let isNullWithDefault = isNull && this.supportsDefault;
                        let isNullWithoutDefault = isNull && !this.supportsDefault;
                        switch (true) {
                            case isNullWithoutDefault:
                                this.inputNode.val(this.defaultText);
                                this.inputNode.addClass("-fb-no-selection");
                                break;
                            case isNullWithDefault:
                                this.inputNode.val(this.defaultText);
                                break;
                            default:
                                this.inputNode.val(name || this.text);
                                this.inputNode.removeClass("-fb-no-selection");
                                break;
                        }
                    }
                    updateUI() {
                        this.showImage(true);
                        this.showPopUpButton(true);
                        this.showClearButton(this.hasScript);
                        this.setIcon();
                        this.setInputText(this.text);
                        this.imageNode.css({
                            opacity: this.hasScript ? 1 : .5
                        });
                        this.hasScript ?
                            this.inputNode.removeClass("-pdjs-no-value") :
                            this.inputNode.addClass("-pdjs-no-value");
                    }
                }
                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 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();
                    }
                    upload_init() {
                        this.m_upload = new PDJS.Shared.UI.Controls.UploadInput({
                            onUploadComplete: (e) => {
                                this.fileId = e.target_name;
                                this.fileName = e.name;
                            }
                        });
                        this.controls.add(this.m_upload);
                        this.m_upload.setLabelText(this.fileName);
                    }
                }
                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 allowDataTags() {
                        return this.source.state.get("allowDataTags", false);
                    }
                    get inputNode() {
                        return this.node.find("input");
                    }
                    get maskInputNode() {
                        return this.node.find("div");
                    }
                    get value() {
                        return this.source.getFeaturePrimaryValue();
                    }
                    set value(value) {
                        this.source.setFeaturePrimaryValue(value);
                    }
                    template() {
                        return `<div class="-fb-string-editor">
                    <div></div>
                    <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.maskInputNode.hide();
                        if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                            this.inputNode.val(this.value);
                            this.maskInputNode.html(Shared.DataTags.format(this.value));
                        }
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.value = this.inputNode.val();
                        });
                        if (this.allowDataTags) {
                            this.configureForDataTags();
                        }
                    }
                    configureForDataTags() {
                        this.maskInputNode.show();
                        this.inputNode.on(Jade.BrowserEvent.KEYUP, () => {
                            this.maskInputNode.html(Shared.DataTags.format(this.inputNode.val()));
                        });
                        this.inputNode.css({
                            color: "transparent"
                        });
                    }
                }
                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) {
                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: "white-no-padding",
                                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,
                            callbacks: {
                                ok: (sender, e) => {
                                    this.updateList(e);
                                }
                            }
                        });
                    }
                    showTagPatternDialog(pattern = "") {
                        Editors.TagPatternDialog.open({
                            pattern: pattern,
                            callbacks: {
                                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.Dialog {
                    constructor(options, windowOptions) {
                        super(options, windowOptions);
                    }
                    get allowWildcards() {
                        return this.state.get("allowWildcards", false);
                    }
                    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 `
            <div class="-pdjs-tag-list-dialog">
                <div role="grid"></div>
                <div role="deck">
                    <button
                        data-command="ok"
                        class="-jadejs-button">
                        OK
                    </button>
                    <button 
                        data-command="cancel"
                        class="-jadejs-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",
                            entityId: null,
                            identity: null,
                            windowOptions: {
                                actions: ["close"],
                                height: "400px",
                                minHeight: "300px",
                                width: "500px",
                                minWidth: "300px",
                                title: true,
                                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.window.destroyContext();
                            this.close({
                                command: "ok",
                                data: selections
                            });
                        }
                        else {
                            this.close();
                        }
                    }
                    static open(options, windowOptions) {
                        return new TagListDialog(options, windowOptions);
                    }
                }
                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 TagPatternDialog extends Jade.UI.Dialog {
                    constructor(options, windowOptions) {
                        super(options, windowOptions);
                    }
                    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 `
            <div class="-pdjs-tag-pattern-dialog">
                <div role="input"></div>
                <div role="deck">
                    <button
                        data-command="ok"
                        class="-jadejs-button">
                        OK
                    </button>
                    <button 
                        data-command="cancel"
                        class="-jadejs-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.window.setOptions({
                            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`,
                            entityId: null,
                            identity: null,
                            windowOptions: {
                                actions: ["close"],
                                height: "105px",
                                width: "400px",
                                title: true,
                                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.window.destroyContext();
                            this.close({
                                command: "ok",
                                data: {
                                    oldPattern: this.pattern,
                                    newPattern: this.m_input.value
                                }
                            });
                        }
                    }
                    static open(options, windowOptions) {
                        return new TagPatternDialog(options, windowOptions);
                    }
                }
                Editors.TagPatternDialog = TagPatternDialog;
            })(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 maskInputNode() {
                        return this.node.find("div");
                    }
                    template() {
                        return `<div class="-fb-text-area-editor">
                    <div></div>
                    <textarea ${this.source.readOnly ? "readonly" : ""} ${!this.source.enabled ? "disabled" : ""}></textarea>
                </div>`;
                    }
                    focus() {
                        super.focus();
                        this.inputNode.focus().select();
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                            this.source.setFeaturePrimaryValue(this.inputNode.val());
                        });
                        this.inputNode.on(Jade.BrowserEvent.KEYUP, () => {
                            this.writeTextToMask();
                        });
                        this.inputNode.on(Jade.BrowserEvent.SCROLL, () => {
                            this.syncScrollPositions();
                        });
                        this.writeTextToInput();
                        this.writeTextToMask();
                        this.inputNode.css({
                            minHeight: `${this.height}px`
                        });
                        this.maskInputNode.css({
                            minHeight: `${this.height}px`
                        });
                    }
                    syncScrollPositions() {
                        this.maskInputNode.scrollLeft(this.inputNode.scrollLeft());
                        this.maskInputNode.scrollTop(this.inputNode.scrollTop());
                    }
                    writeTextToInput() {
                        this.inputNode.val(this.source.getFeaturePrimaryValue());
                    }
                    writeTextToMask() {
                        if (this.allowDataTags) {
                            this.maskInputNode.html(Shared.DataTags.format(this.inputNode.val()));
                        }
                        else {
                            this.maskInputNode.html(this.inputNode.val());
                        }
                    }
                }
                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">
                        <div data-controls>
                            <select role="fixed"></select>
                        </div>
                    </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`,
                            args: {
                                targetId: this.source.getFeaturePrimaryValue(),
                                targetType: "ProspectDirector.Web.Manage.Modules.Views.ViewUIO",
                                arbiterType: "ProspectDirector.Web.Manage.Modules.Views.ViewArbiter",
                                properties: {
                                    designerOnly: true
                                }
                            },
                            callbacks: {
                                "ok": (sender, e) => {
                                }
                            }
                        }, {
                            height: 550,
                            width: 700,
                        });
                        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.setDimensions(args.height, 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;
                        }
                        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("ace/theme/chrome");
                            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();
                            });
                        }
                        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");
                        }
                        template() {
                            return `<div class="-fb-rich-text-editor">
                        <div role="container">
                            <textarea></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`,
                                document_base_url: Jade.Path.resolve("~/scripts/pdjs/external/tinymce"),
                                apply_source_formatting: true,
                                plugins: "link hr textcolor colorpicker",
                                menubar: false,
                                statusbar: false,
                                toolbar: [
                                    "undo redo | fontselect 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;
                    Jade.Application.onStart(() => {
                        FeatureBlendJS.FeatureBlend.addEditorType("ProspectDirector.Web.UI.FeatureSets.Editors.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 Files;
        (function (Files) {
            class EditFiles {
                static showProperties(options) {
                    PDJS.Shared.Features.FeatureDialogForNhib.open({
                        args: {
                            targetId: parseInt(options.entityId),
                            showApplyButton: true,
                            arbiterType: "ProspectDirector.Web.Hub.Files.FilePropertiesDialogArbiter",
                            targetType: "ProspectDirector.Web.Hub.Files.FilePropertiesDialogUIO"
                        },
                        callbacks: {
                            ok: (sender, e) => {
                                sender.destroyContext();
                                if (_.isFunction(options.onSave)) {
                                    options.onSave(sender, e);
                                }
                            }
                        }
                    }, { height: "500px", width: "680px" });
                }
            }
            Files.EditFiles = EditFiles;
        })(Files = Shared.Files || (Shared.Files = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
PDJS.JS.ProspectDirector.Types.Core.Dialogs = {};
PDJS.Application.onStart(() => {
    PDJS.JS.ProspectDirector.Types.Core.Dialogs = {};
    PDJS.JS.ProspectDirector.Types.Core.Dialogs.QuickFilterEditor =
        new (PDJS.JS.ProspectDirector.Types.Core.Dialog.extend({
            init: function () {
                this._super("QuickFilterEditor", "Filter Editor", Jade.Path.resolve("~/viewfilter/editquick"));
            }
        }));
    PDJS.JS.ProspectDirector.Types.Core.Dialogs.FilterEditor =
        new (PDJS.JS.ProspectDirector.Types.Core.Dialog.extend({
            init: function () {
                this._super("FilterEditor", "Filter Editor", Jade.Path.resolve("~/viewfilter/edit"));
            }
        }));
});
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 Navigate;
        (function (Navigate) {
            class NavigatorValidator extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                }
                get changesCallback() {
                    return this.state.get("changes", () => { return false; });
                }
                hasChanges() {
                    return this.changesCallback();
                }
                reset() {
                    return;
                }
            }
            Navigate.NavigatorValidator = NavigatorValidator;
        })(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 CanvasEditorValidator extends Navigate.NavigatorValidator {
                constructor(options) {
                    super(options);
                }
                get canvas() {
                    return this.state.get("canvas");
                }
                hasChanges() {
                    return this.canvas.hasChanges;
                }
            }
            Navigate.CanvasEditorValidator = CanvasEditorValidator;
        })(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 FeatureEditorValidator extends Navigate.NavigatorValidator {
                constructor(options) {
                    super(options);
                    this.editor.rootModel.context.featureSet.onValueChanged((e) => {
                        this.m_hasChanges = true;
                    });
                }
                get editor() {
                    return this.state.get("editor");
                }
                hasChanges() {
                    return this.m_hasChanges;
                }
                reset() {
                    this.m_hasChanges = false;
                }
            }
            Navigate.FeatureEditorValidator = FeatureEditorValidator;
        })(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 Navigator extends PDJS.Core.Model {
                constructor(options) {
                    super(options);
                    this.validators = new Navigate.NavigatorValidatorCollection();
                    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 validators() {
                    return this.m_validators;
                }
                set validators(value) {
                    this.m_validators = value;
                }
                go(e) {
                    this.attemptNavigate(e);
                }
                addAnchorNavigationHandlers() {
                    $(document).on("click", "A", (e) => {
                        if (this.isObservableAnchor(e.target)) {
                            this.go({
                                directive: e,
                            });
                        }
                    });
                }
                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()) {
                        this.promptCallback(fn);
                        error();
                        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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNo,
                        title: "Unsaved Changes Detected",
                        message: "There are unsaved changes. Discard changes and continue?",
                        select: (e) => {
                            if (e.button == Jade.UI.MessageDialogButton.yes) {
                                this.validators.reset();
                                fn();
                            }
                            e.close();
                        }
                    });
                }
            }
            Navigate.Navigator = Navigator;
        })(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 NavigatorValidatorCollection extends Jade.Collection {
                hasChanges() {
                    let result = false;
                    this.each(validator => {
                        if (!result) {
                            result = validator.hasChanges();
                        }
                    });
                    return result;
                }
                reset() {
                    this.each(validator => {
                        validator.reset();
                    });
                }
            }
            Navigate.NavigatorValidatorCollection = NavigatorValidatorCollection;
        })(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_scripts = new Plugins.PluginScriptsCollection();
                }
                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 scripts() {
                    return this.m_scripts;
                }
                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]);
                    }
                    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 PluginRouter {
                constructor() {
                    this.addRoutes();
                }
                routeHandler(e) {
                    var plugin = null;
                    var module = null;
                    var pluginId = this.params["pluginId"];
                    var moduleId = this.params["moduleId"];
                    var fqnId = pluginId + (moduleId == null ? "" : ":" + moduleId);
                    if (pluginId == null) {
                        return;
                    }
                    plugin = PDJS.Shared.Plugins.PluginManager.instance.getPlugin(pluginId);
                    if (plugin != null) {
                        if (moduleId == null) {
                            module = plugin.get_scripts().get_default();
                        }
                        else {
                            module = plugin.get_scripts().get(moduleId);
                        }
                    }
                    if (module == null) {
                        return;
                    }
                    module.route = window.location.hash;
                    PDJS.JS.PD.context
                        .get_global()
                        .get_events()
                        .publish("Module:Request", $.extend({}, module, {
                        id: fqnId
                    }));
                }
                addRoutes() {
                    window["Path"].map("#/plugin/:pluginId(/:moduleId)").to(this.routeHandler);
                }
            }
            Plugins.PluginRouter = PluginRouter;
        })(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 PluginScriptsCollection {
                constructor() {
                    this.m_scripts = {};
                }
                get default() {
                    return this.m_defaultScript;
                }
                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 result = false;
                    for (let key in this.m_scripts) {
                        if (this.m_scripts.hasOwnProperty(key)) {
                            result = true;
                            break;
                        }
                    }
                    return result;
                }
            }
            Plugins.PluginScriptsCollection = PluginScriptsCollection;
        })(Plugins = Shared.Plugins || (Shared.Plugins = {}));
    })(Shared = PDJS.Shared || (PDJS.Shared = {}));
})(PDJS || (PDJS = {}));
var PDJS;
(function (PDJS) {
    var Shared;
    (function (Shared) {
        var Security;
        (function (Security) {
            class AceEditor2 extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                }
                get ddl() {
                    return this.node.find("select");
                }
                get isBasicView() {
                    return parseInt(this.ddl.find(":selected").attr("value")) == 1;
                }
                get enabled() {
                    return this.state.get("enabled", true);
                }
                set enabled(value) {
                    this.state.set("enabled", value);
                }
                get permissions() {
                    return this.state.get("permissions", []);
                }
                set permissions(value) {
                    this.state.set("permissions", value);
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get gridNode() {
                    return this.node.find(".-pd-ace-editor-grid");
                }
                loadAce(ace) {
                    this.clearAllCheckboxes();
                    if (ace == null) {
                        return;
                    }
                    this.m_ace = _.extend({ allow: 0, deny: 0 }, ace);
                    this.filterPermissions();
                    this.updateCheckBoxesToReflectEnabledState();
                }
                loadPermissions(permissions) {
                    this.permissions = permissions || this.permissions;
                    if (!this.hasExpandedPermissions()) {
                        this.ddl.hide();
                    }
                    this.filterPermissions(true);
                }
                redraw() {
                    this.m_grid.redraw();
                    this.loadAce(this.m_ace);
                }
                template() {
                    return `
                <div class='-pd-ace-editor'>
                    <div class='-pd-ace-editor-header'>
                        <div>
                            Permissions
                        </div>
                        <div>
                            <select data-id='permissions-type'>
                                <option value='1'>Basic</option>
                                <option value='0'>Expanded</option>
                            </select>
                        </div>
                    </div>
                    <div data-id='grid' class='-pd-ace-editor-grid' style='border:1px solid #CCCCCC;'></div>
                </div>
            `;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.grid_init();
                    this.loadPermissions();
                    this.ddl.on(Jade.BrowserEvent.CHANGE, _.bind(this.ddl_onChange, this));
                    this.node.find("div[data-id=grid]").on(Jade.BrowserEvent.CHANGE, ".allow input[type=checkbox]", _.bind(this.checkbox_allow_onChange, this));
                    this.node.find("div[data-id=grid]").on(Jade.BrowserEvent.CHANGE, ".deny input[type=checkbox]", _.bind(this.checkbox_deny_onChange, this));
                }
                grid_init() {
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.gridNode,
                        selectionMode: "none",
                        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' value='" + (e.value == null ? -1 : e.value) + "' />";
                                }
                            })
                        ]
                    });
                }
                updateCheckBoxesToReflectEnabledState() {
                    if (this.enabled) {
                        this.enableAllCheckboxes();
                    }
                    else {
                        this.disableAllCheckboxes();
                    }
                }
                ddl_onChange() {
                    this.filterPermissions(this.isBasicView);
                    this.updateCheckBoxesToReflectEnabledState();
                }
                filterPermissions(isBasic) {
                    isBasic = isBasic == null ? this.isBasicView : isBasic;
                    let data = _.filter(this.permissions, function (e) {
                        return e.isBasic == isBasic;
                    });
                    this.m_grid.get_dataSource().data(data);
                    if (this.m_ace == null) {
                        this.disableAllCheckboxes();
                    }
                    else {
                        this.enableAllCheckboxes();
                    }
                    this.updateCheckboxesToMatchAce();
                }
                checkbox_allow_onChange(e) {
                    let checkbox = $(e.currentTarget);
                    let permission = this.checkbox_getPermissionValue(checkbox);
                    let role = "allow";
                    this.checkbox_clearAnalog(checkbox);
                    this.updateAce(checkbox, role);
                    this.setCheckboxSpecialPermissionState(checkbox, false);
                }
                checkbox_deny_onChange(e) {
                    let checkbox = $(e.currentTarget);
                    let permission = this.checkbox_getPermissionValue(checkbox);
                    let role = "deny";
                    this.checkbox_clearAnalog(checkbox);
                    this.updateAce(checkbox, role);
                    this.setCheckboxSpecialPermissionState(checkbox, false);
                }
                checkbox_clearAnalog(target) {
                    let isAllow = target.closest(".permission-check").hasClass("allow");
                    let checkbox = null;
                    if (isAllow) {
                        checkbox = target.closest("tr").find(".deny input[type=checkbox]");
                    }
                    else {
                        checkbox = target.closest("tr").find(".allow input[type=checkbox]");
                    }
                    checkbox.prop("checked", false);
                    this.setCheckboxSpecialPermissionState(checkbox, false);
                }
                checkbox_setChecked(role) {
                    if (this.m_ace == null) {
                        return;
                    }
                    _.each(this.getCheckboxesAndValues(role), (item) => {
                        var hasSpecialPermissions = this.hasSpecialPermission(role, item.value);
                        ;
                        item.checkbox.prop("checked", (this.m_ace[role] & item.value) === item.value);
                        if (hasSpecialPermissions) {
                            item.checkbox.prop("checked", hasSpecialPermissions);
                        }
                        this.setCheckboxSpecialPermissionState(item.checkbox, hasSpecialPermissions);
                    });
                }
                checkbox_getPermissionValue(element) {
                    let result = 0;
                    let data = this.m_grid.getRowData(element);
                    if (data != null) {
                        result = data.value;
                    }
                    return result;
                }
                updateAce(checkbox, role) {
                    if (this.m_ace == null) {
                        return;
                    }
                    let permission = this.checkbox_getPermissionValue(checkbox);
                    let diametricRole = (role === "allow" ? "deny" : "allow");
                    let check = checkbox.is(":checked");
                    let ace = this.m_ace;
                    if (check) {
                        ace[role] = ace[role] | permission;
                    }
                    else {
                        ace[role] = ace[role] & ~permission;
                    }
                    ace[diametricRole] = ace[diametricRole] & ~permission;
                    this.changeCallback(ace);
                }
                updateCheckboxesToMatchAce() {
                    this.checkbox_setChecked("allow");
                    this.checkbox_setChecked("deny");
                }
                hasSpecialPermission(role, permission) {
                    if (this.m_ace == null) {
                        return;
                    }
                    let acePermission = this.m_ace[role];
                    return ((acePermission & permission) !== permission)
                        && ((acePermission & permission) !== 0);
                }
                getCheckboxesAndValues(role) {
                    let result = [];
                    this.node
                        .find(`div[data-id=grid] .${role} input[type=checkbox]`)
                        .each((index, el) => {
                        result[result.length] = {
                            checkbox: $(el),
                            value: this.checkbox_getPermissionValue($(el))
                        };
                    });
                    return result;
                }
                setCheckboxSpecialPermissionState(checkbox, hasSpecialPermissions) {
                    checkbox.css({
                        opacity: hasSpecialPermissions ? ".3" : "1"
                    });
                }
                hasExpandedPermissions() {
                    var found = _.find(this.permissions, function (item) {
                        return item["isBasic"] == false;
                    });
                    return found != null;
                }
                disableAllCheckboxes() {
                    this.node.find('input:checkbox').attr('disabled', 'disabled');
                }
                enableAllCheckboxes() {
                    this.node.find('input:checkbox').removeAttr('disabled');
                }
                clearAllCheckboxes() {
                    this.node.find('input:checkbox').removeAttr('checked');
                }
            }
            Security.AceEditor2 = AceEditor2;
        })(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.Dialog {
                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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">
                    
                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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));
                }
                getWindowOptions() {
                    return {
                        title: "Identity Browser",
                        height: 400,
                        width: 600,
                        maximized: false
                    };
                }
                static open(options, windowOptions) {
                    return new IdentityBrowserDialog(options, windowOptions);
                }
                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({
                            command: "ok",
                            data: this.selections
                        });
                    }
                    else {
                        Jade.UI.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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;
                        }
                    });
                }
            }
            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 LoginDialog extends Jade.UI.Dialog {
                constructor() {
                    super({}, {});
                }
                get loginButtonNode() {
                    return this.node.find("button[data-id=login]");
                }
                static get instance() {
                    if (this.m_instance == null) {
                        this.m_instance = new LoginDialog();
                    }
                    return this.m_instance;
                }
                static set instance(value) {
                    this.m_instance = value;
                }
                static get opened() {
                    return this.m_instance != null;
                }
                get userNameLabelNode() {
                    return this.node.find("label[role=username]");
                }
                get userNameNode() {
                    return this.node.find("input[role=username]");
                }
                get passwordLabelNode() {
                    return this.node.find("label[role=password]");
                }
                get passwordNode() {
                    return this.node.find("input[role=password]");
                }
                get errorNode() {
                    return this.node.find(".-pd-account-box-error");
                }
                get spinnerNode() {
                    return this.node.find("img[role=spinner]");
                }
                template() {
                    return `
                <div style="position:absolute;top:0;right:0;bottom:0;left:0;box-sizing:border-box;background-color:#FFFFFF;">

                    <div style="position:absolute;top:40px;right:40px;bottom:40px;left:40px;box-sizing:border-box;">

                        <div data-controls
                            style="position:absolute;top:0;bottom:44px;left:0;right:0;font-size:14px;">
                    
                            <div style="border:1px solid black;border-width:0 0 1px 0;padding-bottom:5px;margin-bottom:15px;font-size:20px;font-weight:bold;">Session Expired</div>

                            <div style="margin-bottom:5px;">Please login again to resume your session.</div>
                            <form>
                            <label class="-pd-account-box-label" role="username">User Name</label><br>
                            <input class="-pd-account-box-textbox" role="username" type="text" autocomplete="username" name="username" value=""><br>
                            <label class="-pd-account-box-label" role="password" autocomplete="current-password" name="password">Password</label><br>
                            <input class="-pd-account-box-textbox" role="password" type="password"><br>
                            </form>
                            <div class="-pd-account-box-error" style="color:red;margin-top:10px;margin-bottom:5px;height:24px;line-height:24px;"></div>
                        </div>
                        <div 
                            style="position:absolute;bottom:0;left:0;right:0;text-align:right;">
                            <img src="${Jade.IconSet.get("pd").resolve("ICON_CIRCLE_ANIMATED_36X36.GIF", Jade.IconSetSizeSpecificDirectory.misc)}" role="spinner" style="height:20px;width:20px;inline-block;"/>
                            <button 
                                data-id="login"  
                                class="-jadejs-button"
                                style="margin-right:5px;">
                                Login
                            </button>
                        </div>

                    </div>

                </div>`;
                }
                close(options) {
                    super.close(options);
                    LoginDialog.instance = null;
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.spinnerNode.css({
                        position: "relative",
                        top: "4px"
                    });
                    this.spinnerNode.hide();
                    this.userNameLabelNode.css({
                        marginTop: "5px",
                        padding: "3px 3px 3px 0",
                        fontSize: "12px",
                        fontFamily: "Arial",
                        display: "inline-block",
                        height: "20px",
                        lineHeight: "20px"
                    });
                    this.userNameNode.css({
                        padding: "4px",
                        fontSize: "12px",
                        fontFamily: "Arial",
                        border: "1px solid #aaa",
                        boxSizing: "border-box",
                        width: "100%",
                        height: "26px",
                        lineHeight: "22px"
                    });
                    this.passwordLabelNode.css({
                        marginTop: "5px",
                        padding: "3px 3px 3px 0",
                        fontSize: "12px",
                        fontFamily: "Arial",
                        display: "inline-block",
                        height: "20px",
                        lineHeight: "20px"
                    });
                    this.passwordNode.css({
                        padding: "4px",
                        fontSize: "12px",
                        fontFamily: "Arial",
                        border: "1px solid #aaa",
                        boxSizing: "border-box",
                        width: "100%",
                        height: "26px",
                        lineHeight: "22px"
                    });
                    this.loginButtonNode.on(Jade.BrowserEvent.CLICK, _.bind(this.login_onClick, this));
                    this.userNameNode.on(Jade.BrowserEvent.KEYPRESS, (e) => {
                        if (e.keyCode == Jade.KeyCode.Enter) {
                            this.login_onClick();
                        }
                    });
                    this.passwordNode.on(Jade.BrowserEvent.KEYPRESS, (e) => {
                        if (e.keyCode == Jade.KeyCode.Enter) {
                            this.login_onClick();
                        }
                    });
                }
                getWindowOptions() {
                    return {
                        title: false,
                        height: 340,
                        width: 400,
                        minHeight: 250,
                        minWidth: 250,
                        resizable: false,
                        actions: []
                    };
                }
                login_onClick() {
                    this.spinnerNode.show();
                    if (Jade.String.isNullOrWhiteSpace(this.userNameNode.val())) {
                        this.errorNode.text("User Name is required.");
                        return;
                    }
                    if (Jade.String.isNullOrWhiteSpace(this.passwordNode.val())) {
                        this.errorNode.text("Password is required.");
                        return;
                    }
                    let userName = this.userNameNode.val();
                    let loginWithDifferentUsername = false;
                    userName.toLowerCase() !== PDJS.Shared.Environment
                        .current
                        .user
                        .accountName
                        .toLowerCase();
                    this.loginButtonNode.prop("disabled", true);
                    PDJS.Ajax.call({
                        type: "POST",
                        url: Jade.Path.resolve("~/Shared/Account/Relogin"),
                        contentType: "application/json",
                        data: JSON.stringify({
                            userName: this.userNameNode.val(),
                            password: this.passwordNode.val()
                        }),
                        success: (e, status, jqXHR) => {
                            if (e.error === null) {
                                PDJS.Shared.SessionState.instance.resetMonitor(loginWithDifferentUsername);
                                if (loginWithDifferentUsername) {
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, Shared.SessionState.interval);
                                }
                                else {
                                    this.close();
                                }
                            }
                            else {
                                this.loginButtonNode.prop("disabled", false);
                                this.errorNode.text(e.error);
                                jqXHR.suppressEvent = true;
                            }
                        },
                        error: () => {
                            this.loginButtonNode.prop("disabled", false);
                        },
                        complete: () => {
                            this.spinnerNode.hide();
                        }
                    });
                }
                static open() {
                    return LoginDialog.instance;
                }
            }
            Security.LoginDialog = LoginDialog;
        })(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.Shared.Environment.current.user.id,
                        userDisplayName: PDJS.Shared.Environment.current.user.id
                    });
                }
                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.node.disableTextSelection();
                    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 parseInt(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: "Add Users and Groups",
                        filters: [
                            PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
                        ],
                        callbacks: {
                            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.MessageDialog.open({
                        dialogStyle: Jade.UI.MessageDialogStyle.Error,
                        dialogButtons: Jade.UI.MessageDialogButtonStyle.YesNo,
                        title: "Cannot Remove ACE",
                        message: `Inherited entries cannot be removed.<br/><br/>Do you want to set the entry to use its inherited permissions instead?`,
                        select: (e) => {
                            e.close();
                            if (e.button === Jade.UI.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) {
                    window["ProspectDirector"].Modules.Security.AclAdvancedDialog.Dialog.show({
                        params: {
                            id: this.accessControl.securableId,
                            hasChanges: this.accessControl.acl.aces.haveAcesChanged()
                        }
                    });
                }
                getDefaultValuesForProps() {
                    return {
                        id: "advanced",
                        tooltip: "Advanced",
                        label: "Advanced",
                        enabled: true,
                        display: "label",
                        iconSetId: "pd"
                    };
                }
            }
            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(),
                        callbacks: {
                            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.Shared.Environment.current.user.id,
                            name: PDJS.Shared.Environment.current.user.accountName,
                            displayName: PDJS.Shared.Environment.current.user.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 EffectivePermissionsDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(options);
                }
                get aces() {
                    return this.state.get("aces");
                }
                get identity() {
                    return this.state.get("identity");
                }
                set identity(value) {
                    this.state.set("identity", value);
                }
                get entityId() {
                    return this.state.get("entityId");
                }
                get closeButton() {
                    return this.node.find("BUTTON[data-id=button-close]");
                }
                template() {
                    return `
                <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.effectivePermissionsGrid_init();
                    this.effectivePermissionsSourcesGrid_init();
                    this.identitySelector_init();
                    this.closeButton.on(Jade.BrowserEvent.CLICK, _.bind(this.closeButton_onClick, this));
                }
                getDefaultOptions() {
                    return {
                        title: "Effective Permissions",
                        permissions: [],
                        entityId: null,
                        identity: null,
                        windowOptions: {
                            actions: [],
                            height: "575px",
                            minHeight: "300px",
                            width: "500px",
                            minWidth: "300px",
                            title: true,
                            resizable: true
                        }
                    };
                }
                identitySelector_init() {
                    this._identitySelector = new PDJS.JS.PD.Web.UI.Controls.SelectionBox({
                        container: this.node.find("[data-role=identity-selector-container]"),
                        change: _.bind(this.identitySelector_onChange, this),
                        callback: (e) => {
                            PDJS.Shared.Security.IdentityBrowserDialog.open({
                                selectionMode: PD.Web.UI.Controls.GridSelectionMode.single,
                                title: "Select User or Group",
                                filters: [
                                    PDJS.Core.Views.IdentityFilter.excludeAllAdmins()
                                ],
                                callbacks: {
                                    ok: (sender, e) => {
                                        this.identity = _.first(e);
                                        this._identitySelector.setSelection(this.identity.id, this.identity.name);
                                    }
                                }
                            });
                        }
                    });
                    if (this.identity != null) {
                        this._identitySelector.setSelection(this.identity.id, this.identity.displayName || this.identity.name);
                    }
                }
                identitySelector_onChange(e) {
                    PDJS.Ajax.call({
                        type: "POST",
                        contentType: "application/json",
                        url: Jade.Path.resolve("~/Shared/Security/GetEffectivePermissions"),
                        data: JSON.stringify({
                            entityId: this.entityId,
                            identityId: e.value,
                            aces: JSON.stringify(this.aces)
                        }),
                        success: (e) => {
                            this._effectivePermissionsGrid.load(e);
                        }
                    });
                }
                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({
                        command: "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",
                                readOnly: true,
                                attributes: {
                                    class: "permission-check allow"
                                }
                            }),
                            new PD.Web.UI.Controls.GridCheckboxColumn({
                                title: "Deny",
                                field: "denied",
                                width: "40px",
                                readOnly: 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 UI;
        (function (UI) {
            class ControlCommander {
                constructor(options) {
                    this.m_previous = {
                        checked: null,
                        display: null,
                        enabled: null,
                        icon: null,
                        label: null,
                        tooltip: null,
                        visible: null
                    };
                    this.m_state = new Jade.StateBag(options);
                    this.subscribeToCommand();
                }
                get changeCallback() {
                    return this.state.get("change", () => { });
                }
                get checked() {
                    return this.getValue("checked", false);
                }
                get commandId() {
                    return this.state.get("commandId");
                }
                get commandUid() {
                    return this.state.get("commandUid");
                }
                set commandUid(value) {
                    this.state.set("commandUid", value);
                }
                get subscriber() {
                    return this.m_subscriber;
                }
                set subscriber(value) {
                    this.m_subscriber = value;
                }
                get display() {
                    return this.getValue("display", "");
                }
                get enabled() {
                    return this.getValue("enabled", true);
                }
                get icon() {
                    return this.getValue("icon", null);
                }
                get isIconVisible() {
                    return this.showIcon();
                }
                get isLabelVisible() {
                    return this.showLabel();
                }
                get label() {
                    return this.getValue("label", "");
                }
                get previous() {
                    return this.m_previous;
                }
                get state() {
                    return this.m_state;
                }
                get tooltip() {
                    return this.getValue("tooltip", true);
                }
                get visible() {
                    return this.getValue("visible", true);
                }
                get value() {
                    return this.getValue("value", null);
                }
                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.subscriber.subscribe(this.commandId, () => {
                        this.changeCallback();
                    });
                    if (this.subscriber.command != null) {
                        this.commandUid = this.subscriber.command.UID;
                    }
                    if (this.subscriber.command == null) {
                        throw `Cannot resolve command with ID of "${this.commandId}".`;
                    }
                }
                getValue(id, defaultValue = null) {
                    let result = this.subscriber ?
                        this.subscriber[id] :
                        this.state.get(id);
                    if (result == null) {
                        result = defaultValue;
                    }
                    return result;
                }
                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);
                }
            }
            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) {
            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;
                }
                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() {
                    let styleNode = $(`#${this.idStyleTag}`);
                    styleNode.remove();
                    let styles = [];
                    Object.keys(this.m_styles).forEach(name => {
                        styles[styles.length] = this.getStyle(name, this.styles[name]);
                    });
                    $(document.head).append(`<style id="${this.idStyleTag}">${styles.join(" ")}</style>`);
                }
                remove() {
                    $(`#${this.idStyleTag}`).remove();
                }
                getStyle(name, style) {
                    let result = [];
                    Object.keys(style).forEach(name => {
                        result[result.length] = `${this.getFormattedAttributeName(name)}:${style[name]}`;
                    });
                    return `${name} {${result.join(";")}}`;
                }
                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 items() {
                        return this.state.get("items");
                    }
                    set items(value) {
                        this.state.update("items", value);
                    }
                    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;
                    }
                    list_init() {
                        this.m_list = new Controls.BatchFieldList({
                            items: this.items,
                            showCheckboxes: this.showCheckboxes,
                            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,
                            callbacks: {
                                ok: (sender, e) => {
                                    sender.close();
                                    _.each(this.items, (item) => {
                                        item.selected = false;
                                    });
                                    _.each(e, (item) => {
                                        if (_.findIndex(this.items, { id: item.id }) < 0) {
                                            this.items[this.items.length] = item;
                                        }
                                    });
                                    this.items = _.sortBy(this.items, ["label"]);
                                    this.list.refresh();
                                }
                            }
                        }, {
                            height: this.dialogHeight,
                            width: this.dialogWidth
                        });
                    }
                }
                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 popUpButtonNode() {
                        return this.node.find("button[role=popup]");
                    }
                    get list() {
                        return this.state.get("list");
                    }
                    get showCheckboxes() {
                        return this.state.get("showCheckboxes", false);
                    }
                    template() {
                        let icon = Jade.IconSet.get("pd")
                            .resolve("sort_desc.png", Jade.IconSetSizeSpecificDirectory.misc);
                        return `<div role="deck">
                        <button role="dialog" tabIndex="${this.tabIndex}">
                            Select...
                        </button>
                        <button role="popup" tabIndex="${this.tabIndex}">
                            <img src="${icon}"/>
                        </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();
                    }
                    popUp_init() {
                        this.m_popUp =
                            new PDJS.Shared.UI.Controls.PopUp({
                                anchor: this.popUpButtonNode,
                                width: 150,
                                tipped: {
                                    skin: "white-no-padding",
                                    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.Dialog {
                    constructor(options, windowOptions) {
                        super(options, windowOptions);
                    }
                    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 `
            <div style="position:absolute;top:10px;left:10px;right:10px;bottom:10px;box-sizing:border-box;">
                <div data-role="grid" style="position:absolute;top:0;left:0;right:0;bottom:34px;border:1px solid #AAAAAA;">

                </div>
                <div style="position:absolute;height:26px;bottom:0;left:0;right:0;text-align:right;">
                    <button data-command="ok" class="-jadejs-button">OK</button>
                    <button data-command="cancel" class="-jadejs-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, windowOptions) {
                        return new BatchFieldDialog(options, windowOptions);
                    }
                    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({
                                command: "ok",
                                data: this.selections
                            });
                        }
                        else {
                            Jade.UI.MessageDialog.open({
                                dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                                dialogButtons: Jade.UI.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 mask() {
                        return this.m_mask;
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get hasValue() {
                        return this.mask != null &&
                            !Jade.String.isNullOrWhiteSpace(this.value);
                    }
                    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();
                    }
                    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({
                            color: "#AAAAAA",
                            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.state.get("items");
                    }
                    get batchFieldListItems() {
                        return this.controls.getByType(Controls.BatchFieldListItem);
                    }
                    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 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);
                    }
                    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: "#AAAAAA"
                        });
                    }
                    addNoItemsMessage() {
                        this.addMessage("No items in list.");
                    }
                }
                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("img");
                    }
                    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() {
                        let img = Jade.IconSet.get("pd")
                            .resolve("cancel.png", Jade.IconSetSizeSpecificDirectory.misc);
                        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>
                            <img src="${img}"/>
                    </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.node.css({
                            gridGap: this.hasGridGap() ? "5px" : "0",
                            padding: this.isLabelVisible() ? "0 15px" : "0 7px",
                            display: this.visible ? "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() {
                        Tipped.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>`;
                        Tipped.create(this.node, content, {
                            skin: "white",
                            showOn: "mouseenter",
                            hideOn: "mouseleave",
                            hideAfter: 200,
                            hideDelay: 0,
                            showDelay: 750,
                            maxWidth: 300,
                            position: "bottommiddle"
                        });
                    }
                    hideTooltip() {
                        Tipped.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 CodeEditor extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                        this.m_changed = false;
                        this.m_silentChanges = false;
                    }
                    get aceEditor() {
                        return this.m_aceEditor;
                    }
                    get changeCallback() {
                        return this.state.get("change", () => { });
                    }
                    get changed() {
                        return this.m_changed;
                    }
                    get fontSize() {
                        return this.aceEditor.getFontSize();
                    }
                    set fontSize(value) {
                        this.aceEditor.setFontSize(value);
                    }
                    get showInvisibles() {
                        return this.aceEditor.getShowInvisibles();
                    }
                    set showInvisibles(value) {
                        this.aceEditor.setShowInvisibles(value);
                    }
                    get showIndents() {
                        return this.aceEditor.getDisplayIndentGuides();
                    }
                    set showIndents(value) {
                        this.aceEditor.setDisplayIndentGuides(value);
                    }
                    get showLineNumbers() {
                        return this.aceEditor.renderer.getShowGutter();
                    }
                    set showLineNumbers(value) {
                        this.aceEditor.renderer.setShowGutter(value);
                    }
                    addMarker(message, startOnLine, endOnLine) {
                        let range = this.createRange(startOnLine, endOnLine);
                        endOnLine = endOnLine || startOnLine;
                        this.aceEditor.session
                            .addMarker(range, "-pd-ace-editor-line-highlight", "fullLine", true);
                        this.aceEditor.focus();
                        this.aceEditor.gotoLine(startOnLine + 1);
                        this.aceEditor.session.setAnnotations([{
                                row: startOnLine,
                                column: 0,
                                text: message || "Unknown error.",
                                type: "error"
                            }]);
                    }
                    clearMarkers() {
                        this.aceEditor.session.getMarkers(true).forEach(marker => {
                            this.aceEditor.session
                                .removeMarker(marker.id);
                        });
                    }
                    setStyle(mimeType) {
                        let mode = Controls.CodeEditorSettings.getMode(mimeType);
                        let theme = Controls.CodeEditorSettings.getTheme(mimeType);
                        this.aceEditor.setTheme(theme);
                        this.aceEditor.session.setMode(mode);
                    }
                    getValue() {
                        return this.aceEditor.getValue();
                    }
                    setValue(value, silent = false) {
                        let silentChanges = this.m_silentChanges;
                        this.m_silentChanges = silent;
                        this.aceEditor.setValue(value || "");
                        this.m_silentChanges = silentChanges;
                    }
                    showFind() {
                        this.aceEditor.execCommand("find");
                    }
                    showReplace() {
                        this.aceEditor.execCommand("replace");
                    }
                    template() {
                        return `<div style='position:absolute;inset:0;overflow:auto;padding:10px;background-color:#FFFFFF;'></div>`;
                    }
                    resetChangedState() {
                        this.m_changed = false;
                    }
                    focus() {
                        this.aceEditor.focus();
                    }
                    addCommand(shortcut, exec) {
                        this.aceEditor.commands.addCommand({
                            name: shortcut,
                            bindKey: { win: "Ctrl-S" },
                            exec: () => {
                                if (_.isFunction(exec)) {
                                    exec(this.aceEditor);
                                }
                            }
                        });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        ace.config.set("basePath", Jade.Path.resolve("~/scripts/pdjs/external/ace"));
                        this.m_aceEditor = ace.edit(this.node.get(0));
                        this.aceEditor.getSession().on("change", () => {
                            if (!this.m_silentChanges) {
                                this.m_changed = true;
                                this.changeCallback();
                            }
                        });
                        this.aceEditor.setShowFoldWidgets(true);
                        this.aceEditor.renderer.setShowPrintMargin(false);
                        this.aceEditor.getSession().setUseSoftTabs(false);
                        this.fontSize = "14px";
                    }
                    createRange(startOnLine, endOnLine) {
                        let AceRange = ace.require('ace/range').Range;
                        return new AceRange(startOnLine, 0, endOnLine, 1);
                    }
                }
                Controls.CodeEditor = CodeEditor;
            })(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 CodeEditorSettings {
                    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"];
                    }
                }
                Controls.CodeEditorSettings = CodeEditorSettings;
            })(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", () => { });
                    }
                    template() {
                        return `<button role="${this.mode == Controls.ComboBoxMode.List ? "list" : "dialog"}" tabIndex="-1"></button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            width: "21px",
                            bottom: 0,
                            backgroundPosition: "center center",
                            backgroundRepeat: "no-repeat",
                            boxSizing: "border-box",
                            padding: 0
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        let iconPath = Jade.IconSet
                            .get("pd")
                            .resolve("ddl-grip.png", Jade.IconSetSizeSpecificDirectory.misc);
                        this.node.empty();
                        this.node.text(this.mode === Controls.ComboBoxMode.List ? "" : "...");
                        this.node.css({
                            backgroundImage: this.mode === Controls.ComboBoxMode.List ? `url(${iconPath})` : "",
                            opacity: this.enabled ? "1" : ".5",
                            cursor: this.enabled ? "pointer" : "default"
                        });
                        if (this.visible) {
                            this.node.show();
                        }
                        else {
                            this.node.hide();
                        }
                        this.enableClickHandlers(this.enabled);
                    }
                    enableClickHandlers(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 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() {
                        return `<div style="height:${this.height}px;width:${this.width}px;display:none;"></div>`;
                    }
                    show() {
                        this.ensureTippedPopUp();
                        Tipped.show(this.anchor);
                    }
                    hide() {
                        Tipped.hide(this.anchor);
                    }
                    destroy() {
                        Tipped.remove(this.anchor.get(0));
                        super.destroy();
                    }
                    popUp_onCreate() {
                        this.onCreateCallback();
                    }
                    ensureTippedPopUp() {
                        if (this.m_popUpCreated == false) {
                            this.node.detach();
                            Tipped.create(this.anchor, this.node, this.getPopUpOptions());
                            this.node.show();
                            this.popUp_onCreate();
                            this.m_popUpCreated = true;
                        }
                    }
                    getPopUpOptions(options) {
                        return _.merge({
                            skin: "white",
                            radius: false,
                            shadow: false,
                            stem: false,
                            position: "bottomleft",
                            showOn: false,
                            hideAfter: 500,
                            hideDelay: 500,
                            maxWidth: this.width,
                            fadeOut: 100,
                            showDelay: 0,
                            hideOn: "click-outside",
                            hideOthers: true,
                            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 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.KEYPRESS)
                            && 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.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;
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, this.ITEM_SELECTOR, (e) => {
                            let selectedListItem = this.controls.getById($(e.target).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.target).attr("id"));
                            this.setActiveItem(activeListItem);
                        });
                        this.node.on(Jade.BrowserEvent.MOUSELEAVE, this.ITEM_SELECTOR, (e) => {
                            let activeListItem = this.controls.getById($(e.target).attr("id"));
                            this.setActiveItem(activeListItem);
                        });
                        this.node.css({
                            overflowY: "auto"
                        });
                    }
                    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: "white-no-padding",
                            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("div[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();
                        if (Jade.String.isNullOrWhiteSpace(this.subTitle)) {
                            this.subTitleNode.html("No Description");
                        }
                        else {
                            this.subTitleNode.html(this.subTitle);
                        }
                        this.iconNode.attr("src", Jade.IconSet.get("pd")
                            .resolve(this.icon, Jade.IconSetSizeSpecificDirectory.x32));
                    }
                }
                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 LoadingMessageControl extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get message() {
                        return this.state.get("message", "");
                    }
                    set message(value) {
                        this.state.set("message", value);
                    }
                    get margin() {
                        return this.state.get("margin", 0);
                    }
                    get showLoadingIcon() {
                        return this.state.get("showLoadingIcon", true);
                    }
                    get messageNode() {
                        return this.node.find("div[role=message]");
                    }
                    get tableNode() {
                        return this.node.children("table");
                    }
                    get tableCellNode() {
                        return this.node.find("table > tbody > tr > td");
                    }
                    template() {
                        return `<div>
                        <table>
                            <tr>
                                <td>
                                    <div style="text-align:center;vertical-align:center;">
                                        <div role="message" data-controls>
                                            ${this.message}
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
            `;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.css({
                            position: "absolute",
                            top: 0,
                            right: 0,
                            bottom: 0,
                            left: 0,
                            margin: `${this.margin}px`
                        });
                        this.tableNode.css({
                            height: "100%",
                            width: "100%",
                            boxSizing: "border-box"
                        });
                        this.tableCellNode.css({
                            backgroundColor: "#FFFFFF"
                        });
                        this.messageNode.css({
                            display: "inline-block",
                            height: "40px",
                            lineHeight: "40px",
                            fontFamily: "arial",
                            fontSize: "20px",
                            paddingLeft: `${this.showLoadingIcon ? 45 : 0}px`,
                            backgroundRepeat: "no-repeat",
                            backgroundPosition: "0 center"
                        });
                    }
                    onStateChanged() {
                        super.onStateChanged();
                        if (this.showLoadingIcon) {
                            this.messageNode.css({
                                backgroundImage: `url(${Jade.IconSet.get("pd").resolve("ICON_CIRCLE_ANIMATED_36X36.GIF", Jade.IconSetSizeSpecificDirectory.misc)})`
                            });
                        }
                    }
                }
                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) {
                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);
                    }
                    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}"
                                style="height:22px;"/>
                            <input 
                                type="text" 
                                role="mask"
                                readonly
                                tabIndex="${this.tabIndex}"
                                class="${PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget}"
                                style="height:22px;" />
                        </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);
                        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 SearchBox extends Controls.MaskedTextBox {
                    constructor(options) {
                        super(options);
                        this.defaultMaskText = "Search...";
                    }
                    get buttonNode() {
                        return this.node.find("button[role=search]");
                    }
                    get onSearchCallback() {
                        return this.state.get("onSearch", () => { });
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.m_iconSearch = Jade.IconSet.get("pd").resolve("ICON_SEARCH_16X16.GIF", Jade.IconSetSizeSpecificDirectory.misc);
                        this.m_iconCancel = Jade.IconSet.get("pd").resolve("cancel.png", Jade.IconSetSizeSpecificDirectory.misc);
                        this.node.append(`<button role="search"></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,
                            backgroundImage: `url(${this.m_iconSearch})`,
                            backgroundRepeat: "no-repeat",
                            backgroundPosition: "center center",
                            backgroundColor: "transparent",
                            border: "0 none transparent"
                        });
                    }
                    onMaskFocus(e) {
                        this.showText();
                        this.focusText();
                    }
                    onTextBlur(e) {
                        if (Jade.String.isNullOrWhiteSpace(this.textValue)) {
                            this.textValue = "";
                            this.buttonMode(false);
                            this.showMask();
                        }
                    }
                    onTextKeyPress(e) {
                        if (e.keyCode == UI.KeyCodes.Return) {
                            if (!Jade.String.isNullOrWhiteSpace(this.textValue)) {
                                this.submitSearch();
                            }
                            else {
                                this.clearSearch();
                            }
                        }
                    }
                    submitSearch() {
                        this.m_searchSubmitted = true;
                        this.m_searchSubmittedTerm = this.textValue;
                        this.buttonMode(true);
                        this.onSearchCallback({
                            term: this.textValue
                        });
                    }
                    clearSearch() {
                        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();
                        }
                        else {
                            this.submitSearch();
                        }
                    }
                    buttonMode(isSearchMode) {
                        this.buttonNode.css({
                            backgroundImage: isSearchMode ? `url(${this.m_iconCancel})` : `url(${this.m_iconSearch})`
                        });
                    }
                }
                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 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.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.m_popUp = new Controls.PopUpCalendar({
                            skin: "white-no-padding",
                            anchor: this.buttonNode,
                            height: 210,
                            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.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);
                    }
                    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);
                    }
                }
                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);
                    }
                    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);
                        }
                    }
                    getPopUpOptions() {
                        return _.extend(super.getPopUpOptions(), {
                            skin: "white-no-padding",
                            position: "bottomright",
                            offset: { x: 4, y: 3 }
                        });
                    }
                    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);
                    }
                }
                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;
                    }
                    ;
                }
                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]`,
                            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");
                    }
                    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);
                        });
                    }
                    template() {
                        return `<div class="-pdjs-list-view"></div>`;
                    }
                    select(ids) {
                        this.items
                            .each((item) => {
                            item.selected = ids.indexOf(item.data.value) > -1;
                        });
                        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() {
                        this.controls.clear();
                        if (this.items.count == 0) {
                            this.addNoItemsMessage();
                        }
                        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();
                        }
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.data.length == 0 ?
                            this.addNoItemsMessage() :
                            this.refresh();
                        this.node.addClass(PDJS.Canvas.Shared.CanvasCss.FormFieldAnimationTarget);
                        this.node.on(Jade.BrowserEvent.DOUBLECLICK, ".-pdjs-list-view-item", (e) => {
                            this.dblClickCallback(this.selected);
                        });
                        this.height != null ?
                            this.node.css({ height: this.height }) :
                            this.node.attr("data-minimal", "true");
                    }
                    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: "#AAAAAA"
                        });
                    }
                    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, isMultiSelect) {
                        this.items.each(item => {
                            let isMultipleSelect = this.selectMode == ListViewSelectMode.multiple && isMultiSelect;
                            let isSingleSelect = this.selectMode != ListViewSelectMode.none && !isMultiSelect;
                            let isSelected = item.value == e.data.value;
                            if (isMultipleSelect && isSelected) {
                                item.selected = e.selected;
                            }
                            if (isSingleSelect) {
                                item.selected = isSelected;
                            }
                        });
                        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 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 numericType() {
                        return this.state.get("numericType");
                    }
                    get format() {
                        return this.state.get("format");
                    }
                    get value() {
                        return this.textNode.val();
                    }
                    set value(value) {
                        this.textNode.val(value);
                    }
                    get tabIndex() {
                        return this.state.get("tabIndex", -1);
                    }
                    set tabIndex(value) {
                        this.state.set("tabIndex", 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);
                    }
                    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.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", "");
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-heading">${this.label}</div>`;
                    }
                }
                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 PanelMenuLink extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get url() {
                        return this.state.get("url", "#");
                    }
                    get label() {
                        return this.state.get("label", "");
                    }
                    get description() {
                        return this.state.get("description");
                    }
                    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");
                    }
                    template() {
                        return `<div class="-pdjs-ui-panel-menu-link"><a href="#">${this.label}</a></div>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        if (this.url != null && this.url != "#") {
                            let url = Jade.Path.resolve(this.url);
                            this.linkNode.attr("href", url);
                        }
                        else if (this.clickCallback != null) {
                            this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                                this.clickCallback(e);
                                e.preventDefault();
                                e.cancelBubble = true;
                                e.returnValue = false;
                                return false;
                            });
                        }
                        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;
                        }
                        Tipped.create(this.linkNode, this.description, {
                            skin: "white",
                            radius: false,
                            shadow: false,
                            stem: true,
                            position: "leftmiddle",
                            showOn: "mouseenter",
                            hideAfter: 500,
                            hideDelay: 500,
                            maxWidth: 300,
                            fadeOut: 100,
                            showDelay: 0,
                            hideOn: "mouseleave",
                            hideOthers: true,
                            detach: true
                        });
                    }
                }
                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 Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class PanelMenuSeperator extends Jade.UI.Control {
                    constructor() {
                        super({});
                    }
                    template() {
                        return "<hr/>";
                    }
                }
                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 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 ProgressBar extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get backgroundColor() {
                        return this.state.get("backgroundColor", "#00FF00");
                    }
                    set backgroundColor(value) {
                        this.state.set("backgroundColor", value);
                    }
                    get borderColor() {
                        return this.state.get("borderColor", "#DDDDDD");
                    }
                    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", "#000000");
                    }
                    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: "#FFFFFF",
                            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 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 TabStripTabClickArgs {
                    constructor(tab) {
                        this.m_cancel = false;
                        this.m_tab = tab;
                    }
                    get cancel() {
                        return this.m_cancel;
                    }
                    set cancel(value) {
                        this.m_cancel = value;
                    }
                    get tab() {
                        return this.m_tab;
                    }
                }
                Controls.TabStripTabClickArgs = TabStripTabClickArgs;
                class TabStrip extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get binding() {
                        return this.state.get("binding");
                    }
                    get scrollLeftNode() {
                        return this.node.find(".-pdjs-tabstrip-scroll-l");
                    }
                    get scrollRightNode() {
                        return this.node.find(".-pdjs-tabstrip-scroll-r");
                    }
                    get tabsNode() {
                        return this.node.find(".-pdjs-tabstrip-tabs");
                    }
                    get tabOptionsList() {
                        return this.state.get("tabs", []);
                    }
                    set tabOptionsList(value) {
                        this.state.set("tabs", value);
                    }
                    get tabsNodes() {
                        return this.controls.getByType(Controls.TabStripTab);
                    }
                    get tabClickCallback() {
                        return this.state.get("tabClick", () => { });
                    }
                    get tabCreateCallback() {
                        return this.state.get("tabCreate", (e) => {
                            return new Controls.TabStripTab(e);
                        });
                    }
                    template() {
                        return `<div class="-pdjs-tabstrip">
                        <div class="-pdjs-tabstrip-spacer"></div>
                        <div class="-pdjs-tabstrip-scroll-l"></div>
                        <div class="-pdjs-tabstrip-tabs" data-controls></div>
                        <div class="-pdjs-tabstrip-scroll-r"></div>
                        <div class="-pdjs-tabstrip-spacer"></div>
                    </div>`;
                    }
                    onActivate(e) {
                        this.scrollLeftNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.tabsNode.scrollLeft(this.tabsNode.scrollLeft() - 150);
                        });
                        this.scrollRightNode.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.tabsNode.scrollLeft(this.tabsNode.scrollLeft() + 150);
                        });
                        this.tabsNode.on(Jade.BrowserEvent.CLICK, ".-pdjs-tabstrip-tab", (e) => {
                            this.onTabClick($(e.currentTarget).attr("id"));
                        });
                        this.isBrowserResizeAware = true;
                    }
                    onComplete(e) {
                        super.onComplete(e);
                        this.renderTabs();
                    }
                    renderTabs() {
                        this.controls.clear();
                        this.tabOptionsList.forEach(options => {
                            options = _.extend({
                                binding: this.binding
                            }, options);
                            let tab = this.tabCreateCallback(options);
                            if (tab != null) {
                                this.controls.add(tab);
                            }
                        });
                    }
                    onBrowserResize() {
                        let contentWidth = 0;
                        let overflow = 0;
                        this.tabsNodes.each(tab => {
                            contentWidth += tab.node.outerWidth(true);
                        });
                        overflow = contentWidth - this.tabsNode.width();
                        overflow = overflow > 0 ? overflow : 0;
                        this.setScrollerVisiblity();
                        setTimeout(() => {
                            this.scrollSelectedTabIntoView();
                        }, 200);
                    }
                    onTabClick(id) {
                        let args = null;
                        this.tabsNodes.each(tab => {
                            if (tab.ID == id) {
                                args = new TabStripTabClickArgs(tab);
                            }
                        });
                        if (args == null || args.cancel) {
                            return;
                        }
                        this.tabsNodes.each(tab => {
                            if (tab.ID != id) {
                                tab.selected = false;
                            }
                        });
                        args.tab.selected = true;
                        if (args.tab.hasClickCallback) {
                            args.tab.click();
                        }
                        else {
                            this.tabClickCallback(args.tab);
                        }
                    }
                    scrollSelectedTabIntoView() {
                        let selectedTab = this.node.find(".-pdjs-tabstrip-tab-selected");
                        if (selectedTab.length > 0) {
                            selectedTab.parent().scrollLeft(0);
                            selectedTab.parent().scrollLeft(Math.round(selectedTab.position().left));
                        }
                    }
                    setScrollerVisiblity() {
                    }
                }
                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 Shared;
    (function (Shared) {
        var UI;
        (function (UI) {
            var Controls;
            (function (Controls) {
                class TabStripTab extends Jade.UI.Control {
                    constructor(options) {
                        super(options);
                    }
                    get binding() {
                        this.ensureBindingState();
                        return this.m_binding;
                    }
                    get selected() {
                        return this.state.get("selected", false);
                    }
                    set selected(value) {
                        this.setSelected(value);
                    }
                    get clickCallback() {
                        return this.state.get("click", () => { });
                    }
                    get hasClickCallback() {
                        return this.state.get("click") != null;
                    }
                    get iconNode() {
                        return this.node.find("div[role=icon]");
                    }
                    get textNode() {
                        return this.node.find("div[role=text]");
                    }
                    get value() {
                        return this.binding.value;
                    }
                    template() {
                        return `<a data-uid="${this.ID}" class="-pdjs-tabstrip-tab">
                <div role="grid">
                    <div role="icon"></div>
                    <div role="text">${this.binding.text}</div>
                </div>
            </a>`;
                    }
                    click() {
                        this.selected = true;
                        this.clickCallback();
                    }
                    onActivate(e) {
                        this.setSelected(this.selected);
                        if (this.binding.icon != null) {
                            let iconUrl = Jade.IconSet.get("pd").resolve(this.binding.icon, Jade.IconSetSizeSpecificDirectory.x16);
                            this.iconNode.append(`<img src="${iconUrl}"/>`);
                        }
                    }
                    setSelected(value) {
                        value === true ?
                            this.node.addClass("-pdjs-tabstrip-tab-selected") :
                            this.node.removeClass("-pdjs-tabstrip-tab-selected");
                    }
                    ensureBindingState() {
                        if (this.m_binding == null) {
                            this.m_binding = new Controls.TabStripTabBinding({
                                defaults: this.state.get("binding"),
                                state: this.state
                            });
                        }
                    }
                }
                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 TabStripTabBinding 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.TabStripTabBinding = TabStripTabBinding;
            })(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);
                    }
                    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() {
                        return new ToolbarCommandButton(this.state.toJSON());
                    }
                    content() {
                        return `<button class="-pdjs-shared-ui-controls-toolbar-button">
                        <div role="icon">
                            <img src="${this.commander.getResolvedIcon()}"/>
                        </div>
                        <div role="text">${this.commander.label}</div>
                    </button>`;
                    }
                    onActivate(e) {
                        super.onActivate(e);
                        this.node.on(Jade.BrowserEvent.CLICK, (e) => {
                            this.hideTooltip();
                            if (this.commander && this.commander.enabled && this.commander.visible) {
                                this.commander.execute(this.value);
                            }
                        });
                    }
                    onPropertiesChanged() {
                        super.onPropertiesChanged();
                        let isBigPadding = this.commander.isLabelVisible || this.overflowed;
                        let hasGridGap = (this.commander.isIconVisible
                            && this.commander.isLabelVisible)
                            || this.overflowed;
                        this.commander.enabled ?
                            this.contentNode.removeAttr("disabled") :
                            this.contentNode.attr("disabled", "disabled");
                        this.commander.checked ?
                            this.contentNode.attr("checked", "checked") :
                            this.contentNode.removeAttr("checked");
                        this.imageNode.attr("src", this.commander.getResolvedIcon());
                        this.commander.isIconVisible ?
                            this.imageNode.show() :
                            this.imageNode.hide();
                        this.commander.isLabelVisible || this.overflowed ?
                            this.textNode.html(this.commander.label) :
                            this.textNode.html("");
                        this.node.attr("command-id", this.commander.commandUid);
                        this.contentNode.css({
                            gridGap: hasGridGap ? "5px" : "0",
                            padding: isBigPadding ? "0 15px" : "0 7px",
                            display: this.commander.visible ? "grid" : "none"
                        });
                    }
                }
                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 newItem = new Controls.ToolbarOverflowItem({
                                    item: item.createCopy()
                                });
                                this.menu.controls.add(newItem);
                            }
                        });
                    }
                    show() {
                        this.node.show();
                    }
                    hide() {
                        this.node.hide();
                    }
                    createMenu() {
                        if (this.menu) {
                            this.menu.destroy();
                            this.menu = null;
                        }
                        this.menu = new Controls.PopUp({
                            anchor: this.node,
                            width: 250,
                            tipped: {
                                skin: "white-no-padding",
                                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) {
                        this.toolbar.controls.add(item);
                    }
                }
                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 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 scaleNode() {
                        return this.node.find(".-pd-upload-input-scale");
                    }
                    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", () => { });
                    }
                    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'>&nbsp;</div>
                        <div class='-pd-upload-input-label'>&nbsp;</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.JS.PD.Web.UI.Controls.Upload({
                            browse_button: this.browseButtonNode.get(0),
                            container: this.ID,
                            multi_selection: false,
                            onFileAdded: _.bind(this.upload_onFilesAdded, this),
                            onUploadStart: _.bind(this.upload_onStart, this),
                            onUploadProgress: _.bind(this.upload_onProgress, this),
                            onUploadComplete: _.bind(this.upload_onComplete, this),
                            onError: _.bind(this.upload_onError, this)
                        });
                    }
                    upload_onFilesAdded(e) {
                        this.m_uploadFile = _.first(e);
                        this.onFileSelectedCallback(this.m_uploadFile);
                        this.m_upload.start();
                    }
                    upload_onStart(e) {
                        this.browseButtonNode.prop("disabled", true);
                        this.onUploadStartCallback(this.m_uploadFile);
                    }
                    upload_onProgress(e) {
                        this.labelNode.text("Uploading file... " + e.percent + " %");
                        this.scaleNode.css({
                            width: e.percent + "%"
                        });
                    }
                    upload_onComplete(e) {
                        this.labelNode.text(this.uploadName);
                        this.scaleNode.css({
                            width: "0"
                        });
                        this.browseButtonNode.prop("disabled", false);
                        this.onUploadCompleteCallback(this.m_uploadFile);
                    }
                    upload_onError(e) {
                        Jade.UI.MessageDialog.open({
                            title: e.error.title,
                            message: e.error.message,
                            dialogStyle: Jade.UI.MessageDialogStyle.Error,
                            dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                            select: (e) => {
                                e.close();
                            }
                        });
                        this.browseButtonNode.prop("disabled", false);
                    }
                }
                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;
                                }
                            });
                        }
                        get enabled() {
                            return this.state.get("enabled", true);
                        }
                        set enabled(value) {
                            this.state.set("enabled", value);
                        }
                        get errors() {
                            return this.m_errors;
                        }
                        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", "#000000");
                        }
                        get labelNode() {
                            return this.node.children("[role=label]");
                        }
                        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;
                        }
                        onInit(e) {
                            super.onInit(e);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            if (this.required) {
                                this.validators.add(new Fields.FieldValidatorRequired());
                            }
                        }
                        onStateChanged() {
                            super.onStateChanged();
                            this.labelNode.text(`${this.label}:`);
                            this.labelNode.css({
                                color: this.required ? "#FF0000" : "#000000"
                            });
                            if (this.enabled) {
                                this.controlNode.removeClass(PDJS.Shared.UI.CssClass.Disabled);
                            }
                            else {
                                this.controlNode.addClass(PDJS.Shared.UI.CssClass.Disabled);
                            }
                        }
                        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;
                            });
                            Tipped.create(this.labelNode, message, {
                                skin: "validation-error"
                            });
                            this.node.addClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: `url(${icon})`
                            });
                        }
                        removeValidationErrorToolTip() {
                            Tipped.remove(this.labelNode);
                            this.node.removeClass("-pdjs-validation-errors");
                            this.labelNode.css({
                                backgroundImage: ""
                            });
                        }
                    }
                    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 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" style="position:absolute;top:3px;right:0;bottom:0;left:0;"></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("ace/theme/pdjsexpression");
                            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();
                            });
                        }
                    }
                    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 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 IntegerField extends Fields.Field {
                        get inputNode() {
                            return this.controlNode.find("input");
                        }
                        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);
                        }
                        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 style=""/>`);
                            this.inputNode.css({
                                border: "0 none transparent",
                                height: "22px",
                                width: "100%",
                                paddingLeft: "5px",
                                boxSizing: "border-box",
                                position: "absolute",
                                top: 0,
                                right: 0,
                                left: 0,
                                fontSize: "12px"
                            });
                            this.node.css({
                                height: "50px"
                            });
                            this.validators.add(new Fields.FieldValidatorRegex({
                                message: `Value must be a number.`,
                                regularExpression: "^\\d*$",
                                expectedResult: true
                            }));
                            this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                                this.validate();
                            });
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.rawValue);
                        }
                    }
                    Fields.IntegerField = IntegerField;
                })(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 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.Manage.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 inputNode() {
                            return this.controlNode.find("input, textarea");
                        }
                        get value() {
                            return this.inputNode.val();
                        }
                        set value(value) {
                            this.inputNode.val(value);
                        }
                        get height() {
                            return this.state.get("height", 50);
                        }
                        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 blurCallback() {
                            return this.state.get("blur", () => { });
                        }
                        focus() {
                            this.inputNode.get(0).focus();
                            this.inputNode.get(0).select();
                        }
                        hasValue() {
                            return !Jade.String.isNullOrWhiteSpace(this.value);
                        }
                        onActivate(e) {
                            super.onActivate(e);
                            if (this.multiline) {
                                this.controlNode.append(`<textarea></textarea>`);
                            }
                            else {
                                this.controlNode.append(`<input type="text" />`);
                            }
                            this.inputNode.css({
                                border: "0 none transparent",
                                height: `100%`,
                                width: "100%",
                                paddingLeft: "5px",
                                boxSizing: "border-box",
                                position: "absolute",
                                top: 0,
                                right: 0,
                                left: 0,
                                fontSize: "12px"
                            });
                            this.node.css({
                                height: `${this.height}px`
                            });
                            this.inputNode.css({
                                position: "absolute",
                                boxSizing: "border-box",
                                top: 0,
                                right: 0,
                                left: 0,
                                bottom: 0
                            });
                            this.inputNode.on(Jade.BrowserEvent.BLUR, () => {
                                if (this.validateOnBlur) {
                                    this.validate();
                                    this.blurCallback();
                                }
                            });
                            if (!Jade.String.isNullOrWhiteSpace(this.value)) {
                                this.inputNode.val(this.value);
                            }
                            this.validators.add(new Fields.FieldValidatorLength({
                                min: this.minLength,
                                max: this.maxLength
                            }));
                        }
                        validatorValidate(validator) {
                            return validator.isValid(this.value);
                        }
                    }
                    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 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.Dialog {
                constructor(options, windowOptions = {}) {
                    super(_.extend({
                        title: `Upload | Resolve Conflict`
                    }, options), _.extend({
                        actions: [],
                        width: "500px",
                        maximized: false,
                        resizable: true
                    }, windowOptions));
                }
                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 `<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>`;
                }
                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({
                                    command: "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.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]");
                }
                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));
                    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();
                }
                close(options) {
                    super.close(options);
                    UploadDialog.instance = null;
                    if (this.uploader != null) {
                        this.uploader.stopUpload();
                        this.uploader.clear();
                    }
                }
                template() {
                    return `
                <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="-jadejs-button">Upload</button>
                            <button data-command="commit" class="-jadejs-button">Save</button>
                            <button data-command="cancel" class="-jadejs-button">Cancel</button>
                        </div>
                    </div>
                </div>
            `;
                }
                getWindowOptions() {
                    return {
                        title: "Upload | File",
                        actions: [],
                        height: 450,
                        width: 700,
                        minHeight: "250px",
                        minWidth: "250px"
                    };
                }
                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: "#1fee1c",
                        color: "#000000",
                        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.MessageDialog.open({
                            dialogStyle: Jade.UI.MessageDialogStyle.Warning,
                            dialogButtons: Jade.UI.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() {
                    let hasQueuedFiles = this.uploader.files.queued.count > 0;
                    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;
                    let errorFileCount = 0;
                    let savedFileCount = 0;
                    let fileNames = files.map(file => file.name);
                    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.window, e.data);
                        },
                        error: (e) => {
                            let failed = e.data.failed
                                .map(item => item.file);
                            this.commit_handleError(failed);
                        },
                        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;
                            errorFileCount += 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;
                            savedFileCount += 1;
                        }
                    });
                }
                commit_handleError(errored, handled = []) {
                    if (errored.length == 0 && handled.length > 0) {
                        this.commit_serviceCall(this.folderId, handled);
                        return;
                    }
                    let file = _.first(errored);
                    let resolveCurrent = (fileId, action) => {
                        file.fileMode = action;
                        errored = errored.filter(item => item.id != fileId);
                        handled.push(file);
                        this.commit_handleError(errored, handled);
                    };
                    let resolveRemaining = (action) => {
                        errored.forEach(file => {
                            file.fileMode = action;
                            handled.push(file);
                        });
                        errored = [];
                        this.commit_handleError(errored, handled);
                    };
                    Upload.ConflictDialog.open({
                        fileName: file.name,
                        callbacks: {
                            ok: (window, e) => {
                                setTimeout(() => {
                                    e.repeat ?
                                        resolveRemaining(e.action) :
                                        resolveCurrent(file.id, e.action);
                                }, 250);
                            }
                        }
                    });
                }
                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 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) {
                    let item = this.getListItem(file.id);
                    if (item) {
                        item.update(file);
                        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 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) {
                    this.data.state.set(data);
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.progress_init();
                }
                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;
                }
                progress_init() {
                    this.progress = new PDJS.Shared.UI.Controls.ProgressBar({
                        insertAt: "div[role=progress]",
                        showMessage: false,
                        backgroundColor: "#1fee1c",
                        color: "#000000",
                        height: "3px",
                        borderColor: "#DDDDDD"
                    });
                    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 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", () => { });
                }
                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(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,
                        max_file_size: "2gb",
                        max_file_count: 100,
                        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));
                }
                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,
                        callbacks: {}
                    });
                }
            }
            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.file ?
                        this.message = this.detail.message.replace("{FILE}", this.file.name) :
                        this.message = this.detail.message;
                }
                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;
                }
            }
            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}" is 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 ViewComponentType;
            (function (ViewComponentType) {
                ViewComponentType["Design"] = "design";
                ViewComponentType["Bounds"] = "bounds";
                ViewComponentType["FindInResults"] = "findinresults";
            })(ViewComponentType = Views.ViewComponentType || (Views.ViewComponentType = {}));
        })(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 Events;
            (function (Events) {
                Events["ColumnsAdded"] = "ColumnsAdded";
                Events["ColumnsRemoved"] = "ColumnsRemoved";
                Events["ColumnsCleared"] = "ColumnsCleared";
                Events["ColumnNameEdit"] = "ColumnNameEdit";
                Events["AddedColumnsChanged"] = "AddedColumnsChanged";
                Events["AddedColumnsMoved"] = "AddedColumnsMoved";
                Events["FinderSettingsChanged"] = "FinderSettingsChanged";
                Events["FiltersAdded"] = "FiltersAdded";
                Events["FiltersRemoved"] = "FiltersRemoved";
                Events["FiltersCleared"] = "FiltersCleared";
                Events["FiltersDuplicate"] = "FiltersDuplicate";
                Events["ConditionsAdded"] = "ConditionsAdded";
                Events["ConditionsConverted"] = "ConditionsConverted";
                Events["EntTypeAnchorsChanged"] = "EntTypeAnchorsChanged";
                Events["DocTypeAnchorsChanged"] = "DocTypeAnchorsChanged";
            })(Events = Views.Events || (Views.Events = {}));
        })(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 Jade.UI.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();
                    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();
                    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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/document-type-anchors:document-type-anchor/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/document-type-anchors:document-type-anchor/remove"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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("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);
                    this.state.set("$featureEditor", 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");
                }
                get featureEditor() {
                    return this.state.get("$featureEditor");
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
            }
            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 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-entity-type-anchors-editor">
                    <div role="toolbar"></div>
                    <div role="header"></div>
                    <div role="content" data-controls></div>
                </div>`;
                }
                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);
                    this.updateContextState();
                }
                save() {
                    let result = [];
                    let anchors = this.m_grid.get_dataSource().get_instance().data().toJSON();
                    anchors.forEach(anchor => {
                        result[result.length] = anchor.parts;
                    });
                    return result;
                }
                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,
                        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.updateContextState();
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.ToolBar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.EntTypeAnchorsToolbar()]
                    });
                    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().map((item) => {
                        let json = item.toJSON();
                        json.uid = item.uid;
                        return json;
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/anchors": {
                            viewStateId: this.viewStateId,
                            addedAnchors: addedAnchors,
                            addedAnchorsAll: allAnchors,
                            $editorGrid: this.m_grid
                        }
                    }, {
                        force: true
                    });
                }
            }
            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();
                    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
                    });
                    this.controls.add(this.m_finder);
                }
                editor_init() {
                    this.m_editor = new Views.EntTypeAnchorsEditor({
                        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.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 viewStateId() {
                    return this.state.get("viewStateId");
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get searchTerm() {
                    return this.state.get("searchTerm");
                }
                set searchTerm(value) {
                    this.state.set("searchTerm", value);
                }
                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();
                    this.updateContextState();
                }
                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,
                        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.updateContextState();
                        },
                        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);
                }
                updateContextState() {
                    if (this.m_grid == null) {
                        return;
                    }
                    let foundAnchors = this.m_grid.getSelections().toArray().map((item) => {
                        let json = item.toJSON();
                        json.uid = item.uid;
                        return json;
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/anchors": {
                            viewStateId: this.viewStateId,
                            foundAnchors: foundAnchors,
                            $finderGrid: this.m_grid
                        }
                    }, { force: true });
                }
            }
            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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/anchors:entity-type-anchor/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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 {
                get grid() {
                    return this.editorGrid.get_kendo();
                }
                onExecute(e) {
                    super.onExecute(e);
                    this.foundAnchors.forEach(item => {
                        this.populate(item.parts);
                    });
                    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.grid.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.grid.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() {
                    let grid = this.editorGrid.get_kendo();
                    grid.dataSource.data([]);
                    grid.refresh();
                    this.enabled = false;
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.EntTypeAnchorsChanged);
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.addedAnchorsAll.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.Dialog {
                constructor(options) {
                    super(options, {});
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.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 contentNode() {
                    return this.node.children("div[role=content]");
                }
                get splitterNode() {
                    return this.node.find("div[role=splitter]");
                }
                get buttonsNode() {
                    return this.node.children("div[role=buttons]");
                }
                template() {
                    return `
                <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();
                }
                getWindowOptions() {
                    return {
                        title: this.getDialogTitle(),
                        height: 500,
                        width: 600
                    };
                }
                okButton_onClick(e) {
                    this.m_editor.save(() => {
                        this.close({
                            command: "ok"
                        });
                    });
                }
                cancelButton_onClick(e) {
                    this.close({
                        command: "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.ColumnsEditor({
                        insertAt: "div[role=editor]",
                        componentType: this.componentType,
                        viewStateId: this.viewStateId
                    });
                    this.controls.add(this.m_editor);
                }
                finder_init(anchorDepths, excludeColumns) {
                    this.m_finder = new Views.ColumnsFinder({
                        insertAt: "div[role=finder]",
                        columnFinderType: Views.ColumnFinderType.Columns,
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        anchorDepths: anchorDepths,
                        excludeColumns: excludeColumns
                    });
                    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);
                }
                getDialogTitle() {
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            return "View Bounds Columns";
                        case Views.ViewComponentType.Design:
                            return "View Design Columns";
                        case Views.ViewComponentType.FindInResults:
                            return "Find in Results Columns";
                    }
                }
                initializationRequest() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "GetBoundsColumns";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "GetDesignColumns";
                            break;
                        case Views.ViewComponentType.FindInResults:
                            action = "GetFindInResults";
                            break;
                    }
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.editor_init();
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                static open(options, windowOptions = {}) {
                    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("viewStateId", null);
                    this.state.set("foundColumns", null);
                    this.state.set("addedColumns", null);
                    this.state.set("addedColumnsAll", null);
                    this.state.set("$editorGrid", null);
                    this.state.set("$finderGrid", null);
                    this.state.set("$columnNameEditors", null);
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.Design);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get foundColumns() {
                    return this.state.get("foundColumns", []);
                }
                get addedColumns() {
                    return this.state.get("addedColumns", []);
                }
                get addedColumnsAll() {
                    return this.state.get("addedColumnsAll", []);
                }
                get editorGrid() {
                    return this.state.get("$editorGrid");
                }
                get finderGrid() {
                    return this.state.get("$finderGrid");
                }
                get columnNameEditors() {
                    return this.state.get("$columnNameEditors");
                }
                onExecute(e) {
                    if (this.componentType == Views.ViewComponentType.Design) {
                        this.onExecuteForDesign();
                    }
                    else {
                        this.onExecuteForBounds();
                    }
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                }
                onExecuteForDesign() {
                }
            }
            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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/columns:column/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/columns:column/remove"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/columns:columns/clear"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/columns:column/edit"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/columns:column/move-up"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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.foundColumns.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() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsAdded, {
                        columns: this.foundColumns
                    });
                }
                onExecuteForDesign() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsAdded, {
                        columns: this.foundColumns
                    });
                }
            }
            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.addedColumnsAll.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "columns/clear",
                        tooltip: "Clear Columns",
                        label: "Clear",
                        icon: "eraser2.png",
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsCleared);
                }
                onExecuteForDesign() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsCleared);
                }
            }
            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 selectedItem() {
                    return _.first(this.addedColumns);
                }
                get editor() {
                    if (this.selectedItem != null) {
                        return this.columnNameEditors.get(this.selectedItem.uid);
                    }
                    return null;
                }
                onStateChanged(e) {
                    super.onStateChanged(e);
                    this.enabled = this.addedColumns.length == 1;
                    if (this.editor) {
                        this.showEditState(!this.editor.isNotOriginalName);
                    }
                }
                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);
                    if (this.editor) {
                        if (this.editor.isNotOriginalName) {
                            this.editor.revert();
                            this.showEditState(true);
                        }
                        else {
                            this.editor.edit();
                        }
                    }
                }
                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";
                    }
                }
            }
            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.addedColumns.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        enabled: true,
                        display: "icon label",
                        iconSetId: "pd"
                    };
                }
                onExecuteForBounds() {
                }
                onExecuteForDesign() {
                    this.move(this.addedColumnsAll.slice(0));
                }
                move(columns) {
                    if (this.moveDirection == MoveDirection.down) {
                        columns = columns.reverse();
                    }
                    let movingIds = this.addedColumns.map(column => { return column.id; });
                    let movingColumns = [];
                    columns.forEach((column, index, array) => {
                        this.transfer({
                            column: column,
                            index: index,
                            movingColumns: movingColumns,
                            movingColumnsIds: movingIds
                        });
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.AddedColumnsMoved, {
                        columns: this.moveDirection == MoveDirection.up ? movingColumns : movingColumns.reverse()
                    });
                }
                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.addedColumns.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() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsRemoved, {
                        columns: this.addedColumns
                    });
                }
                onExecuteForDesign() {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.ColumnsRemoved, {
                        columns: this.addedColumns
                    });
                }
            }
            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) {
            let AddedColumnsChangedEventType;
            (function (AddedColumnsChangedEventType) {
                AddedColumnsChangedEventType["add"] = "add";
                AddedColumnsChangedEventType["remove"] = "remove";
                AddedColumnsChangedEventType["clear"] = "clear";
            })(AddedColumnsChangedEventType = Views.AddedColumnsChangedEventType || (Views.AddedColumnsChangedEventType = {}));
            class ColumnsEditor extends Jade.UI.Control {
                constructor(options) {
                    super(options);
                    this.m_nameEditorsMap = new Views.ColumnsEditorNameEditorMap();
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.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]");
                }
                get columns() {
                    return this.m_grid.get_dataSource().data();
                }
                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) {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "SetBoundsColumns";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "SetDesignColumns";
                            break;
                        case Views.ViewComponentType.FindInResults:
                            action = "SetFindInResults";
                            break;
                    }
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.POST,
                        contentType: "application/json",
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: JSON.stringify({
                            viewStateId: this.viewStateId,
                            columns: this.m_grid.get_dataSource().get_instance().data().toJSON()
                        }),
                        success: (e) => {
                            if (_.isFunction(callback)) {
                                callback();
                            }
                        }
                    });
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.initializationRequest();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.ColumnsAdded, (args) => { this.grid_addColumns(args.columns); });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.ColumnsRemoved, (args) => { this.grid_removeColumns(args.columns); });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.ColumnsCleared, _.bind(this.grid_clearColumns, this));
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.AddedColumnsMoved, (args) => { this.grid_moveColumns(args.columns); });
                }
                grid_init(data) {
                    let grid = () => {
                        return this.contentNode.children(".-pd-viewgrid").data("kendoGrid");
                    };
                    this.m_data = data.columns;
                    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.contentNode,
                        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:\\#EEEEEE;color:\\#333333;border-bottom-color:\\#EEEEEE;"
                                }
                            }),
                            new PD.Web.UI.Controls.GridColumn({
                                field: "name",
                                title: "Name",
                                width: "300px",
                                template: (e) => {
                                    this.m_nameEditorsMap.add(e);
                                    return `<div data-id="${e.id}"></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) => {
                            this.updateViewColumnsContextState();
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new Jade.UI.ToolBar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.ColumnsDialogToolBarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                initializationRequest() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "GetBoundsColumns";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "GetDesignColumns";
                            break;
                        case Views.ViewComponentType.FindInResults:
                            action = "GetFindInResults";
                            break;
                    }
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.grid_init(e);
                            this.toolbar_init();
                            this.updateViewColumnsContextState();
                        }
                    });
                }
                grid_addColumns(columns) {
                    let dataSource = this.m_grid.get_dataSource().get_instance();
                    columns.forEach(column => {
                        let record = dataSource.get(column.id);
                        if (record == null) {
                            dataSource.add(column);
                        }
                    });
                    this.m_grid.refresh({
                        clear: true,
                        selections: columns.map(column => { return column.id; })
                    });
                    this.grid_publishAddedColumnsChangedEvent({
                        added: columns,
                        eventType: AddedColumnsChangedEventType.add
                    });
                }
                grid_removeColumns(columns) {
                    let dataSource = this.m_grid.get_dataSource().get_instance();
                    columns.forEach(column => {
                        let record = dataSource.get(column.id);
                        if (record != null) {
                            dataSource.remove(record);
                        }
                    });
                    this.m_grid.refresh({
                        clear: true
                    });
                    this.grid_publishAddedColumnsChangedEvent({
                        removed: columns,
                        eventType: AddedColumnsChangedEventType.remove
                    });
                }
                grid_clearColumns() {
                    let grid = this.m_grid.get_kendo();
                    grid.dataSource.data().slice(0).forEach(column => {
                        grid.dataSource.remove(column);
                    });
                    this.m_grid.refresh({
                        clear: true
                    });
                    this.grid_publishAddedColumnsChangedEvent({
                        eventType: AddedColumnsChangedEventType.clear
                    });
                }
                grid_moveColumns(columns) {
                    let grid = this.m_grid.get_kendo();
                    grid.dataSource.data(columns);
                    this.m_grid.refresh();
                }
                grid_publishAddedColumnsChangedEvent(args) {
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .publish(Views.Events.AddedColumnsChanged, {
                        added: args.added == null ? [] : args.added,
                        removed: args.removed == null ? [] : args.removed,
                        eventType: args.eventType,
                        columns: this.m_grid.get_dataSource().get_instance().data().toJSON()
                    });
                }
                updateViewColumnsContextState() {
                    if (this.m_grid == null) {
                        return;
                    }
                    let allColumns = this.m_grid.get_dataSource().get_instance().data().toJSON();
                    let addedColumns = this.m_grid.getSelections().toArray().map((item) => {
                        let json = item.toJSON();
                        json.uid = item.uid;
                        return json;
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .commands
                        .setState({
                        "view/columns": {
                            viewStateId: this.viewStateId,
                            componentType: this.componentType,
                            addedColumns: addedColumns,
                            addedColumnsAll: allColumns,
                            $editorGrid: this.m_grid,
                            $columnNameEditors: this.m_nameEditorsMap
                        }
                    }, { force: true });
                }
            }
            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 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;
                }
                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.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) {
            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 componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.Design);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get contentNode() {
                    return this.node.children("div[role=content]");
                }
                get excludeColumns() {
                    return this.state.get("excludeColumns", []);
                }
                set excludeColumns(value) {
                    this.state.set("excludeColumns", null);
                    this.state.set("excludeColumns", value);
                }
                get anchorDepths() {
                    return this.state.get("anchorDepths", []);
                }
                get columnFinderType() {
                    return this.state.get("columnFinderType", ColumnFinderType.Columns);
                }
                get onDoubleClickCallback() {
                    return this.state.get("onDoubleClick", () => { });
                }
                template() {
                    return `
                <div class="-pdjs-view-columns-finder">
                    <div role="toolbar"></div>
                    <div role="content"></div>
                </div>`;
                }
                getSelections() {
                    return this.m_grid.getSelections().toArray();
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.toolbar_init();
                    this.grid_init();
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.AddedColumnsChanged, (args) => {
                        let columns = args.columns;
                        let removed = args.removed;
                        if (columns !== undefined) {
                            this.excludeColumns = args.columns;
                        }
                        if (removed !== undefined) {
                            this.m_grid.refresh({
                                clear: true,
                                selections: args.removed.map(item => { return item.id; })
                            });
                        }
                        else {
                            this.m_grid.refresh();
                        }
                    });
                    PDJS.Application
                        .instance
                        .contexts
                        .current
                        .events
                        .subscribe(Views.Events.FinderSettingsChanged, () => {
                        this.m_grid.refresh();
                    });
                }
                grid_init() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "SearchBoundsColumns";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "SearchDesignColumns";
                            break;
                        case Views.ViewComponentType.FindInResults:
                            action = "SearchFindInResultsColumns";
                            break;
                    }
                    this.m_grid = new PD.Web.UI.Controls.Grid({
                        container: this.contentNode,
                        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: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                                    type: "post",
                                    data: () => {
                                        return {
                                            viewStateId: this.viewStateId,
                                            term: this.m_toolbar.searchTerm,
                                            textOnly: this.componentType === Views.ViewComponentType.FindInResults,
                                            depth: this.m_toolbar.anchorDepth,
                                            exclude: this.excludeColumns.flatMap(column => { return column.id; })
                                        };
                                    }
                                }
                            },
                            schema: {
                                data: "data",
                                total: "totalCount"
                            },
                            sort: [
                                { field: "name", dir: "asc" }
                            ]
                        },
                        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) => {
                            this.draggable_init();
                            let state = {
                                viewStateId: this.viewStateId,
                                componentType: this.componentType,
                                foundColumns: e.selections.toArray().map(item => { return item.toJSON(); }),
                                $finderGrid: this.m_grid
                            };
                            let context = {};
                            switch (this.columnFinderType) {
                                case ColumnFinderType.Columns:
                                    context = { "view/columns": state };
                                    break;
                                case ColumnFinderType.Filters:
                                    context = { "view/filters": state };
                                    break;
                            }
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .setState(context, { force: true });
                        },
                        dblclick: (e) => {
                            let command = null;
                            switch (this.columnFinderType) {
                                case ColumnFinderType.Columns:
                                    command = "view/columns:column/add";
                                    break;
                                case ColumnFinderType.Filters:
                                    command = "view/filters:filter/add";
                                    break;
                            }
                            PDJS.Application
                                .instance
                                .contexts
                                .current
                                .commands
                                .execute(command);
                            this.onDoubleClickCallback();
                        },
                        contextMenu: (grid) => {
                            this.contextMenu_init(grid);
                        }
                    });
                }
                toolbar_init() {
                    this.m_toolbar = new Views.ColumnsFinderToolbar({
                        insertAt: "div[role=toolbar]",
                        onAnchorDepthChange: () => {
                            this.m_grid.get_dataSource().get_instance()._skip = 0;
                            this.m_grid.get_dataSource().read();
                        },
                        onFilterChange: (term) => {
                            this.m_grid.get_dataSource().get_instance()._skip = 0;
                            this.m_grid.get_dataSource().read();
                        },
                        anchorDepths: this.anchorDepths
                    });
                    this.controls.add(this.m_toolbar);
                }
                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);
                }
            }
            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.Dialog {
                constructor(options) {
                    super(options, {});
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.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 `
                <div class="-pdjs-view-columns-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();
                }
                getWindowOptions() {
                    return {
                        title: this.getDialogTitle(),
                        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]",
                        columnFinderType: Views.ColumnFinderType.Columns,
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        anchorDepths: anchorDepths,
                        excludeColumns: excludeColumns,
                        onDoubleClick: () => {
                            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);
                }
                getDialogTitle() {
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            return "View Bounds Columns";
                        case Views.ViewComponentType.Design:
                            return "View Design Columns";
                    }
                }
                initializationRequest() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "GetBoundsColumns";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "GetDesignColumns";
                            break;
                    }
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                okAndClose() {
                    this.close({
                        command: "ok",
                        data: this.m_finder.getSelections()
                    });
                }
                static open(options, windowOptions = {}) {
                    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 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 onAnchorDepthChangeCallback() {
                    return this.state.get("onAnchorDepthChange", () => { });
                }
                get onFilterChangeCallback() {
                    return this.state.get("onFilterChange", () => { });
                }
                get anchorDepthNode() {
                    return this.node.find("select");
                }
                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;
                            this.onFilterChangeCallback(this.searchTerm);
                        }
                    });
                    this.controls.add(this.m_searchBox);
                }
                anchorDepth_init() {
                    this.anchorDepthNode.on(Jade.BrowserEvent.CHANGE, () => {
                        this.onAnchorDepthChangeCallback();
                    });
                    if (this.anchorDepths.length <= 1) {
                        this.anchorDepthNode.hide();
                    }
                    this.anchorDepths.forEach(depth => {
                        this.anchorDepthNode.append(`<option value="${depth.value}">Columns for: ${depth.name}</option>`);
                    });
                }
            }
            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 componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.Design);
                }
                get okButtonNode() {
                    return this.node.find("button[data-command=ok]");
                }
                get cancelButtonNode() {
                    return this.node.find("button[data-command=cancel]");
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get contentNode() {
                    return this.node.find("div[role=content]");
                }
                get buttonsNode() {
                    return this.node.children("div[role=buttons]");
                }
                get headerNode() {
                    return this.node.children("div[role=header]");
                }
                onActivate(e) {
                    super.onActivate(e);
                    this.addContent();
                }
                getPopUpOptions() {
                    return _.extend(super.getPopUpOptions(), {
                        skin: "white",
                        position: "topleft",
                        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);
                    }
                }
                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 conditions or filters have been added.<br/>
                                Add a <a href="#" role="condition">condition</a> or <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: "#f1f1f1"
                    });
                    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", Views.ViewComponentType.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) {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "SetBoundsFilters";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "SetDesignFilters";
                            break;
                    }
                    PDJS.Ajax.call({
                        type: Jade.HttpVerb.POST,
                        contentType: "application/json",
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        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 Jade.UI.ToolBar({
                        insertAt: "[role=toolbar]",
                        segments: [new Views.FiltersDialogToolBarSegment()]
                    });
                    this.controls.add(this.m_toolbar);
                }
                initializationRequest() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "GetBoundsFilters";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "GetDesignFilters";
                            break;
                    }
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.tree_init(e.condition);
                            this.toolbar_init();
                        }
                    });
                }
            }
            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) {
                    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;
                }
                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 dropTargetNode = $(e.dropTarget);
                    let isDropBetween = e.statusClass == "insert-top" ||
                        e.statusClass == "insert-middle" ||
                        e.statusClass == "insert-bottom";
                    if (isDropBetween) {
                        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);
                    }
                }
                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 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";
                    let srcNode = null;
                    let dstNode = null;
                    let sibNode = null;
                    let newSrcNode = null;
                    switch (true) {
                        case conditionOnCondition:
                            dstNode = $(e.destinationNode);
                            srcNode = $(e.sourceNode);
                            sibNode = Views.FiltersEditorTreeActions.getFirstChildFilter(dstNode);
                            if (sibNode.length == 1) {
                                this.tree.insertBefore(srcData.toJSON(), sibNode);
                                newSrcNode = sibNode.prev();
                            }
                            else {
                                newSrcNode = this.tree.append(srcData, dstNode);
                            }
                            this.tree.remove(e.sourceNode);
                            this.tree.select(newSrcNode);
                            break;
                        case filterOnFilter:
                            sibNode = $(e.destinationNode);
                            this.tree.insertAfter(srcData.toJSON(), sibNode);
                            newSrcNode = sibNode.next();
                            this.tree.remove(e.sourceNode);
                            this.tree.select(newSrcNode);
                            break;
                        case conditionOnFilter:
                            dstNode = this.tree.parent(e.destinationNode);
                            sibNode = Views.FiltersEditorTreeActions.getFirstChildFilter(dstNode);
                            this.tree.insertBefore(srcData.toJSON(), sibNode);
                            newSrcNode = sibNode.prev();
                            this.tree.remove(e.sourceNode);
                            this.tree.select(newSrcNode);
                            break;
                        case filterOnCondition:
                            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);
                    }
                    data.length == 0 ? message.node.show() : message.node.hide();
                }
            }
            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) {
            let FiltersDialogEvents;
            (function (FiltersDialogEvents) {
            })(FiltersDialogEvents = Views.FiltersDialogEvents || (Views.FiltersDialogEvents = {}));
            class FiltersDialog extends Jade.UI.Dialog {
                constructor(options) {
                    super(options, {});
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.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]");
                }
                get buttonsNode() {
                    return this.node.children("div[role=buttons]");
                }
                template() {
                    return `
                <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();
                }
                getWindowOptions() {
                    return {
                        title: this.getDialogTitle(),
                        height: 500,
                        width: 600
                    };
                }
                okButton_onClick(e) {
                    this.m_editor.save(() => {
                        this.close({
                            command: "ok"
                        });
                    });
                }
                cancelButton_onClick(e) {
                    this.close({
                        command: "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
                    });
                    this.controls.add(this.m_editor);
                }
                finder_init(anchorDepths, excludeColumns) {
                    this.m_finder = new Views.ColumnsFinder({
                        insertAt: "div[role=finder]",
                        columnFinderType: Views.ColumnFinderType.Filters,
                        componentType: this.componentType,
                        viewStateId: this.viewStateId,
                        anchorDepths: anchorDepths,
                        excludeColumns: excludeColumns
                    });
                    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);
                }
                getDialogTitle() {
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            return "View Bounds Filters";
                        case Views.ViewComponentType.Design:
                            return "View Design Filters";
                    }
                }
                initializationRequest() {
                    let action = null;
                    switch (this.componentType) {
                        case Views.ViewComponentType.Bounds:
                            action = "GetBoundsFilters";
                            break;
                        case Views.ViewComponentType.Design:
                            action = "GetDesignFilters";
                            break;
                    }
                    PDJS.Ajax.call({
                        url: Jade.Path.resolve(`~/Shared/ViewColumns/${action}`),
                        data: {
                            viewStateId: this.viewStateId
                        },
                        success: (e) => {
                            this.editor_init();
                            this.finder_init(e.anchors, e.columns);
                            this.popup_init();
                        }
                    });
                }
                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("foundColumns", null);
                    this.state.set("$selectedItem", null);
                    this.state.set("$tree", null);
                }
                get componentType() {
                    return this.state.get("componentType", Views.ViewComponentType.Design);
                }
                get viewStateId() {
                    return this.state.get("viewStateId");
                }
                get foundColumns() {
                    return this.state.get("foundColumns", []);
                }
                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 Jade.UI.ToolBarSegment {
                onAddItems(e) {
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:filter/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:filter/remove"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:filters/clear"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:filter/edit"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:filter/duplicate"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        commandId: "view/filters:condition/add"
                    }));
                    e.registerItem(new Jade.UI.ToolBarButtonCommand({
                        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 label",
                        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.foundColumns.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.foundColumns.length > 0;
                }
                getDefaultValuesForProps() {
                    return {
                        id: "filter/add",
                        tooltip: "Add Filter",
                        label: "Add Filter",
                        icon: "arrow_down_green.png",
                        enabled: true,
                        display: "icon label",
                        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 label",
                        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 label",
                        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 label",
                        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.JS.ProspectDirector.Types.Core.Dialogs.FilterEditor.show({
                        params: {
                            viewStateId: this.viewStateId,
                            id: filter.id,
                            enabled: filter.enabled,
                            operator: filter.operator,
                            value: filter.value,
                            verse: filter.verse
                        },
                        callbacks: {
                            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 label",
                        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 label",
                        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 = {}));
