<commit_before>/*
 CKEditor Addons
 */
CKEDITOR.define("confirmChanges", {});
CKEDITOR.define("validateText", {});
CKEDITOR.define("getTextHistory", {});

CKEDITOR.newCommandWithExecution = function (executionFunc) {
    return {
        modes: {wysiwyg: 1, source: 1},// This command works in both editing modes.
        editorFocus: false,// This command will not auto focus editor before execution.
        canUndo: false,// This command requires no undo snapshot.
        exec: executionFunc
    }
};

CKEDITOR.plugins.add("documentSaver", {
    init: function (editor) {
        var pluginName = "documentSaver";
        editor.documentSnapshot = editor.getData();
        editor.blurHandler = function (event) {
            if (event.editor.checkDirty()) {
                event.editor.openDialog(pluginName);
            }
        };
        editor.focusHandler = function (event) {
            event.removeListener();
            event.editor.on('blur', event.editor.blurHandler);
        };
        var switchToolbarCommandFunction = function (event) {
            var element = event.element;
            if (event.elementMode == 1) {
                event.execCommand("toolbarswitch");
            }
            for (var key in CKEDITOR.instances) {
                var editor = CKEDITOR.instances[key];
                if (element == editor.element) {
                    return editor;
                }
            }
        };

        editor.on('blur', editor.blurHandler);

        function saveData(event, noCallback) {
            editor.documentSnapshot = event.getData();
            event.resetDirty();
            if (noCallback) {
                event.removeListener('blur', event.blurHandler);
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                event.on("focus", event.focusHandler);
            }
        }

        function switchModeCallback(e) {
            return function () {
                Imcms.BackgroundWorker.createTask({
                    showProcessWindow: true,
                    refreshPage: true
                })();
                $(e.element.$).click();
            };
        }

        var confirmBeforeSwitch = function (event) {
            var callback = switchModeCallback(event);
            event = switchToolbarCommandFunction(event);
            CKEDITOR.fireOnce("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmNoEvent = function (event, callback) {
            if (!callback) {
                event = switchToolbarCommandFunction(event);
            }
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmWithEvent = function (event) {
            event = switchToolbarCommandFunction(event);
            var callback = Imcms.Events.getCallback("TextEditorRedirect");
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            event.resetDirty();
        };
        var confirmCommandWithEvent = CKEDITOR.newCommandWithExecution(confirmWithEvent);
        editor.addCommand("confirmChanges", confirmCommandWithEvent);
        editor.ui.addButton('confirm', {
            label: 'Save all changes',
            command: "confirmChanges",
            icon: "images/ic_apply.png"
        });

        var confirmCommandNoEvent = CKEDITOR.newCommandWithExecution(confirmNoEvent);
        editor.addCommand("confirmChangesWithoutEvent", confirmCommandNoEvent);

        var confirmCommandBeforeSwitch = CKEDITOR.newCommandWithExecution(confirmBeforeSwitch);
        editor.addCommand("confirmChangesBeforeSwitch", confirmCommandBeforeSwitch);

        var cancelCommandFunction = function (event) {
            var newEditor = switchToolbarCommandFunction(event),
                hideCommand = function (event) {
                    setTimeout(function () {
                        event.removeListener('instanceReady', hideCommand);
                        event.setData(event.documentSnapshot);
                        event.removeListener('blur', event.blurHandler);
                        event.focusManager.unlock();
                        event.element.$.blur();
                        event.focusManager.blur();
                        event.on("focus", event.focusHandler);
                    }, 1);
                };
            if (newEditor != event) {
                newEditor.on('instanceReady', hideCommand.bind(null, newEditor));

            } else {
                hideCommand(event);
            }
        };
        var cancelCommandDefinition = CKEDITOR.newCommandWithExecution(
            Imcms.Events.getCallbackOr("TextEditorRedirect", cancelCommandFunction)
        );
        editor.addCommand("cancelChanges", cancelCommandDefinition);
        editor.ui.addButton('cancel', {
            label: 'Cancel all changes and restore document to previous state',
            command: "cancelChanges",
            icon: "images/ic_cancel.png"
        });

        var saveCommandDefinition = CKEDITOR.newCommandWithExecution(function (event) {
            var $button = $('.' + event.id).find('.cke_button__savedata_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            confirmNoEvent(event, function () {
                $button.css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_save.png" + ")"
                });
            });
        });
        editor.addCommand("saveChanges", saveCommandDefinition);
        editor.ui.addButton('saveData', {
            label: 'Save all changes',
            command: "saveChanges",
            icon: "images/ic_save.png"
        });
    }
});
CKEDITOR.dialog.add("documentSaver", function (event) {
    return {
        title: 'Save changes',
        width: 200,
        height: 25,
        onOk: function () {
            event.execCommand("confirmChanges");
        },
        onCancel: function () {
            event.execCommand("cancelChanges");
        },
        onHide: function () {
            setTimeout(function () {
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                $(event.focusManager.currentActive).blur();
            }, 500);
        },
        contents: [
            {
                id: 'general',
                label: 'Settings',
                elements: [
                    {
                        type: 'html',
                        onLoad: function (event) {
                            var $dialog = $(event.sender.parts.dialog.$);
                            $dialog.find(".cke_resizer.cke_resizer_ltr").hide(); // dialog resize triangle
                            // in Safari close button goes to wrong side,
                            $dialog.find(".cke_dialog_close_button").css("float", "right");
                        },
                        html: '
You have changed the text. Do you wish to save it?
'
                    }
                ]
            }
        ]
    };
});

CKEDITOR.defineToolbar = function (editor) {
    var prefix;

    if (editor.elementMode == 1) { // full-screen editor mode
        editor.config.maxToolbar = true;
        prefix = "max";

    } else {
        editor.config.maxToolbar = false;
        prefix = "min";
    }

    if (editor.element.data("contenttype") === "text") {
        return prefix + "PlainText";

    } else if (editor.element.data("contenttype") === "from-html") {
        return prefix + "TextToolbar";

    } else {
        return prefix + "HtmlToolbar";
    }
};

CKEDITOR.switchFormat = false;

CKEDITOR.plugins.add("switchFormatToHTML", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToHTML', {
            label: 'Switch format to HTML',
            command: "switchFormat",
            icon: "images/switch-between-html-and-text-mode.png"
        });
    }
});

CKEDITOR.plugins.add("switchFormatToText", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToText', {
            label: 'Switch format to text',
            command: "switchFormat",
            icon: "images/plain_text.png"
        });
    }
});

CKEDITOR.plugins.add("fileBrowser", {
    init: function (editor) {

        var onChooseFile = function () {
            Imcms.Editors.Content.showDialog({
                onApply: $.proxy(onFileChosen, this),
                onCancel: $.proxy(onFileChosen, this)
            });
            editor.focusManager.blur();
            editor.element.$.blur();
        };
        var onFileChosen = function (data) {
            if (data) {
                editor.insertHtml('
', 'unfiltered_html');
            }
            editor.focusManager.focus();
            editor.element.$.focus();
        };

        var openBrowserCommandDefinition = CKEDITOR.newCommandWithExecution(onChooseFile);
        editor.addCommand("openBrowser", openBrowserCommandDefinition);

        editor.ui.addButton('openBrowser', {
            label: 'Open Image Browser',
            command: "openBrowser",
            icon: "images/ic_images.png"
        });
    }
});

CKEDITOR.plugins.add("w3cValidator", {
    init: function (editor) {
        var w3cValidateCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__w3cvalidate_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("validateText", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + (data.result ? "images/ic_valid.png" : "images/ic_invalid.png") + ")"
                    });

                    if (!data.result) {
                        $(event.element.$).data("w3cValidateData", data);
                        event.execCommand("w3cValidateDialog", data);
                    }
                }
            }, event);
        };
        var w3cValidateCommandDefinition = CKEDITOR.newCommandWithExecution(w3cValidateCommand);
        editor.addCommand("w3cValidate", w3cValidateCommandDefinition);
        editor.addCommand("w3cValidateDialog", new CKEDITOR.dialogCommand("w3cValidationResultDialog"));

        editor.ui.addButton('w3cValidate', {
            label: 'Validate Content over W3C',
            command: "w3cValidate",
            icon: "images/ic_w3c.png"
        });
    }
});
CKEDITOR.dialog.add("w3cValidationResultDialog", function (event) {
    var $wrapper = $("
"),
        $content = $("
").addClass("imcms-w3c-errors").appendTo($wrapper),
        data = $(event.element.$).data("w3cValidateData");

    $("
").append($("
").text("Validation Output: " + data.data.errors.length + " Errors")).appendTo($content);

    data.data.errors.forEach(function (item, pos) {
        var $container = $("
").addClass("imcms-w3c-error").appendTo($content),
            $errorMessage = $("
").text(pos + 1 + ". " + item.message.charAt(0).toUpperCase() + item.message.slice(1)).appendTo($container),
            $sourceContainer = $("
").appendTo($container),
            $source = $("").addClass("language-html").html(item.line + ": " + item.source.replace(/(<([^>]+)>)/ig, "")).appendTo($sourceContainer);

        Prism.highlightElement($source[0]);
    });

    return {
        title: 'Validation Result Dialog',
        width: 600,
        minHeight: 250,
        contents: [
            {
                id: 'w3cValidation',
                label: 'Validation',
                elements: [
                    {
                        type: 'html',
                        html: $("
").append($wrapper).html()
                    }
                ]
            }
        ]
    };
});

CKEDITOR.plugins.add("textHistory", {
    init: function (editor) {
        var textHistoryCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__texthistory_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("getTextHistory", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_history.png" + ")"
                    });

                    $(event.element.$).data("textHistoryData", data);
                    event.execCommand("textHistoryDialog", data);
                }
            }, event);
        };
        var textHistoryCommandDefinition = CKEDITOR.newCommandWithExecution(textHistoryCommand);
        editor.addCommand("textHistory", textHistoryCommandDefinition);
        editor.addCommand("textHistoryDialog", new CKEDITOR.dialogCommand("textHistory"));

        editor.ui.addButton('textHistory', {
            label: 'Text History',
            command: "textHistory",
            icon: "images/ic_history.png"
        });
    }
});

CKEDITOR.dialog.add("textHistory", function (event) {
    var $wrapper = $("
").addClass("imcms-text-history"),
        $leftPanel = $("
").addClass("imcms-left-panel").appendTo($wrapper),

        $content = $("
").addClass("imcms-content")
            .css({
                "max-width": "600px",
                "float": "right"
            })
            .appendTo($wrapper),

        data = $(event.element.$).data("textHistoryData")
            .map(function (textHistoryData) {
                textHistoryData.modifiedDate = new Date(textHistoryData.modifiedDate);
                textHistoryData.type = (textHistoryData.type == "HTML")
                    ? "html"
                    : "from-html";
                return textHistoryData;
            })
            .sort(function (a, b) {
                return (a.modifiedDate > b.modifiedDate ? -1 : (a.modifiedDate == b.modifiedDate ? 0 : 1));
            }),

        groupedData = {},
        $selected = undefined,
        selectedItem,
        previousType;

    data.forEach(function (it) {
        var key = it.modifiedDate.format("dd/m/yy");

        if (!(key in groupedData)) {
            groupedData[key] = [];
        }

        groupedData[key].push(it);
    });

    var buttonsShowed = false;

    function addTextHistoryButton(text, onClick) {
        return $("<button>")
            .addClass("imcms-neutral")
            .css("float", "right")
            .html(text)
            .appendTo($wrapper)
            .click(onClick);
    }

    $.each(groupedData, function (key, list) {
        $("
").addClass("imcms-separator").text(key).appendTo($leftPanel);

        list.forEach(function (item) {
            $("
").appendTo($leftPanel)
                .append(item.modifiedDate.format("HH:MM:ss") + " | " + item.modifiedBy)
                .click(function () {
                    if (!buttonsShowed) {
                        addTextHistoryButton("View Page", function () {
                            if (selectedItem.type !== "html") {
                                $content.html($content.text());
                                selectedItem.type = "html";
                            }
                        });
                        addTextHistoryButton("View Source", function () {
                            if (selectedItem.type === "html") {
                                $content.text($content.html());
                                selectedItem.type = "from-html";
                            }
                        });
                        buttonsShowed = true;
                    }

                    if ($selected) {
                        $selected.removeClass("selected");
                    }

                    var callFunc = (item.type === "html")
                        ? "html"
                        : "text";

                    $content[callFunc](item.text);
                    $selected = $(this).addClass("selected");
                    selectedItem = item;
                    previousType = item.type;
                });
        })
    });

    return {
        title: 'Text History Dialog',
        width: 600,
        height: 400,
        contents: [
            {
                id: 'textHistory',
                label: 'Text History',
                elements: [
                    {
                        type: 'html',
                        onLoad: function () {
                            $("#" + this.domId).append($wrapper)
                        },
                        html: ""
                    }
                ]
            }
        ],
        buttons: [
            {
                id: "text history OK button",
                type: "button",
                label: "Write to textfield",
                title: "Write to textfield",
                "class":"cke_dialog_ui_button_ok",
                disabled: false,
                onClick: function () {
                    if (selectedItem) {
                        event.setData(""); // clear previous text
                        var contentType = $(event.element.$).data("contenttype");

                        var callFunc = (contentType === "html")
                            ? "insertHtml"
                            : "insertText";

                        event[callFunc](selectedItem.text);

                        if (selectedItem.type !== contentType) {
                            event.execCommand("switchFormat");
                        }
                    }
                }
            },
            CKEDITOR.dialog.cancelButton
        ]
    };
});<commit_msg>IMCMS-179 - Image in texteditor: - Using ImageInTextEditor in text editor's addon function.<commit_after>/*
 CKEditor Addons
 */
CKEDITOR.define("confirmChanges", {});
CKEDITOR.define("validateText", {});
CKEDITOR.define("getTextHistory", {});

CKEDITOR.newCommandWithExecution = function (executionFunc) {
    return {
        modes: {wysiwyg: 1, source: 1},// This command works in both editing modes.
        editorFocus: false,// This command will not auto focus editor before execution.
        canUndo: false,// This command requires no undo snapshot.
        exec: executionFunc
    }
};

CKEDITOR.plugins.add("documentSaver", {
    init: function (editor) {
        var pluginName = "documentSaver";
        editor.documentSnapshot = editor.getData();
        editor.blurHandler = function (event) {
            if (event.editor.checkDirty()) {
                event.editor.openDialog(pluginName);
            }
        };
        editor.focusHandler = function (event) {
            event.removeListener();
            event.editor.on('blur', event.editor.blurHandler);
        };
        var switchToolbarCommandFunction = function (event) {
            var element = event.element;
            if (event.elementMode == 1) {
                event.execCommand("toolbarswitch");
            }
            for (var key in CKEDITOR.instances) {
                var editor = CKEDITOR.instances[key];
                if (element == editor.element) {
                    return editor;
                }
            }
        };

        editor.on('blur', editor.blurHandler);

        function saveData(event, noCallback) {
            editor.documentSnapshot = event.getData();
            event.resetDirty();
            if (noCallback) {
                event.removeListener('blur', event.blurHandler);
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                event.on("focus", event.focusHandler);
            }
        }

        function switchModeCallback(e) {
            return function () {
                Imcms.BackgroundWorker.createTask({
                    showProcessWindow: true,
                    refreshPage: true
                })();
                $(e.element.$).click();
            };
        }

        var confirmBeforeSwitch = function (event) {
            var callback = switchModeCallback(event);
            event = switchToolbarCommandFunction(event);
            CKEDITOR.fireOnce("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmNoEvent = function (event, callback) {
            if (!callback) {
                event = switchToolbarCommandFunction(event);
            }
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            saveData(event, !callback);
        };

        var confirmWithEvent = function (event) {
            event = switchToolbarCommandFunction(event);
            var callback = Imcms.Events.getCallback("TextEditorRedirect");
            CKEDITOR.fire("confirmChangesEvent", {callback: callback}, event);
            event.resetDirty();
        };
        var confirmCommandWithEvent = CKEDITOR.newCommandWithExecution(confirmWithEvent);
        editor.addCommand("confirmChanges", confirmCommandWithEvent);
        editor.ui.addButton('confirm', {
            label: 'Save all changes',
            command: "confirmChanges",
            icon: "images/ic_apply.png"
        });

        var confirmCommandNoEvent = CKEDITOR.newCommandWithExecution(confirmNoEvent);
        editor.addCommand("confirmChangesWithoutEvent", confirmCommandNoEvent);

        var confirmCommandBeforeSwitch = CKEDITOR.newCommandWithExecution(confirmBeforeSwitch);
        editor.addCommand("confirmChangesBeforeSwitch", confirmCommandBeforeSwitch);

        var cancelCommandFunction = function (event) {
            var newEditor = switchToolbarCommandFunction(event),
                hideCommand = function (event) {
                    setTimeout(function () {
                        event.removeListener('instanceReady', hideCommand);
                        event.setData(event.documentSnapshot);
                        event.removeListener('blur', event.blurHandler);
                        event.focusManager.unlock();
                        event.element.$.blur();
                        event.focusManager.blur();
                        event.on("focus", event.focusHandler);
                    }, 1);
                };
            if (newEditor != event) {
                newEditor.on('instanceReady', hideCommand.bind(null, newEditor));

            } else {
                hideCommand(event);
            }
        };
        var cancelCommandDefinition = CKEDITOR.newCommandWithExecution(
            Imcms.Events.getCallbackOr("TextEditorRedirect", cancelCommandFunction)
        );
        editor.addCommand("cancelChanges", cancelCommandDefinition);
        editor.ui.addButton('cancel', {
            label: 'Cancel all changes and restore document to previous state',
            command: "cancelChanges",
            icon: "images/ic_cancel.png"
        });

        var saveCommandDefinition = CKEDITOR.newCommandWithExecution(function (event) {
            var $button = $('.' + event.id).find('.cke_button__savedata_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            confirmNoEvent(event, function () {
                $button.css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_save.png" + ")"
                });
            });
        });
        editor.addCommand("saveChanges", saveCommandDefinition);
        editor.ui.addButton('saveData', {
            label: 'Save all changes',
            command: "saveChanges",
            icon: "images/ic_save.png"
        });
    }
});
CKEDITOR.dialog.add("documentSaver", function (event) {
    return {
        title: 'Save changes',
        width: 200,
        height: 25,
        onOk: function () {
            event.execCommand("confirmChanges");
        },
        onCancel: function () {
            event.execCommand("cancelChanges");
        },
        onHide: function () {
            setTimeout(function () {
                event.focusManager.unlock();
                event.element.$.blur();
                event.focusManager.blur();
                $(event.focusManager.currentActive).blur();
            }, 500);
        },
        contents: [
            {
                id: 'general',
                label: 'Settings',
                elements: [
                    {
                        type: 'html',
                        onLoad: function (event) {
                            var $dialog = $(event.sender.parts.dialog.$);
                            $dialog.find(".cke_resizer.cke_resizer_ltr").hide(); // dialog resize triangle
                            // in Safari close button goes to wrong side,
                            $dialog.find(".cke_dialog_close_button").css("float", "right");
                        },
                        html: '
You have changed the text. Do you wish to save it?
'
                    }
                ]
            }
        ]
    };
});

CKEDITOR.defineToolbar = function (editor) {
    var prefix;

    if (editor.elementMode == 1) { // full-screen editor mode
        editor.config.maxToolbar = true;
        prefix = "max";

    } else {
        editor.config.maxToolbar = false;
        prefix = "min";
    }

    if (editor.element.data("contenttype") === "text") {
        return prefix + "PlainText";

    } else if (editor.element.data("contenttype") === "from-html") {
        return prefix + "TextToolbar";

    } else {
        return prefix + "HtmlToolbar";
    }
};

CKEDITOR.switchFormat = false;

CKEDITOR.plugins.add("switchFormatToHTML", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToHTML', {
            label: 'Switch format to HTML',
            command: "switchFormat",
            icon: "images/switch-between-html-and-text-mode.png"
        });
    }
});

CKEDITOR.plugins.add("switchFormatToText", {
    init: function (editor) {
        editor.ui.addButton('switchFormatToText', {
            label: 'Switch format to text',
            command: "switchFormat",
            icon: "images/plain_text.png"
        });
    }
});

CKEDITOR.plugins.add("fileBrowser", {
    init: function (editor) {

        var onChooseFile = function () {
            Imcms.Editors.Content.showDialog({
                onApply: $.proxy(onFileChosen, this),
                onCancel: $.proxy(onFileChosen, this)
            });
            editor.focusManager.blur();
            editor.element.$.blur();
        };
        var onFileChosen = function (data) {
            if (data) {
                editor.insertHtml('
', 'unfiltered_html');
            }
            editor.focusManager.focus();
            editor.element.$.focus();
        };

        var imageInTextEditor = new Imcms.Image.ImageInTextEditor(editor),
            openBrowserCommandDefinition = CKEDITOR.newCommandWithExecution(
                imageInTextEditor.onBrowserOpen.bind(imageInTextEditor)
            );
        editor.addCommand("openBrowser", openBrowserCommandDefinition);

        editor.ui.addButton('openBrowser', {
            label: 'Open Image Browser',
            command: "openBrowser",
            icon: "images/ic_images.png"
        });
    }
});

CKEDITOR.plugins.add("w3cValidator", {
    init: function (editor) {
        var w3cValidateCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__w3cvalidate_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("validateText", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + (data.result ? "images/ic_valid.png" : "images/ic_invalid.png") + ")"
                    });

                    if (!data.result) {
                        $(event.element.$).data("w3cValidateData", data);
                        event.execCommand("w3cValidateDialog", data);
                    }
                }
            }, event);
        };
        var w3cValidateCommandDefinition = CKEDITOR.newCommandWithExecution(w3cValidateCommand);
        editor.addCommand("w3cValidate", w3cValidateCommandDefinition);
        editor.addCommand("w3cValidateDialog", new CKEDITOR.dialogCommand("w3cValidationResultDialog"));

        editor.ui.addButton('w3cValidate', {
            label: 'Validate Content over W3C',
            command: "w3cValidate",
            icon: "images/ic_w3c.png"
        });
    }
});
CKEDITOR.dialog.add("w3cValidationResultDialog", function (event) {
    var $wrapper = $("
"),
        $content = $("
").addClass("imcms-w3c-errors").appendTo($wrapper),
        data = $(event.element.$).data("w3cValidateData");

    $("
").append($("
").text("Validation Output: " + data.data.errors.length + " Errors")).appendTo($content);

    data.data.errors.forEach(function (item, pos) {
        var $container = $("
").addClass("imcms-w3c-error").appendTo($content),
            $errorMessage = $("
").text(pos + 1 + ". " + item.message.charAt(0).toUpperCase() + item.message.slice(1)).appendTo($container),
            $sourceContainer = $("
").appendTo($container),
            $source = $("").addClass("language-html").html(item.line + ": " + item.source.replace(/(<([^>]+)>)/ig, "")).appendTo($sourceContainer);

        Prism.highlightElement($source[0]);
    });

    return {
        title: 'Validation Result Dialog',
        width: 600,
        minHeight: 250,
        contents: [
            {
                id: 'w3cValidation',
                label: 'Validation',
                elements: [
                    {
                        type: 'html',
                        html: $("
").append($wrapper).html()
                    }
                ]
            }
        ]
    };
});

CKEDITOR.plugins.add("textHistory", {
    init: function (editor) {
        var textHistoryCommand = function (event) {
            var $button = $('.' + event.id).find('.cke_button__texthistory_icon')
                .css({
                    backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_loader.gif" + ")"
                });
            //todo: Add message if content is invalid
            CKEDITOR.fire("getTextHistory", {
                callback: function (data) {
                    $button.css({
                        backgroundImage: "url(" + CKEDITOR.basePath + "images/ic_history.png" + ")"
                    });

                    $(event.element.$).data("textHistoryData", data);
                    event.execCommand("textHistoryDialog", data);
                }
            }, event);
        };
        var textHistoryCommandDefinition = CKEDITOR.newCommandWithExecution(textHistoryCommand);
        editor.addCommand("textHistory", textHistoryCommandDefinition);
        editor.addCommand("textHistoryDialog", new CKEDITOR.dialogCommand("textHistory"));

        editor.ui.addButton('textHistory', {
            label: 'Text History',
            command: "textHistory",
            icon: "images/ic_history.png"
        });
    }
});

CKEDITOR.dialog.add("textHistory", function (event) {
    var $wrapper = $("
").addClass("imcms-text-history"),
        $leftPanel = $("
").addClass("imcms-left-panel").appendTo($wrapper),

        $content = $("
").addClass("imcms-content")
            .css({
                "max-width": "600px",
                "float": "right"
            })
            .appendTo($wrapper),

        data = $(event.element.$).data("textHistoryData")
            .map(function (textHistoryData) {
                textHistoryData.modifiedDate = new Date(textHistoryData.modifiedDate);
                textHistoryData.type = (textHistoryData.type == "HTML")
                    ? "html"
                    : "from-html";
                return textHistoryData;
            })
            .sort(function (a, b) {
                return (a.modifiedDate > b.modifiedDate ? -1 : (a.modifiedDate == b.modifiedDate ? 0 : 1));
            }),

        groupedData = {},
        $selected = undefined,
        selectedItem,
        previousType;

    data.forEach(function (it) {
        var key = it.modifiedDate.format("dd/m/yy");

        if (!(key in groupedData)) {
            groupedData[key] = [];
        }

        groupedData[key].push(it);
    });

    var buttonsShowed = false;

    function addTextHistoryButton(text, onClick) {
        return $("<button>")
            .addClass("imcms-neutral")
            .css("float", "right")
            .html(text)
            .appendTo($wrapper)
            .click(onClick);
    }

    $.each(groupedData, function (key, list) {
        $("
").addClass("imcms-separator").text(key).appendTo($leftPanel);

        list.forEach(function (item) {
            $("
").appendTo($leftPanel)
                .append(item.modifiedDate.format("HH:MM:ss") + " | " + item.modifiedBy)
                .click(function () {
                    if (!buttonsShowed) {
                        addTextHistoryButton("View Page", function () {
                            if (selectedItem.type !== "html") {
                                $content.html($content.text());
                                selectedItem.type = "html";
                            }
                        });
                        addTextHistoryButton("View Source", function () {
                            if (selectedItem.type === "html") {
                                $content.text($content.html());
                                selectedItem.type = "from-html";
                            }
                        });
                        buttonsShowed = true;
                    }

                    if ($selected) {
                        $selected.removeClass("selected");
                    }

                    var callFunc = (item.type === "html")
                        ? "html"
                        : "text";

                    $content[callFunc](item.text);
                    $selected = $(this).addClass("selected");
                    selectedItem = item;
                    previousType = item.type;
                });
        })
    });

    return {
        title: 'Text History Dialog',
        width: 600,
        height: 400,
        contents: [
            {
                id: 'textHistory',
                label: 'Text History',
                elements: [
                    {
                        type: 'html',
                        onLoad: function () {
                            $("#" + this.domId).append($wrapper)
                        },
                        html: ""
                    }
                ]
            }
        ],
        buttons: [
            {
                id: "text history OK button",
                type: "button",
                label: "Write to textfield",
                title: "Write to textfield",
                "class":"cke_dialog_ui_button_ok",
                disabled: false,
                onClick: function () {
                    if (selectedItem) {
                        event.setData(""); // clear previous text
                        var contentType = $(event.element.$).data("contenttype");

                        var callFunc = (contentType === "html")
                            ? "insertHtml"
                            : "insertText";

                        event[callFunc](selectedItem.text);

                        if (selectedItem.type !== contentType) {
                            event.execCommand("switchFormat");
                        }
                    }
                }
            },
            CKEDITOR.dialog.cancelButton
        ]
    };
});<|endoftext|>


<commit_before>const { makeRoutesFilter, removeDuplicates } = require('./filters.js')

/**
 * returns an exact copy of the passed in object but with one
 * property changed
 */
const applyFilter = function(filter, object, prop) {
  return Object.assign({}, object, { [prop]: filter(object[prop]) })
}

// apply multiple filters to a single workBatch
const applyAdvisoryFilters = function(workBatch, filters) {
  if (!Array.isArray(filters)) filter = [filter]
  // filters should be pure functions accepting and returning one object
  return filters.reduce(
    (result, filter) => applyFilter(filter, result, 'advisories'),
    workBatch
  )
}

exports.cleanSubwayData = function(workBatches) {
  return workBatches.map(workBatch =>
    applyAdvisoryFilters(workBatch, [removeDuplicates])
  )
}

exports.filterByRoutes = function(workBatches, routesToKeep) {
  const routesFilter = makeRoutesFilter(routesToKeep)
  return workBatches.map(workBatch =>
    applyAdvisoryFilters(workBatch, [routesFilter])
  )
}
<commit_msg>Fix unused variable<commit_after>const { makeRoutesFilter, removeDuplicates } = require('./filters.js')

/**
 * returns an exact copy of the passed in object but with one
 * property changed
 */
const applyFilter = function(filter, object, prop) {
  return Object.assign({}, object, { [prop]: filter(object[prop]) })
}

// apply multiple filters to a single workBatch
const applyAdvisoryFilters = function(workBatch, filters) {
  // eslint-disable-line no-param-reassign
  if (!Array.isArray(filters)) filters = [filters]

  // filters should be pure functions accepting and returning one object
  return filters.reduce(
    (result, filter) => applyFilter(filter, result, 'advisories'),
    workBatch
  )
}

exports.cleanSubwayData = function(workBatches) {
  return workBatches.map(workBatch =>
    applyAdvisoryFilters(workBatch, [removeDuplicates])
  )
}

exports.filterByRoutes = function(workBatches, routesToKeep) {
  const routesFilter = makeRoutesFilter(routesToKeep)
  return workBatches.map(workBatch =>
    applyAdvisoryFilters(workBatch, [routesFilter])
  )
}
<|endoftext|>


<commit_before>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;

// internal deps
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var POGarmentJobOrderFabric = DLModels.po.POGarmentJobOrderFabric;
var PurchaseOrderGroup = DLModels.po.PurchaseOrderGroup;
var moduleId = 'POTJ'
var poType = map.po.type.POGarmentJobOrderFabric;
var generateCode = require('../.././utils/code-generator');

module.exports = class POGarmentJobOrderFabricManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.POGarmentJobOrderFabricCollection = this.db.use(map.po.collection.PurchaseOrder);

        var PurchaseOrderGroupManager = require('./purchase-order-group-manager');
        this.purchaseOrderGroupManager = new PurchaseOrderGroupManager(db, user);

        var PurchaseOrderManager = require("./purchase-order-manager");
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);

        this.PurchaseOrderGroupCollection = this.db.use(map.po.collection.PurchaseOrderGroup);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var filter = {
                _deleted: false,
                _type: poType
            };

            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterRONo = {
                    'RONo': {
                        '$regex': regex
                    }
                };
                var filterRefPONo = {
                    'RefPONo': {
                        '$regex': regex
                    }
                };
                var filterPONo = {
                    'PONo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterRONo, filterRefPONo, filterPONo]
                };

                query['$and'].push($or);
            }

            this.POGarmentJobOrderFabricCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(POGarmentJobOrderFabrics => {
                    resolve(POGarmentJobOrderFabrics);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    readAllPurchaseOrderGroup(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var type = {
                _type: poType
            }

            var query = {
                '$and': [deleted, type]
            };

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterPODLNo = {
                    'PODLNo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterPODLNo]
                };

                query['$and'].push($or);
            }

            this.PurchaseOrderGroupCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(PurchaseOrderGroups => {
                    resolve(PurchaseOrderGroups);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByPONo(poNo) {
        return new Promise((resolve, reject) => {
            if (poNo === '')
                resolve(null);
            var query = {
                PONo: poNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleOrDefaultByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.POGarmentJobOrderFabricCollection
                .single(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleOrDefaultByQuery(query) {
        return new Promise((resolve, reject) => {
            this.POGarmentJobOrderFabricCollection
                .singleOrDefault(query)
                .then(fabric => {
                    resolve(fabric);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrderFabric(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {
            poGarmentJobOrderFabric.PONo = generateCode(moduleId)
            this._validate(poGarmentJobOrderFabric)
                .then(validpoGarmentJobOrderFabric => {
                    this.purchaseOrderManager.create(validpoGarmentJobOrderFabric)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    createGroup(items) {
        return new Promise((resolve, reject) => {
            var newPOGroup = new PurchaseOrderGroup()
            newPOGroup.PODLNo = generateCode('PODL/GJOF')
            newPOGroup._type = poType

            var _tasks = [];

            for (var item of items) {
                _tasks.push(this.getByPONo(item))
            }

            Promise.all(_tasks)
                .then(results => {
                    newPOGroup.items = results
                    this.purchaseOrderGroupManager.create(newPOGroup)
                        .then(id => {
                            for (var data of newPOGroup.items) {
                                data.PODLNo = newPOGroup.PODLNo
                                this.update(data)
                            }

                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    update(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrderFabric(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {
            this._validate(poGarmentJobOrderFabric)
                .then(validpoGarmentJobOrderFabric => {
                    this.purchaseOrderManager.update(validpoGarmentJobOrderFabric)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        })
    }

    delete(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrder(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {

            poGarmentJobOrderFabric._deleted = true;
            this.purchaseOrderManager.delete(poGarmentJobOrderFabric)
                .then(id => {
                    resolve(id);
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    _validate(poGarmentJobOrderFabric) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = poGarmentJobOrderFabric;

            var getPOGarmentJobOrderFabricPromise = this.POGarmentJobOrderFabricCollection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        // code: valid.code
                    }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getPOGarmentJobOrderFabricPromise])
                .then(results => {
                    var _module = results[0];

                    if (!valid.PRNo || valid.PRNo == '')
                        errors["PRNo"] = "Nomor PR tidak boleh kosong";
                    if (!valid.PRNo || valid.PRNo == '')
                        errors["RONo"] = "Nomor RO tidak boleh kosong";
                    if (!valid.article || valid.article == '')
                        errors["article"] = "Artikel tidak boleh kosong";

                    if (!valid.buyer._id || valid.buyer._id == '')
                        errors["buyerId"] = "Nama Pembeli tidak boleh kosong";

                    this.purchaseOrderManager._validatePO(valid, errors);

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new PurchaseOrder(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
    // ====================================PO DL===========================================

    readAllPurchaseOrderGroup(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var type = {
                _type: poType
            }

            var query = {
                '$and': [deleted, type]
            };

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterPODLNo = {
                    'PODLNo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterPODLNo]
                };

                query['$and'].push($or);
            }

            this.PurchaseOrderGroupCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(PurchaseOrderGroups => {
                    resolve(PurchaseOrderGroups);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getPurchaseOrderGroupById(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSinglePurchaseOrderGroupByQuery(query) {
        return new Promise((resolve, reject) => {
            this.PurchaseOrderGroupCollection
                .single(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getByPONo(poNo) {
        return new Promise((resolve, reject) => {
            if (poNo === '')
                resolve(null);
            var query = {
                PONo: poNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    createGroup(items) {
        return new Promise((resolve, reject) => {
            var newPOGroup = new PurchaseOrderGroup()

            newPOGroup.PODLNo = generateCode('PODL/GJOF')
            newPOGroup._type = poType

            var _tasks = [];

            for (var item of items) {
                _tasks.push(this.getByPONo(item))
            }

            Promise.all(_tasks)
                .then(results => {
                    newPOGroup.items = results
                    this.purchaseOrderGroupManager.create(newPOGroup)
                        .then(id => {
                            for (var data of newPOGroup.items) {
                                data.PODLNo = newPOGroup.PODLNo
                                this.update(data)
                                    .then(id => {
                                        resolve(id);
                                    })
                                    .catch(e => {
                                        reject(e);
                                    });
                            }
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
}<commit_msg>update po garment jo fabric<commit_after>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;

// internal deps
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var POGarmentJobOrderFabric = DLModels.po.POGarmentJobOrderFabric;
var PurchaseOrderGroup = DLModels.po.PurchaseOrderGroup;
var moduleId = 'POTJ'
var poType = map.po.type.POGarmentJobOrderFabric;
var generateCode = require('../.././utils/code-generator');

module.exports = class POGarmentJobOrderFabricManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.POGarmentJobOrderFabricCollection = this.db.use(map.po.collection.PurchaseOrder);

        var PurchaseOrderGroupManager = require('./purchase-order-group-manager');
        this.purchaseOrderGroupManager = new PurchaseOrderGroupManager(db, user);

        var PurchaseOrderManager = require("./purchase-order-manager");
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);

        this.PurchaseOrderGroupCollection = this.db.use(map.po.collection.PurchaseOrderGroup);
    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var filter = {
                _deleted: false,
                _type: poType
            };

            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterRONo = {
                    'RONo': {
                        '$regex': regex
                    }
                };
                var filterRefPONo = {
                    'RefPONo': {
                        '$regex': regex
                    }
                };
                var filterPONo = {
                    'PONo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterRONo, filterRefPONo, filterPONo]
                };

                query['$and'].push($or);
            }

            this.POGarmentJobOrderFabricCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(POGarmentJobOrderFabrics => {
                    resolve(POGarmentJobOrderFabrics);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    readAllPurchaseOrderGroup(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var type = {
                _type: poType
            }

            var query = {
                '$and': [deleted, type]
            };

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterPODLNo = {
                    'PODLNo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterPODLNo]
                };

                query['$and'].push($or);
            }

            this.PurchaseOrderGroupCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(PurchaseOrderGroups => {
                    resolve(PurchaseOrderGroups);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByPONo(poNo) {
        return new Promise((resolve, reject) => {
            if (poNo === '')
                resolve(null);
            var query = {
                PONo: poNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleOrDefaultByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.POGarmentJobOrderFabricCollection
                .single(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleOrDefaultByQuery(query) {
        return new Promise((resolve, reject) => {
            this.POGarmentJobOrderFabricCollection
                .singleOrDefault(query)
                .then(fabric => {
                    resolve(fabric);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrderFabric(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {
            poGarmentJobOrderFabric.PONo = generateCode(moduleId)
            this._validate(poGarmentJobOrderFabric)
                .then(validpoGarmentJobOrderFabric => {
                    this.purchaseOrderManager.create(validpoGarmentJobOrderFabric)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    createGroup(items) {
        return new Promise((resolve, reject) => {
            var newPOGroup = new PurchaseOrderGroup()
            newPOGroup.PODLNo = generateCode('PODL/GJOF')
            newPOGroup._type = poType

            var _tasks = [];

            for (var item of items) {
                _tasks.push(this.getByPONo(item))
            }

            Promise.all(_tasks)
                .then(results => {
                    newPOGroup.items = results
                    this.purchaseOrderGroupManager.create(newPOGroup)
                        .then(id => {
                            for (var data of newPOGroup.items) {
                                data.PODLNo = newPOGroup.PODLNo
                                this.update(data)
                            }

                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    update(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrderFabric(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {
            this._validate(poGarmentJobOrderFabric)
                .then(validpoGarmentJobOrderFabric => {
                    this.purchaseOrderManager.update(validpoGarmentJobOrderFabric)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        })
    }

    delete(poGarmentJobOrderFabric) {
        poGarmentJobOrderFabric = new POGarmentJobOrderFabric(poGarmentJobOrderFabric);
        return new Promise((resolve, reject) => {

            poGarmentJobOrderFabric._deleted = true;
            this.purchaseOrderManager.delete(poGarmentJobOrderFabric)
                .then(id => {
                    resolve(id);
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    _validate(poGarmentJobOrderFabric) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = poGarmentJobOrderFabric;

            var getPOGarmentJobOrderFabricPromise = this.POGarmentJobOrderFabricCollection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        // code: valid.code
                    }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getPOGarmentJobOrderFabricPromise])
                .then(results => {
                    var _module = results[0];

                    if (!valid.PRNo || valid.PRNo == '')
                        errors["PRNo"] = "Nomor PR tidak boleh kosong";
                    if (!valid.PRNo || valid.PRNo == '')
                        errors["RONo"] = "Nomor RO tidak boleh kosong";
                    if (!valid.article || valid.article == '')
                        errors["article"] = "Artikel tidak boleh kosong";

                    if (!valid.buyer._id || valid.buyer._id == '')
                        errors["buyerId"] = "Nama Pembeli tidak boleh kosong";

                    this.purchaseOrderManager._validatePO(valid, errors);

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new PurchaseOrder(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
    // ====================================PO DL===========================================

    readAllPurchaseOrderGroup(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false
            };
            var type = {
                _type: poType
            }

            var query = {
                '$and': [deleted, type]
            };

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterPODLNo = {
                    'PODLNo': {
                        '$regex': regex
                    }
                };

                var $or = {
                    '$or': [filterPODLNo]
                };

                query['$and'].push($or);
            }

            this.PurchaseOrderGroupCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(PurchaseOrderGroups => {
                    resolve(PurchaseOrderGroups);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getPurchaseOrderGroupById(id) {
        return new Promise((resolve, reject) => {
            if (id === '')
                resolve(null);
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSinglePurchaseOrderGroupByQuery(query) {
        return new Promise((resolve, reject) => {
            this.PurchaseOrderGroupCollection
                .single(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getByPONo(poNo) {
        return new Promise((resolve, reject) => {
            if (poNo === '')
                resolve(null);
            var query = {
                PONo: poNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    createGroup(items) {
        return new Promise((resolve, reject) => {
            var newPOGroup = new PurchaseOrderGroup()

            newPOGroup.PODLNo = generateCode('PODL/GJOF')
            newPOGroup._type = poType

            var _tasks = [];

            for (var item of items) {
                _tasks.push(this.getByPONo(item))
            }

            Promise.all(_tasks)
                .then(results => {
                    newPOGroup.items = results
                    this.purchaseOrderGroupManager.create(newPOGroup)
                        .then(id => {
                            for (var data of newPOGroup.items) {
                                data.PODLNo = newPOGroup.PODLNo
                                this.update(data)
                                    .then(id => {
                                        resolve(id);
                                    })
                                    .catch(e => {
                                        reject(e);
                                    });
                            }
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
}<|endoftext|>


<commit_before>/* global require, module, process, console, __dirname */
/* jshint -W097 */
'use strict';

var
  _              = require('underscore'),
  async          = require('async'),
  respFormatter  = require('src/lib/responseFormatter'),
  errors         = require('src/lib/errors'),
  RequestUtil    = require('src/lib/apiRequestUtil'),
  slugger        = require('src/lib/slugger'),
  Article        = require('../../models/blog/Article'),
  TagsController = require('./TagsController');

var ArticlesController = {

  getOne: function(req, res, next) {

    var
      r        = new RequestUtil(req),
      criteria = _.extend({ '_id': req.params.article_id }, r.query);

    Article
      .findOne(criteria)
      .populate(r.expands)
      .exec(function(err,model) {
        /* istanbul ignore next */
        if (err) {
          console.log(err);
          return next( new errors.App(err) );
        }
        if (!model) {
          return next( new errors.NotFound() );
        }

        var meta = r.getMeta();
        res.json(respFormatter(model, meta));
      });
  },

  getAll: function(req, res, next) {
    var r = new RequestUtil(req);

    Article.paginate(r.query, r.page, r.limit, function(err, pageCount, paginatedResults, itemCount) {
      /* istanbul ignore next */
      if (err) {
        next( new errors.App(err) );
        return;
      }

      var meta = r.getMeta(null, { itemCount: itemCount, pageCount: pageCount });

      res.json(respFormatter(paginatedResults, meta));

    }, r.options);

  },

  create: function(req, res, next) {

    var slug, tags, model, r = new RequestUtil(req);

    async.series([

      // get the slug (it's async because it ensures that the slug is not
      // already used and if so, it adds a numeric suffix)
      function(callback) {
        slugger(Article, req.body.title, null, function(articleSlug) {
          slug = articleSlug;
          callback();
        });
      },

      // get the tags IDs (and create the tags if they don't exist)
      function(callback) {
        TagsController.retrieveAndCreate(req, function(articleTags) {
          tags = articleTags;
          callback();
        });
      },

      // create the Article
      function(callback) {
        model = new Article(); // create a new instance of the Article model

        // set the article attributes
        model.title        = req.body.title;
        model.slug         = slug;
        model.excerpt      = req.body.excerpt;
        model.body         = req.body.body;
        model.author       = req.body.author_id;
        model.owner        = req.user.userId;
        model.published    = req.body.published;
        model.published_at = req.body.publish_date;
        model.commentable  = req.body.commentable;
        model.tags         = tags;

        model.save(callback);
      },

      // expand the relations
      function(callback) {
        model.populate(r.expands, callback);
      }

    ], function(err) {

      /* istanbul ignore next */
      if (err) {
        return next( new errors.App(err) );
      }

      var meta = r.getMeta(model);
      res.json(respFormatter(model, meta));

    });

  },

  update: function(req, res, next) {

    var slug, tags, model, r = new RequestUtil(req);

    async.series([

      // retrieve the model
      function(callback) {
        Article.findById(req.params.article_id, function(err, articleModel) {
          /* istanbul ignore next */
          if (err) { return callback(err); }
          /* istanbul ignore next */
          if (!articleModel) { return callback( new errors.NotFound() ); }

          model = articleModel;
          callback();
        });
      },

      // get the slug (it's async because it ensures that the slug is not
      // already used and if so, it adds a numeric suffix)
      function(callback) {
        slugger(Article, req.body.title, req.body.slug, function(articleSlug) {
          slug = articleSlug;
          callback();
        });
      },

      // get the tags IDs (and create the tags if they don't exist)
      function(callback) {
        TagsController.retrieveAndCreate(req, function(articleTags) {
          tags = articleTags;
          callback();
        });
      },

      // update the Article
      function(callback) {

        // set the article attributes
        model.title        = req.body.title;
        model.slug         = slug;
        model.excerpt      = req.body.excerpt;
        model.body         = req.body.body;
        model.author       = req.body.author_id;
        model.owner        = req.user.userId;
        model.published    = req.body.published;
        model.published_at = req.body.publish_date;
        model.commentable  = req.body.commentable;
        model.tags         = tags;

        model.save(callback);
      },

      // expand the relations
      function(callback) {
        model.populate(r.expands, callback);
      }

    ], function(err) {

      /* istanbul ignore next */
      if (err) {
        var error = (err.name === 'HttpNotFoundError') ? err : new errors.App(err);
        return next(error);
      }

      var meta = r.getMeta();
      res.json(respFormatter(model, meta));

    });
  },

  delete: function(req, res, next) {

    var r = new RequestUtil(req);

    Article
      .findById(req.params.article_id)
      .populate(r.expands)
      .exec(function(err,model) {

        /* istanbul ignore next */
        if (err) {
          return next( new errors.App(err) );
        }
        if (!model) {
          return next( new errors.NotFound() );
        }

        model.remove(function() {
          res.json(respFormatter(model));
        });
    });

  }

};

module.exports = ArticlesController;
<commit_msg>feat: improve error handling<commit_after>/* global require, module, process, console, __dirname */
/* jshint -W097 */
'use strict';

var
  _              = require('underscore'),
  async          = require('async'),
  respFormatter  = require('src/lib/responseFormatter'),
  RequestUtil    = require('src/lib/apiRequestUtil'),
  errors         = require('src/lib/errors'),
  slugger        = require('src/lib/slugger'),
  Article        = require('../../models/blog/Article'),
  TagsController = require('./TagsController');

var ArticlesController = {

  getOne: function(req, res, next) {

    var
      r        = new RequestUtil(req),
      criteria = _.extend({ '_id': req.params.article_id }, r.query);

    Article
      .findOne(criteria)
      .populate(r.expands)
      .exec(function(err, model) {
        /* istanbul ignore next */
        if (err)    { return next(err); }
        if (!model) { return next(new errors.NotFound()); }

        var meta = r.getMeta();
        res.json(respFormatter(model, meta));
      });
  },

  getAll: function(req, res, next) {
    var r = new RequestUtil(req);

    Article.paginate(r.query, r.page, r.limit, function(err, pageCount, paginatedResults, itemCount) {
      /* istanbul ignore next */
      if (err) { return next(err); }

      var meta = r.getMeta(null, { itemCount: itemCount, pageCount: pageCount });

      res.json(respFormatter(paginatedResults, meta));

    }, r.options);

  },

  create: function(req, res, next) {

    var slug, tags, model, r = new RequestUtil(req);

    async.series([

      // get the slug (it's async because it ensures that the slug is not
      // already used and if so, it adds a numeric suffix)
      function(callback) {
        slugger(Article, req.body.title, null, function(articleSlug) {
          slug = articleSlug;
          callback();
        });
      },

      // get the tags IDs (and create the tags if they don't exist)
      function(callback) {
        TagsController.retrieveAndCreate(req, function(articleTags) {
          tags = articleTags;
          callback();
        });
      },

      // create the Article
      function(callback) {
        model = new Article(); // create a new instance of the Article model

        // set the article attributes
        model.title        = req.body.title;
        model.slug         = slug;
        model.excerpt      = req.body.excerpt;
        model.body         = req.body.body;
        model.author       = req.body.author_id;
        model.owner        = req.user.userId;
        model.published    = req.body.published;
        model.published_at = req.body.publish_date;
        model.commentable  = req.body.commentable;
        model.tags         = tags;

        model.save(callback);
      },

      // expand the relations
      function(callback) {
        model.populate(r.expands, callback);
      }

    ], function(err) {

      /* istanbul ignore next */
      if (err) { return next(err); }

      var meta = r.getMeta(model);
      res.json(respFormatter(model, meta));

    });

  },

  update: function(req, res, next) {

    var slug, tags, model, r = new RequestUtil(req);

    async.series([

      // retrieve the model
      function(callback) {
        Article.findById(req.params.article_id, function(err, articleModel) {
          /* istanbul ignore next */
          if (err)           { return callback(err); }
          /* istanbul ignore next */
          if (!articleModel) { return callback(new errors.NotFound()); }

          model = articleModel;
          callback();
        });
      },

      // get the slug (it's async because it ensures that the slug is not
      // already used and if so, it adds a numeric suffix)
      function(callback) {
        slugger(Article, req.body.title, req.body.slug, function(articleSlug) {
          slug = articleSlug;
          callback();
        });
      },

      // get the tags IDs (and create the tags if they don't exist)
      function(callback) {
        TagsController.retrieveAndCreate(req, function(articleTags) {
          tags = articleTags;
          callback();
        });
      },

      // update the Article
      function(callback) {

        // set the article attributes
        model.title        = req.body.title;
        model.slug         = slug;
        model.excerpt      = req.body.excerpt;
        model.body         = req.body.body;
        model.author       = req.body.author_id;
        model.owner        = req.user.userId;
        model.published    = req.body.published;
        model.published_at = req.body.publish_date;
        model.commentable  = req.body.commentable;
        model.tags         = tags;

        model.save(callback);
      },

      // expand the relations
      function(callback) {
        model.populate(r.expands, callback);
      }

    ], function(err) {

      /* istanbul ignore next */
      if (err) {
        return next(err);
      }

      var meta = r.getMeta();
      res.json(respFormatter(model, meta));

    });
  },

  delete: function(req, res, next) {

    var r = new RequestUtil(req);

    Article
      .findById(req.params.article_id)
      .populate(r.expands)
      .exec(function(err, model) {

        /* istanbul ignore next */
        if (err)    { return next(err); }
        if (!model) { return next( new errors.NotFound() ); }

        model.remove(function() {
          res.json(respFormatter(model));
        });
    });
  }

};

module.exports = ArticlesController;
<|endoftext|>


<commit_before>import React from 'react';
import SPELLS from 'common/SPELLS';

import Analyzer from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';

import SpellIcon from 'common/SpellIcon';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';

import { formatNumber } from 'common/format';
import { TooltipElement } from 'common/Tooltip';

const debug = false;

class Celestial extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  petID = null;
  _pets = {};
  soothHealing = 0;
  soothOverHealing = 0;
  envelopHealing = 0;
  evelopOverhealing = 0;
  healing = 0;
  overhealing = 0;
  count = 0;

  constructor(...args) {
    super(...args);
    this._pets = this.owner.report.friendlyPets.filter(pet => pet.petOwner === this.owner.player.id);
  }

  on_byPlayer_summon(event) {
    this.petID = event.targetID;
    debug && console.log(`${event.ability.guid === SPELLS.INVOKE_CHIJI_THE_RED_CRANE_TALENT.id ? 'Chi-Ji' : 'Yu\'lon'} Summoned: ${this.petID}`);
  }

  on_heal(event) {
    if (event.ability.guid === SPELLS.ENVELOPING_BREATH.id) {
      this.envelopHealing += (event.amount || 0) + (event.absorbed || 0);
      this.evelopOverhealing += event.overheal || 0;
    }
    if (event.sourceID === this.petID && event.ability.guid === SPELLS.SOOTHING_BREATH.id) {
      this.soothHealing += (event.amount || 0) + (event.absorbed || 0);
      this.soothOverHealing += event.overheal || 0;
    }
    this.healing = this.soothHealing + this.envelopHealing;
  }

  statistic() {
    if (!this.selectedCombatant.hasTalent(SPELLS.INVOKE_CHIJI_THE_RED_CRANE_TALENT.id)) {
      return (
        <>
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<SpellIcon id={SPELLS.SOOTHING_BREATH.id} />}
            value={`${formatNumber(this.soothHealing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by Soothing Breath.">
                Soothing Breath Healing
              </TooltipElement>
            )}
          />
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<SpellIcon id={SPELLS.ENVELOPING_BREATH.id} />}
            value={`${formatNumber(this.envelopHealing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by the Enveloping Breath.">
                Enveloping Breath Healing
              </TooltipElement>
            )}
          />
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<><SpellIcon id={SPELLS.ENVELOPING_BREATH.id} /><SpellIcon id={SPELLS.SOOTHING_BREATH.id} /></>}
            value={`${formatNumber(this.healing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by both Enveloping & Soothing Breath.">
                Total Healing Contributed
              </TooltipElement>
            )}
          />
        </>
      );
    }
    return <span />;
  }

  on_fightend() {
    if (debug) {
      console.log(`Celestial ID: ${this.petID}`);
    }
  }
}

export default Celestial;
<commit_msg>Remove unused variable<commit_after>import React from 'react';
import SPELLS from 'common/SPELLS';

import Analyzer from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';

import SpellIcon from 'common/SpellIcon';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';

import { formatNumber } from 'common/format';
import { TooltipElement } from 'common/Tooltip';

const debug = false;

class Celestial extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  petID = null;
  soothHealing = 0;
  soothOverHealing = 0;
  envelopHealing = 0;
  evelopOverhealing = 0;
  healing = 0;
  overhealing = 0;
  count = 0;

  constructor(...args) {
    super(...args);
  }

  on_byPlayer_summon(event) {
    this.petID = event.targetID;
    debug && console.log(`${event.ability.guid === SPELLS.INVOKE_CHIJI_THE_RED_CRANE_TALENT.id ? 'Chi-Ji' : 'Yu\'lon'} Summoned: ${this.petID}`);
  }

  on_heal(event) {
    if (event.ability.guid === SPELLS.ENVELOPING_BREATH.id) {
      this.envelopHealing += (event.amount || 0) + (event.absorbed || 0);
      this.evelopOverhealing += event.overheal || 0;
    }
    if (event.sourceID === this.petID && event.ability.guid === SPELLS.SOOTHING_BREATH.id) {
      this.soothHealing += (event.amount || 0) + (event.absorbed || 0);
      this.soothOverHealing += event.overheal || 0;
    }
    this.healing = this.soothHealing + this.envelopHealing;
  }

  statistic() {
    if (!this.selectedCombatant.hasTalent(SPELLS.INVOKE_CHIJI_THE_RED_CRANE_TALENT.id)) {
      return (
        <>
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<SpellIcon id={SPELLS.SOOTHING_BREATH.id} />}
            value={`${formatNumber(this.soothHealing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by Soothing Breath.">
                Soothing Breath Healing
              </TooltipElement>
            )}
          />
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<SpellIcon id={SPELLS.ENVELOPING_BREATH.id} />}
            value={`${formatNumber(this.envelopHealing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by the Enveloping Breath.">
                Enveloping Breath Healing
              </TooltipElement>
            )}
          />
          <StatisticBox
            position={STATISTIC_ORDER.OPTIONAL(50)}
            icon={<><SpellIcon id={SPELLS.ENVELOPING_BREATH.id} /><SpellIcon id={SPELLS.SOOTHING_BREATH.id} /></>}
            value={`${formatNumber(this.healing)}`}
            label={(
              <TooltipElement content="This is the effective healing contributed by both Enveloping & Soothing Breath.">
                Total Healing Contributed
              </TooltipElement>
            )}
          />
        </>
      );
    }
    return <span />;
  }

  on_fightend() {
    if (debug) {
      console.log(`Celestial ID: ${this.petID}`);
    }
  }
}

export default Celestial;
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define(['../base/Object', './EventBus', "sap/base/assert"],
	function(BaseObject, EventBus, assert) {
	"use strict";

		var _EVENT_ID = "sapUiIntervalTrigger-event";

		/**
		 * Creates an instance of EventBus.
		 *
		 * @class Provides a trigger that triggers in a set interval and calls all
		 *        registered listeners. If the interval is <= 0 the trigger is
		 *        switched off and won't trigger at all.
		 * @param {int}
		 *            iInterval is the interval the trigger should be used. If the
		 *            trigger is >0 triggering starts/runs and if the interval is
		 *            set to <=0 triggering stops.
		 *
		 * @extends sap.ui.base.Object
		 * @author SAP SE
		 * @version ${version}
		 * @public
		 * @since 1.11.0
		 * @alias sap.ui.core.IntervalTrigger
		 */
		var IntervalTrigger = BaseObject.extend("sap.ui.core.IntervalTrigger", {
			constructor : function(iInterval) {
				BaseObject.apply(this);

				this._oEventBus = new EventBus();

				this._delayedCallId = null;
				this._trigger = trigger.bind(this);

				this._iInterval = 0;
				if (iInterval) {
					this.setInterval(iInterval);
				}
			}
		});

		/**
		 * This is the function that will be used for triggering.
		 *
		 * @private
		 */
		var trigger = function() {
			clearTimeout(this._delayedCallId);

			// if interval is active and there are registered listeners
			var bHasListeners = this._oEventBus._defaultChannel.hasListeners(_EVENT_ID);
			if (this._iInterval > 0 && bHasListeners) {
				this._oEventBus.publish(_EVENT_ID);

				this._delayedCallId = setTimeout(this._trigger, this._iInterval);
			}
		};

		/**
		 * Destructor method for objects.
		 *
		 * @public
		 */
		IntervalTrigger.prototype.destroy = function() {
			BaseObject.prototype.destroy.apply(this, arguments);

			delete this._trigger;

			this._oEventBus.destroy();
			delete this._oEventBus;
		};

		/**
		 * Sets the trigger interval. If the value is >0 triggering will start if
		 * there are any registered listeners. If the interval is set to <=0
		 * triggering will stop.
		 *
		 * @public
		 * @param {int}
		 *            iInterval sets the interval in milliseconds when a new
		 *            triggering should occur.
		 */
		IntervalTrigger.prototype.setInterval = function(iInterval) {
			assert((typeof iInterval === "number"), "Interval must be an integer value");

			// only change and (re)trigger if the interval is different
			if (this._iInterval !== iInterval) {
				this._iInterval = iInterval;
				this._trigger();
			}
		};

		/**
		 * Adds a listener to the list that should be triggered.
		 *
		 * @public
		 * @param {function}
		 *            fnFunction is the called function that should be called when
		 *            the trigger want to trigger the listener.
		 * @param {object}
		 *            [oListener] that should be triggered.
		 */
		IntervalTrigger.prototype.addListener = function(fnFunction, oListener) {
			this._oEventBus.subscribe(_EVENT_ID, fnFunction, oListener);

			this._trigger();
		};

		/**
		 * Removes corresponding listener from list.
		 *
		 * @public
		 * @param {function}
		 *            fnFunction is the previously registered function
		 * @param {object}
		 *            [oListener] that should be removed
		 */
		IntervalTrigger.prototype.removeListener = function(fnFunction, oListener) {
			this._oEventBus.unsubscribe(_EVENT_ID, fnFunction, oListener);
		};

		/*
		 * @see sap.ui.base.Object#getInterface
		 */
		IntervalTrigger.prototype.getInterface = function() {
			return this;
		};

	/**
	 * Central instance of the IntervalTrigger (Singleton)
	 *
	 * @example
Create instance

	 *
	 * sap.ui.require(["sap/ui/core/IntervalTrigger"], function(IntervalTrigger) {
	 *     var fnDoIt = function(){
	 *         // my code
	 *     }
	 *     IntervalTrigger.addListener(fnDoIt, this);
	 *     IntervalTrigger.removeListener(fnDoIt, this);
	 * });
	 *
	 * Note: Only addListener and removeListener functions are exposed such that the
	 * singleton can neither be destroyed nor the interval can be modified.
	 *
	 * @return {sap.ui.core.IntervalTrigger} the instance with 200ms interval
	 */
	var getInstance = function() {

		var oIntervalTrigger = new IntervalTrigger(200);
		getInstance = function() {
			return oIntervalTrigger;
		};
		return oIntervalTrigger;
	};

	/**
	 * Adds a listener to the list that should be triggered.
	 *
	 * @public
	 * @since 1.61
	 * @param {function} fnFunction is the called function that should be called when
	 *            the trigger want to trigger the listener.
	 * @param {object} [oListener] that should be triggered.
	 */
	IntervalTrigger.addListener = function(fnFunction, oListener) {
		getInstance().addListener(fnFunction, oListener);
	};

	/**
	 * Removes corresponding listener from list.
	 *
	 * @public
	 * @since 1.61
	 * @param {function} fnFunction is the previously registered function
	 * @param {object} [oListener] that should be removed
	 */
	IntervalTrigger.removeListener = function(fnFunction, oListener) {
		getInstance().removeListener(fnFunction, oListener);
	};

	return IntervalTrigger;

});<commit_msg>[FIX] IntervalTrigger: call clearTimeout only once per timer<commit_after>/*!
 * ${copyright}
 */
sap.ui.define(['../base/Object', './EventBus', "sap/base/assert"],
	function(BaseObject, EventBus, assert) {
	"use strict";

		var _EVENT_ID = "sapUiIntervalTrigger-event";

		/**
		 * Creates an instance of EventBus.
		 *
		 * @class Provides a trigger that triggers in a set interval and calls all
		 *        registered listeners. If the interval is <= 0 the trigger is
		 *        switched off and won't trigger at all.
		 * @param {int}
		 *            iInterval is the interval the trigger should be used. If the
		 *            trigger is >0 triggering starts/runs and if the interval is
		 *            set to <=0 triggering stops.
		 *
		 * @extends sap.ui.base.Object
		 * @author SAP SE
		 * @version ${version}
		 * @public
		 * @since 1.11.0
		 * @alias sap.ui.core.IntervalTrigger
		 */
		var IntervalTrigger = BaseObject.extend("sap.ui.core.IntervalTrigger", {
			constructor : function(iInterval) {
				BaseObject.apply(this);

				this._oEventBus = new EventBus();

				this._delayedCallId = null;
				this._trigger = trigger.bind(this);

				this._iInterval = 0;
				if (iInterval) {
					this.setInterval(iInterval);
				}
			}
		});

		/**
		 * This is the function that will be used for triggering.
		 *
		 * @private
		 */
		var trigger = function() {
			if (this._delayedCallId) {
				 clearTimeout(this._delayedCallId);
				 this._delayedCallId = null;
			}

			// if interval is active and there are registered listeners
			var bHasListeners = this._oEventBus._defaultChannel.hasListeners(_EVENT_ID);
			if (this._iInterval > 0 && bHasListeners) {
				this._oEventBus.publish(_EVENT_ID);

				this._delayedCallId = setTimeout(this._trigger, this._iInterval);
			}
		};

		/**
		 * Destructor method for objects.
		 *
		 * @public
		 */
		IntervalTrigger.prototype.destroy = function() {
			BaseObject.prototype.destroy.apply(this, arguments);

			if (this._delayedCallId) {
				 clearTimeout(this._delayedCallId);
				 this._delayedCallId = null;
			}
			delete this._trigger;

			this._oEventBus.destroy();
			delete this._oEventBus;
		};

		/**
		 * Sets the trigger interval. If the value is >0 triggering will start if
		 * there are any registered listeners. If the interval is set to <=0
		 * triggering will stop.
		 *
		 * @public
		 * @param {int}
		 *            iInterval sets the interval in milliseconds when a new
		 *            triggering should occur.
		 */
		IntervalTrigger.prototype.setInterval = function(iInterval) {
			assert((typeof iInterval === "number"), "Interval must be an integer value");

			// only change and (re)trigger if the interval is different
			if (this._iInterval !== iInterval) {
				this._iInterval = iInterval;
				this._trigger();
			}
		};

		/**
		 * Adds a listener to the list that should be triggered.
		 *
		 * @public
		 * @param {function}
		 *            fnFunction is the called function that should be called when
		 *            the trigger want to trigger the listener.
		 * @param {object}
		 *            [oListener] that should be triggered.
		 */
		IntervalTrigger.prototype.addListener = function(fnFunction, oListener) {
			this._oEventBus.subscribe(_EVENT_ID, fnFunction, oListener);

			this._trigger();
		};

		/**
		 * Removes corresponding listener from list.
		 *
		 * @public
		 * @param {function}
		 *            fnFunction is the previously registered function
		 * @param {object}
		 *            [oListener] that should be removed
		 */
		IntervalTrigger.prototype.removeListener = function(fnFunction, oListener) {
			this._oEventBus.unsubscribe(_EVENT_ID, fnFunction, oListener);
		};

		/*
		 * @see sap.ui.base.Object#getInterface
		 */
		IntervalTrigger.prototype.getInterface = function() {
			return this;
		};

	/**
	 * Central instance of the IntervalTrigger (Singleton)
	 *
	 * @example
Create instance

	 *
	 * sap.ui.require(["sap/ui/core/IntervalTrigger"], function(IntervalTrigger) {
	 *     var fnDoIt = function(){
	 *         // my code
	 *     }
	 *     IntervalTrigger.addListener(fnDoIt, this);
	 *     IntervalTrigger.removeListener(fnDoIt, this);
	 * });
	 *
	 * Note: Only addListener and removeListener functions are exposed such that the
	 * singleton can neither be destroyed nor the interval can be modified.
	 *
	 * @return {sap.ui.core.IntervalTrigger} the instance with 200ms interval
	 */
	var getInstance = function() {

		var oIntervalTrigger = new IntervalTrigger(200);
		getInstance = function() {
			return oIntervalTrigger;
		};
		return oIntervalTrigger;
	};

	/**
	 * Adds a listener to the list that should be triggered.
	 *
	 * @public
	 * @since 1.61
	 * @param {function} fnFunction is the called function that should be called when
	 *            the trigger want to trigger the listener.
	 * @param {object} [oListener] that should be triggered.
	 */
	IntervalTrigger.addListener = function(fnFunction, oListener) {
		getInstance().addListener(fnFunction, oListener);
	};

	/**
	 * Removes corresponding listener from list.
	 *
	 * @public
	 * @since 1.61
	 * @param {function} fnFunction is the previously registered function
	 * @param {object} [oListener] that should be removed
	 */
	IntervalTrigger.removeListener = function(fnFunction, oListener) {
		getInstance().removeListener(fnFunction, oListener);
	};

	return IntervalTrigger;

});<|endoftext|>