<commit_before>var Bind = require("github/jillix/bind");
var Events = require("github/jillix/events");

module.exports = function(config) {

    var DmsTree = this;
    Events.call(DmsTree, config);

    var storage = {};
    var currentTemplate;

    var ctrlDown = false;

    $(document).on("keydown", function (e) {
        if (e.keyCode === 17) {
            ctrlDown = true;
            console.log("> true");
        }
    }).on("keyup", function (e) {
        if (e.keyCode === 17) {
            ctrlDown = false;
            console.log("> false");
        }
    });

    ///////////////////
    // HANDLERS
    ///////////////////
    $(DmsTree.dom).on("click", ".list", function () {
        var $item = $(this).closest("li");

        DmsTree.removeActive("*");
        DmsTree.setActive($item);

        var filters = (storage[$item.attr("data-id")] || {}).filters || [];

        DmsTree.emit("setFilters", filters, true);

        return false;
    }).on("click", ".folder", function () {

        var $item = $(this);
        $item = $item.closest("li");

        if (DmsTree.isLoading($item)) { return; }

        var dataItem = storage[$item.attr("data-id")];

        if (DmsTree.folderIsOpened($item)) {
            DmsTree.closeFolder($item);
            DmsTree.collapse($item);
            return;
        }

        DmsTree.startLoading($item);

        var crudObj = {
            t: "_list",
            q: {
                "_ln._id": dataItem._id
            }
        }

        DmsTree.emit("find", crudObj, function (err, docs) {

            if (err) {
                alert(err);
                return;
            }

            // TODO Just simulating a timeout
            setTimeout(function () {

            DmsTree.expand($item, docs);

            DmsTree.removeActive(".dms-tree *");
            DmsTree.setActive($item);

            DmsTree.stopLoading($item);
            DmsTree.openFolder($item);
            }, 100);
        });
        return false;
    }).on("click", ".all", function () {

        DmsTree.removeActive(".dms-tree *");
        DmsTree.setActive($(this));

        DmsTree.emit("setFilters", [], true);
        return false;
    });

    ///////////////////////////////
    // Generate the tree from items
    ///////////////////////////////
    DmsTree.buildFrom = function (items) {

        var $tree = $(".dms-tree", DmsTree.dom);
        var $typeTemplates = $(".type-templates", DmsTree.dom);

        switch (Object.prototype.toString.call(items)) {
            // object
            case "[object Object]":

                currentTemplate = items;

                var crudObj = {
                    t: "_list",
                    q: {
                        "_ln._tp": {
                            $ne: "_list"
                        },
                        "_ln": {
                            $elemMatch: {
                                _id: currentTemplate._id,
                                _tp: "_template"
                            }
                        }
                    }
                };

                // -> emit -> bind-crud -> callback -> buildFrom Array
                DmsTree.emit("find", crudObj, function (err, docs) {
                    if (err) {
                        alert(err);
                        return;
                    }

                    DmsTree.buildFrom(docs);
                });

                crudObj = {
                    t: "_list",
                    q: {
                        _ln: {
                            $elemMatch: {
                                _id: currentTemplate._id
                            }
                        },
                        type: {
                            $ne: "folder"
                        }
                    },
                    f: {
                        $none: 1,
                        _id: 0
                    }
                };

                DmsTree.emit("find", crudObj, function (err, docs) {
                    if (err) {
                        alert(err);
                        return;
                    }

                    var $all = $(".all-template", $typeTemplates)
                        .clone()
                        .removeClass("all-template");

                    $(".all-value", $all).text(docs.length);
                    $tree.prepend($all);
                });
                return;
            // array
            case "[object Array]":
                break;
            // other type
            default:
                return;
        }

        $tree.empty();
        storage = {};

        // an empty array
        if (!items || !items.length) { return; }

        var $itemsToAppend = $("<div>");

        for (var i in items) {
            var item = items[i];
            var $newItem = $("." + item.type + "-template", $typeTemplates).clone();

            storage[item._id] = item;

            $newItem
                .attr("data-id", item._id)
                .removeClass(item.type + "-template")
                .find(".name").text(item.name);

            $itemsToAppend.append($newItem);
        }

        $itemsToAppend.find("li").draggable({
            revert: true
        });

        $itemsToAppend.find(".folder").closest("li").droppable({
            over: DmsTree.dragAndDrop.over,
            out: DmsTree.dragAndDrop.out,
            drop: DmsTree.dragAndDrop.drop
        });

        $tree.append($itemsToAppend);
        $tree.find("li").hide().slideDown();
    };

    ///////////////////////////////
    // Set active class
    ///////////////////////////////
    DmsTree.setActive = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);

        if (ctrlDown && jQueryElement.hasClass("active")) {
            jQueryElement.toggleClass("active");
        }
        else {
            jQueryElement.addClass("active");
        }

        DmsTree.emit("selectionChanged", DmsTree.getActive("item"));
    };

    DmsTree.removeActive = function (jQueryElement) {

        if (ctrlDown) { return; }

        jQueryElement = $(jQueryElement, DmsTree.dom);
        jQueryElement.removeClass("active");

        DmsTree.emit("selectionChanged", DmsTree.getActive("item"));
    };

    //////////////////////////////
    // Get active (item/element)
    //////////////////////////////
    DmsTree.getActive = function (item) {

        var jQueryElements = $(DmsTree.dom).find(".active");
        if (!jQueryElements.length) { return undefined; }

        if (item === "item") {
            var activeItems = [];

            if (jQueryElements.length === 1) {
                activeItems.push(storage[jQueryElements.attr("data-id")]);
                return activeItems
            }

            jQueryElements.each(function () {
                activeItems.push(storage[$(this).attr("data-id")]);
            })

            return activeItems;
        }

        return jQueryElements;
    };

    ///////////////////////////////
    // Open-Close functions
    ///////////////////////////////
    DmsTree.openFolder = function (jQueryElement) {

        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return; }

        var $openClose = jQueryElement.find(".open-close");

        $openClose.children().first().addClass("hide");
        $openClose.children().last().removeClass("hide");
        jQueryElement.find(".chevron").toggleClass("icon-chevron-right icon-chevron-down");
    };

    DmsTree.closeFolder = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return; }

        var $openClose = jQueryElement.find(".open-close");

        $openClose.children().last().addClass("hide");
        $openClose.children().first().removeClass("hide");
        jQueryElement.find(".chevron").toggleClass("icon-chevron-right icon-chevron-down");
    };

    DmsTree.folderIsOpened = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $openClose = jQueryElement.find(".open-close");

        if ($openClose.children().last().hasClass("hide")) { return false; }
        return true;
    };

    ///////////////////////////////
    // Loading functions
    ///////////////////////////////
    DmsTree.startLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $loading = jQueryElement.find(".loading-toggle");

        $loading.children().first().removeClass("hide");
        $loading.children().last().addClass("hide");
        jQueryElement.attr("data-loading", "true");
    };

    DmsTree.stopLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $loading = jQueryElement.find(".loading-toggle");

        $loading.children().first().addClass("hide");
        var $last = $loading.children().last();
        $last.removeClass("hide");
        jQueryElement.attr("data-loading", "");
    };

    DmsTree.isLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return true; }
        return false;
    };

    ////////////////////
    // EXPAND / COLLAPSE
    ////////////////////
    DmsTree.expand = function (jQueryElement, docs) {

        jQueryElement = $(jQueryElement, DmsTree.dom);

        if (jQueryElement.next().prop("tagName") === "UL") { return; }

        var $ul = $("<ul>");
        for (var i in docs) {
            var doc = docs[i];
            storage[doc._id] = doc;

            var templClass = doc.type + "-template";
            var $newItem = $("." + templClass)
                            .clone()
                            .removeClass(templClass);

            $newItem.attr("data-id", doc._id)
                    .find(".name").text(doc.name);

            $ul.append($newItem);
        }

        $ul.find("li").draggable({
            revert: true
        });

        $(".folder", $ul).closest("li").droppable({
            over: DmsTree.dragAndDrop.over,
            out: DmsTree.dragAndDrop.out,
            drop: DmsTree.dragAndDrop.drop
        });

        jQueryElement.after($ul);
        $ul.hide().slideDown();
    };

    DmsTree.collapse = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var folderContent = jQueryElement.next();
        folderContent.slideUp(function () {
            folderContent.remove();
        });
    };

    //////////////////////
    // NEW LIST/NEW FOLDER
    //////////////////////
    DmsTree.newList = function (listObj, callback) {

        if (!currentTemplate) { return alert("Select a template, first."); }

        DmsTree.emit("getFilters", function (filters) {

            // TODO This will be removed when getFilters will not send dom references
            for (var i in filters) {
                delete filters[i].item;
                delete filters[i].hash;
            }

            listObj.filters = filters;
            listObj._ln = [
                {
                    _tp: "_template",
                    _id: currentTemplate._id
                }
            ];

            // TODO Parent???

            var crudObj = {
                t: "_list",
                d: listObj
            };

            DmsTree.emit("insert", crudObj, function (err, insertedDoc) {

                closeModals();

                if (err) {
                    alert(err);
                    return;
                }

                if (callback) { callback(err, insertedDoc); }
                DmsTree.emit("refresh");
            });
        });
    };

    //////////////////////
    // EDIT LIST
    //////////////////////
    DmsTree.editList = function (listObj, callback) {

        var activeItem = DmsTree.getActive("item")[0];

        for (var key in listObj) {
            activeItem[key] = listObj[key];
        }

        var newItem = JSON.parse(JSON.stringify(activeItem));
        delete newItem._id;

        DmsTree.emit("getFilters", function (filters) {

            // TODO This will be removed when getFilters will not send dom references
            for (var i in filters) {
                delete filters[i].item;
                delete filters[i].hash;
            }

            newItem.filters = filters;

            var crudObj = {
                t: "_list",
                q: {
                    _id: activeItem._id
                },
                d: newItem
            };

            DmsTree.emit("update", crudObj, function (err) {

                closeModals();
                if (err) { return alert(err); }

                DmsTree.emit("refresh");
            });
        });
    };

    //////////////////////
    // Delete LIST
    //////////////////////
    DmsTree.deleteList = function () {

        var activeItems = DmsTree.getActive("item");
        if (!activeItems || !activeItems.length) { return alert("No list selected."); }

        // var _ids = [];

        // for (var i in activeItems) {
        //     _ids.push(activeItems[i]._id);
        // }

        // TODO Until bind-crud #5 is fixed :: https://github.com/jillix/bind-crud/issues/5
        // var crudObj = {
        //     t: "_list",
        //     q: { _id: {
        //             $in: _ids
        //         }
        //     }
        // };

        var counter = 0;
        for (var i in activeItems) {

            var crudObj = {
                t: "_list",
                q: {
                    _id: activeItems[i]._id
                }
            }

            DmsTree.emit("remove", crudObj, function (err) {

                closeModals();

                if (err) { return alert(err); }
                if (++counter === activeItems.length) {
                    DmsTree.getActive().slideUp(function () {
                        $(this).remove();
                    });
                }
            });
        }

        // DmsTree.emit("remove", crudObj, function (err) {
        //     if (err) { return alert(err); }
        //     DmsTree.emit("buildFrom", currentTemplate);
        // });
    };

    ////////////////////////////
    // Drag and drop
    ///////////////////////////
    DmsTree.dragAndDrop = {
        over: function () {
            $(this).addClass("over");
        },
        out: function () {
            $(this).removeClass("over");
        },
        drop: function () {
            $(this).removeClass("over");
        }
    };

    function closeModals() {
        try {
            $(".modal").modal("hide");
        } catch (e) {}
    }

    DmsTree.emit("ready", config);
    DmsTree.on("refresh", function () {
        DmsTree.buildFrom(currentTemplate);
    });
};
<commit_msg>Added DRAGGABLE constant<commit_after>var Bind = require("github/jillix/bind");
var Events = require("github/jillix/events");

module.exports = function(config) {

    var DmsTree = this;
    Events.call(DmsTree, config);

    var DRAGGABLE = {
        revert: true,
        zIndex: 2500,
        start: function () {
            $(this).effect("highlight", {}, 1000);
            $(this).css("cursor", "move");
        },
        stop: function() {
            $(this).css("cursor", "default");
            $(".stack").css('z-index', '500');
        }
    };

    var storage = {};
    var currentTemplate;

    var ctrlDown = false;

    $(document).on("keydown", function (e) {
        if (e.keyCode === 17) {
            ctrlDown = true;
            console.log("> true");
        }
    }).on("keyup", function (e) {
        if (e.keyCode === 17) {
            ctrlDown = false;
            console.log("> false");
        }
    });

    ///////////////////
    // HANDLERS
    ///////////////////
    $(DmsTree.dom).on("click", ".list", function () {
        var $item = $(this).closest("li");

        DmsTree.removeActive("*");
        DmsTree.setActive($item);

        var filters = (storage[$item.attr("data-id")] || {}).filters || [];

        DmsTree.emit("setFilters", filters, true);

        return false;
    }).on("click", ".folder", function () {

        var $item = $(this);
        $item = $item.closest("li");

        if (DmsTree.isLoading($item)) { return; }

        var dataItem = storage[$item.attr("data-id")];

        if (DmsTree.folderIsOpened($item)) {
            DmsTree.closeFolder($item);
            DmsTree.collapse($item);
            return;
        }

        DmsTree.startLoading($item);

        var crudObj = {
            t: "_list",
            q: {
                "_ln._id": dataItem._id
            }
        }

        DmsTree.emit("find", crudObj, function (err, docs) {

            if (err) {
                alert(err);
                return;
            }

            // TODO Just simulating a timeout
            setTimeout(function () {

            DmsTree.expand($item, docs);

            DmsTree.removeActive(".dms-tree *");
            DmsTree.setActive($item);

            DmsTree.stopLoading($item);
            DmsTree.openFolder($item);
            }, 100);
        });
        return false;
    }).on("click", ".all", function () {

        DmsTree.removeActive(".dms-tree *");
        DmsTree.setActive($(this));

        DmsTree.emit("setFilters", [], true);
        return false;
    });

    ///////////////////////////////
    // Generate the tree from items
    ///////////////////////////////
    DmsTree.buildFrom = function (items) {

        var $tree = $(".dms-tree", DmsTree.dom);
        var $typeTemplates = $(".type-templates", DmsTree.dom);

        switch (Object.prototype.toString.call(items)) {
            // object
            case "[object Object]":

                debugger;
                currentTemplate = items;

                var crudObj = {
                    t: "_list",
                    q: {
                        "_ln._tp": {
                            $ne: "_list"
                        },
                        "_ln": {
                            $elemMatch: {
                                id: currentTemplate.id,
                                _tp: "_template"
                            }
                        }
                    }
                };

                // -> emit -> bind-crud -> callback -> buildFrom Array
                DmsTree.emit("find", crudObj, function (err, docs) {
                    if (err) {
                        alert(err);
                        return;
                    }

                    DmsTree.buildFrom(docs);
                });

                crudObj = {
                    t: "_list",
                    q: {
                        _ln: {
                            $elemMatch: {
                                id: currentTemplate.id
                            }
                        },
                        type: {
                            $ne: "folder"
                        }
                    },
                    f: {
                        $none: 1,
                        _id: 0
                    }
                };

                DmsTree.emit("find", crudObj, function (err, docs) {
                    if (err) {
                        alert(err);
                        return;
                    }

                    var $all = $(".all-template", $typeTemplates)
                        .clone()
                        .removeClass("all-template");

                    $(".all-value", $all).text(docs.length);
                    $tree.prepend($all);
                });
                return;
            // array
            case "[object Array]":
                break;
            // other type
            default:
                return;
        }

        $tree.empty();
        storage = {};

        // an empty array
        if (!items || !items.length) { return; }

        var $itemsToAppend = $("<div>");

        for (var i in items) {
            var item = items[i];
            var $newItem = $("." + item.type + "-template", $typeTemplates).clone();

            storage[item._id] = item;

            $newItem
                .attr("data-id", item._id)
                .removeClass(item.type + "-template")
                .find(".name").text(item.name);

            $itemsToAppend.append($newItem);
        }

        $itemsToAppend.find("li").draggable(DRAGGABLE);

        $itemsToAppend.find(".folder").closest("li").droppable({
            over: DmsTree.dragAndDrop.over,
            out: DmsTree.dragAndDrop.out,
            drop: DmsTree.dragAndDrop.drop
        });

        $tree.append($itemsToAppend);
        $tree.find("li").hide().slideDown();
    };

    ///////////////////////////////
    // Set active class
    ///////////////////////////////
    DmsTree.setActive = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);

        if (ctrlDown && jQueryElement.hasClass("active")) {
            jQueryElement.toggleClass("active");
        }
        else {
            jQueryElement.addClass("active");
        }

        DmsTree.emit("selectionChanged", DmsTree.getActive("item"));
    };

    DmsTree.removeActive = function (jQueryElement) {

        if (ctrlDown) { return; }

        jQueryElement = $(jQueryElement, DmsTree.dom);
        jQueryElement.removeClass("active");

        DmsTree.emit("selectionChanged", DmsTree.getActive("item"));
    };

    //////////////////////////////
    // Get active (item/element)
    //////////////////////////////
    DmsTree.getActive = function (item) {

        var jQueryElements = $(DmsTree.dom).find(".active");
        if (!jQueryElements.length) { return undefined; }

        if (item === "item") {
            var activeItems = [];

            if (jQueryElements.length === 1) {
                activeItems.push(storage[jQueryElements.attr("data-id")]);
                return activeItems
            }

            jQueryElements.each(function () {
                activeItems.push(storage[$(this).attr("data-id")]);
            })

            return activeItems;
        }

        return jQueryElements;
    };

    ///////////////////////////////
    // Open-Close functions
    ///////////////////////////////
    DmsTree.openFolder = function (jQueryElement) {

        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return; }

        var $openClose = jQueryElement.find(".open-close");

        $openClose.children().first().addClass("hide");
        $openClose.children().last().removeClass("hide");
        jQueryElement.find(".chevron").toggleClass("icon-chevron-right icon-chevron-down");
    };

    DmsTree.closeFolder = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return; }

        var $openClose = jQueryElement.find(".open-close");

        $openClose.children().last().addClass("hide");
        $openClose.children().first().removeClass("hide");
        jQueryElement.find(".chevron").toggleClass("icon-chevron-right icon-chevron-down");
    };

    DmsTree.folderIsOpened = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $openClose = jQueryElement.find(".open-close");

        if ($openClose.children().last().hasClass("hide")) { return false; }
        return true;
    };

    ///////////////////////////////
    // Loading functions
    ///////////////////////////////
    DmsTree.startLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $loading = jQueryElement.find(".loading-toggle");

        $loading.children().first().removeClass("hide");
        $loading.children().last().addClass("hide");
        jQueryElement.attr("data-loading", "true");
    };

    DmsTree.stopLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var $loading = jQueryElement.find(".loading-toggle");

        $loading.children().first().addClass("hide");
        var $last = $loading.children().last();
        $last.removeClass("hide");
        jQueryElement.attr("data-loading", "");
    };

    DmsTree.isLoading = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        if (jQueryElement.attr("data-loading")) { return true; }
        return false;
    };

    ////////////////////
    // EXPAND / COLLAPSE
    ////////////////////
    DmsTree.expand = function (jQueryElement, docs) {

        jQueryElement = $(jQueryElement, DmsTree.dom);

        if (jQueryElement.next().prop("tagName") === "UL") { return; }

        var $ul = $("<ul>");
        for (var i in docs) {
            var doc = docs[i];
            storage[doc._id] = doc;

            var templClass = doc.type + "-template";
            var $newItem = $("." + templClass)
                            .clone()
                            .removeClass(templClass);

            $newItem.attr("data-id", doc._id)
                    .find(".name").text(doc.name);

            $ul.append($newItem);
        }

        $ul.find("li").draggable(DRAGGABLE);

        $(".folder", $ul).closest("li").droppable({
            over: DmsTree.dragAndDrop.over,
            out: DmsTree.dragAndDrop.out,
            drop: DmsTree.dragAndDrop.drop
        });

        jQueryElement.after($ul);
        $ul.hide().slideDown();
    };

    DmsTree.collapse = function (jQueryElement) {
        jQueryElement = $(jQueryElement, DmsTree.dom);
        var folderContent = jQueryElement.next();
        folderContent.slideUp(function () {
            folderContent.remove();
        });
    };

    //////////////////////
    // NEW LIST/NEW FOLDER
    //////////////////////
    DmsTree.newList = function (listObj, callback) {

        if (!currentTemplate) { return alert("Select a template, first."); }

        DmsTree.emit("getFilters", function (filters) {

            // TODO This will be removed when getFilters will not send dom references
            for (var i in filters) {
                delete filters[i].item;
                delete filters[i].hash;
            }

            listObj.filters = filters;
            listObj._ln = [
                {
                    _tp: "_template",
                    _id: currentTemplate._id
                }
            ];

            // TODO Parent???

            var crudObj = {
                t: "_list",
                d: listObj
            };

            DmsTree.emit("insert", crudObj, function (err, insertedDoc) {

                closeModals();

                if (err) {
                    alert(err);
                    return;
                }

                if (callback) { callback(err, insertedDoc); }
                DmsTree.emit("refresh");
            });
        });
    };

    //////////////////////
    // EDIT LIST
    //////////////////////
    DmsTree.editList = function (listObj, callback) {

        var activeItem = DmsTree.getActive("item")[0];

        for (var key in listObj) {
            activeItem[key] = listObj[key];
        }

        var newItem = JSON.parse(JSON.stringify(activeItem));
        delete newItem._id;

        DmsTree.emit("getFilters", function (filters) {

            // TODO This will be removed when getFilters will not send dom references
            for (var i in filters) {
                delete filters[i].item;
                delete filters[i].hash;
            }

            newItem.filters = filters;

            var crudObj = {
                t: "_list",
                q: {
                    _id: activeItem._id
                },
                d: newItem
            };

            DmsTree.emit("update", crudObj, function (err) {

                closeModals();
                if (err) { return alert(err); }

                DmsTree.emit("refresh");
            });
        });
    };

    //////////////////////
    // Delete LIST
    //////////////////////
    DmsTree.deleteList = function () {

        var activeItems = DmsTree.getActive("item");
        if (!activeItems || !activeItems.length) { return alert("No list selected."); }

        // var _ids = [];

        // for (var i in activeItems) {
        //     _ids.push(activeItems[i]._id);
        // }

        // TODO Until bind-crud #5 is fixed :: https://github.com/jillix/bind-crud/issues/5
        // var crudObj = {
        //     t: "_list",
        //     q: { _id: {
        //             $in: _ids
        //         }
        //     }
        // };

        var counter = 0;
        for (var i in activeItems) {

            var crudObj = {
                t: "_list",
                q: {
                    _id: activeItems[i]._id
                }
            }

            DmsTree.emit("remove", crudObj, function (err) {

                closeModals();

                if (err) { return alert(err); }
                if (++counter === activeItems.length) {
                    DmsTree.getActive().slideUp(function () {
                        $(this).remove();
                    });
                }
            });
        }

        // DmsTree.emit("remove", crudObj, function (err) {
        //     if (err) { return alert(err); }
        //     DmsTree.emit("buildFrom", currentTemplate);
        // });
    };

    ////////////////////////////
    // Drag and drop
    ///////////////////////////
    DmsTree.dragAndDrop = {
        over: function () {
            $(this).addClass("over");
        },
        out: function () {
            $(this).removeClass("over");
        },
        drop: function () {
            $(this).removeClass("over");
        }
    };

    function closeModals() {
        try {
            $(".modal").modal("hide");
        } catch (e) {}
    }

    DmsTree.emit("ready", config);
    DmsTree.on("refresh", function () {
        DmsTree.buildFrom(currentTemplate);
    });
};
<|endoftext|>


<commit_before>const parse = require('./parse.js')
const error = require('./error.js')
const help = require('./help.js')
const helpOption = {
  name: 'help',
  alias: 'h',
  description: 'get help'
}
const defaultRootCommand = {
  command: [],
  description: '',
  parameters: [],
  options: [
    helpOption
  ]
}
const commandMatches = (a, b) => a.reduce((acc, val, index) => (b[index] != null && val === b[index] ? acc + 1 : acc), 0) === a.length

module.exports = (name) => {
  const commands = []

  return {
    command(command, define) {
      if (define == null) {
        define = command

        command = []
      }

      const options = []
      const parameters = []
      let description = ''

      const action = define({
        parameter(parameter) {
          parameters.push(parameter)
        },
        option(option) {
          options.push(option)
        },
        description(desc) {
          description = desc
        }
      })

      options.push(helpOption)

      commands.unshift({
        command,
        description,
        parameters,
        options,
        action
      })
    },
    async start(argv) {
      let command = commands.reduce((acc, command) => {
        if (acc != null) return acc

        if (commandMatches(command.command, argv)) {
          return command
        }

        return acc
      }, null)

      if (command == null) {
        command = defaultRootCommand
      }

      const subCommands = commands.filter((sub) => {
        if (sub !== command && commandMatches(command.command, sub.command)) {
          return true
        }

        return false
      }, []).reverse()

      try {
        const args = parse(argv.slice(command.command.length), {options: command.options, parameters: command.parameters})

        if (args.help === true || command.action == null) {
          help(name, command.command, command.description, {commands: subCommands, options: command.options, parameters: command.parameters})
        } else if (command.action != null) {
          await command.action(args)
        }
      } catch (e) {
        error(e)
      }
    }
  }
}
<commit_msg>Fix when parse fails<commit_after>const parse = require('./parse.js')
const error = require('./error.js')
const help = require('./help.js')
const helpOption = {
  name: 'help',
  alias: 'h',
  description: 'get help'
}
const defaultRootCommand = {
  command: [],
  description: '',
  parameters: [],
  options: [
    helpOption
  ]
}
const commandMatches = (a, b) => a.reduce((acc, val, index) => (b[index] != null && val === b[index] ? acc + 1 : acc), 0) === a.length

module.exports = (name) => {
  const commands = []

  return {
    command(command, define) {
      if (define == null) {
        define = command

        command = []
      }

      const options = []
      const parameters = []
      let description = ''

      const action = define({
        parameter(parameter) {
          parameters.push(parameter)
        },
        option(option) {
          options.push(option)
        },
        description(desc) {
          description = desc
        }
      })

      options.push(helpOption)

      commands.unshift({
        command,
        description,
        parameters,
        options,
        action
      })
    },
    async start(argv) {
      let command = commands.reduce((acc, command) => {
        if (acc != null) return acc

        if (commandMatches(command.command, argv)) {
          return command
        }

        return acc
      }, null)

      if (command == null) {
        command = defaultRootCommand
      }

      const subCommands = commands.filter((sub) => {
        if (sub !== command && commandMatches(command.command, sub.command)) {
          return true
        }

        return false
      }, []).reverse()

      try {
        const args = parse(argv.slice(command.command.length), {options: command.options, parameters: command.parameters})

        if (args == null || args.help === true || command.action == null) {
          help(name, command.command, command.description, {commands: subCommands, options: command.options, parameters: command.parameters})
        } else if (command.action != null) {
          await command.action(args)
        }
      } catch (e) {
        error(e)
      }
    }
  }
}
<|endoftext|>


<commit_before>"use strict";

var renderLoop;
(function($){
	$(document).ready(function (){
		console.log("main.js");
		setup();
		renderLoop = setInterval(update, 30);
		$(document).keydown(handleInput);
		$(document).keyup(handleInput);
	});
})(jQuery);

var SCALE = 1.0;

window["red"] = {"color":"red"};
window["blue"] = {"color":"blue"};
var teams = [window["red"], window["blue"]];

var field;
var fieldWidth = 800;
var fieldHeight = 600;

var missileTimeout = 2250;
var fireRateLimit = 100;
var gravityStrength = 10000;

Math.radians = function(degrees) {
	return degrees * Math.PI / 180;
};
Math.degrees = function(radians) {
	return radians * 180 / Math.PI;
};

function setup() {
	var svg = d3.select('#playfield').append("svg")
		.attr("width",fieldWidth)
		.attr("height",fieldHeight)
		.attr("id","field");
	field = d3.select('#field');
	svg.append("rect")
		.attr("width",fieldWidth)
		.attr("height",fieldHeight)
		.attr("fill","black");

	svg.append("circle") //sun
		.attr("cx",fieldWidth/2)
		.attr("cy",fieldHeight/2)
		.attr("r", 5*SCALE)
		.style("fill","white")
		.attr("id","sun");

	d3.select('svg').selectAll(".ship").data(teams).enter().append("polygon")
		.attr("points",-8*SCALE+","+16*SCALE+" 0,"+-8*SCALE+" "+8*SCALE+","+16*SCALE)
		.attr("id", function(d){console.log(d.color); return d.color;})
		.attr("fill", function(d){return d.color;})
		.attr("class", "ship");

	red.x = 50;
	red.y = Math.floor((fieldHeight-100)*Math.random())+50;
	red.rot = 90;
	red.xv = 0.0;
	red.yv = 0.0;
	red.fireTime = new Date() - 1000;
	red.missileReady = true;

	blue.x = fieldWidth-50;
	blue.y = Math.floor((fieldHeight-100)*Math.random())+50;
	blue.rot = -90;
	blue.xv = 0.0;
	blue.yv = 0.0;
	blue.fireTime = new Date() - 1000;
	blue.missileReady = true;

	updateGraphics();
}

function updatePositions(){
	var sun = d3.select('#sun');

	teams.forEach(function(teamObj){
		var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv;
		if (speed > 225) {
			teamObj.xv = 15.*teamObj.xv/Math.sqrt(speed);
			teamObj.yv = 15.*teamObj.yv/Math.sqrt(speed);
		} else if (speed < 0.00) {
			teamObj.xv = 0;
			teamObj.yv = 0;
		}

		var dx = teamObj.x - sun.attr('cx');
		var dy = teamObj.y - sun.attr('cy');
		var dis = Math.sqrt(dx*dx+dy*dy);
		if (dx*dx+dy*dy > 10){
			var force = gravityStrength / (dx*dx+dy*dy);
		} else {
			var force = gravityStrength;
		}
		teamObj.xv += -force*dx/dis;
		teamObj.yv += -force*dy/dis;

		teamObj.x += teamObj.xv;
		teamObj.x = (teamObj.x+fieldWidth)%fieldWidth;
		teamObj.y += teamObj.yv;
		teamObj.y = (teamObj.y+fieldHeight)%fieldHeight;
	});

	missiles.forEach(function(m){
		var dx = m.x - sun.attr('cx');
		var dy = m.y - sun.attr('cy');
		var dis = Math.sqrt(dx*dx+dy*dy);
		if (dx*dx+dy*dy > 10){
			var force = gravityStrength / (dx*dx+dy*dy);
		} else {
			var force = gravityStrength;
		}
		m.xv += -force*dx/dis;
		m.yv += -force*dy/dis;
	});
}

function updateGraphics(team){
	teams.forEach(function(teamObj){
		// console.log(teamObj);
		d3.select("#"+teamObj.color).attr("transform","translate("+teamObj.x+","+teamObj.y+"),rotate("+teamObj.rot+")");
	});
}

function update() {
	checkKeys();

	if (missiles.length){
		var filteredMissiles = [];
		for (var i=0; i<missiles.length; i++) {
			var m = missiles[i];
			if (new Date() - m.time < missileTimeout){
				m.x += m.xv;
				m.x = (m.x+fieldWidth)%fieldWidth;
				m.y += m.yv;
				m.y = (m.y+fieldHeight)%fieldHeight;
				filteredMissiles.push(m);
			}
		}
		missiles = filteredMissiles;

		var dots = d3.select("#field").selectAll('.missile').data(missiles);
		dots.attr("cx", function(d){ return d.x; })
			.attr("cy", function(d){ return d.y; });
		dots.exit().remove();
	}

	updatePositions();
	updateGraphics();
}

function teamMove(team,action) {
	var teamObj = window[team];
	switch (action){
		case "thrust":
			teamObj.xv += 0.5*Math.cos(Math.radians(teamObj.rot-90));
			teamObj.yv += 0.5*Math.sin(Math.radians(teamObj.rot-90));
			break;
		case "fire":
			fireMissile(team);
			break;
		case "turn right":
			teamObj.rot = teamObj.rot + 5;
			break;
		case "turn left":
			teamObj.rot = teamObj.rot - 5;
			break;
		case "hyperspace":
			break;
	}
}

var missiles = [];
/* class Missile {
	constructor(x,y,xv,yv) {
		this.x = x;
		this.y = y;
		this.xv = xv;
		this.yv = yv;
		if (missiles.length > 0){
			this.id = missiles[missiles.length-1].id + 1;
		} else {
			this.id = 1;
		}
		this.name = "missile"+this.id;
	}
} */

function fireMissile(team) {
	var mx,my,mxv,myv;
	var p = window[team];
	mx = p.x;
	my = p.y;
	mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90));
	myv = p.yv + 10*Math.sin(Math.radians(p.rot-90));

	// missiles.push(new Missile(mx,my,mxv,myv));
	missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date()});
	missiles[missiles.length-1]['id'] = missiles.length;

	d3.select("#field").selectAll(".missile")
		.data(missiles)
	  .enter().append("circle")
		.attr("cx", function(d){ return d.x; })
		.attr("cy", function(d){ return d.y; })
		.attr("r", 1.5)
		.style("fill","white")
		.attr("class", "missile");
}

var keystates = {};
function handleInput(event) {
	if (event.which == 27){
		clearInterval(renderLoop);
		renderLoop = false;
		return;
	} else if (event.which == 13){
		event.preventDefault();
		if (!renderLoop){ renderLoop = setInterval(update, 30); }
		return;
	}

	if (event.which == 191){ event.preventDefault(); };

	if (event.type == 'keydown'){ keystates[event.which] = true;  }
	if (event.type == 'keyup')  {
		keystates[event.which] = false;

		if (event.which == 66) {
			window["red"].missileReady = true;
		} else if (event.which == 191) {
			window["blue"].missileReady = true;
		}
	}
}

var keysOfInterest = [
			90,88,67,86,66,
			78,77,188,190,191
		     ];
function checkKeys() {
	keysOfInterest.forEach(function(k){
		if (keystates[k]){
			switch (k){
				// RED
				case 90:
					teamMove("red","turn left");
					break;
				case 88:
					teamMove("red","turn right");
					break;
				case 67:
					teamMove("red","hyperspace");
					break;
				case 86:
					teamMove("red","thrust");
					break;
				case 66:
					if (new Date() - window["red"].fireTime > fireRateLimit && window["red"].missileReady) {
						teamMove("red","fire");
						window["red"].fireTime = new Date();
						window["red"].missileReady = false;
					}
					break;

				// BLUE
				case 78:
					teamMove("blue","turn left");
					break;
				case 77:
					teamMove("blue","turn right");
					break;
				case 188:
					teamMove("blue","hyperspace");
					break;
				case 190:
					teamMove("blue","thrust");
					break;
				case 191:
					if (new Date() - window["blue"].fireTime > fireRateLimit && window["blue"].missileReady) {
						teamMove("blue","fire");
						window["blue"].fireTime = new Date();
						window["blue"].missileReady = false;
					}
					break;
			}
		}
	});
}
<commit_msg>Gravity works fantastic.<commit_after>"use strict";

var renderLoop;
(function($){
	$(document).ready(function (){
		console.log("main.js");
		setup();
		renderLoop = setInterval(update, 30);
		$(document).keydown(handleInput);
		$(document).keyup(handleInput);
	});
})(jQuery);

var SCALE = 1.0;

window["red"] = {"color":"red"};
window["blue"] = {"color":"blue"};
var teams = [window["red"], window["blue"]];

var field;
var fieldWidth = 800;
var fieldHeight = 600;

var missileTimeout = 2250;
var fireRateLimit = 100;
var gravityStrength = 10000;
var speedLimit = 15; //user
var maxSpeed = 40; //gravity-boosted

Math.radians = function(degrees) {
	return degrees * Math.PI / 180;
};
Math.degrees = function(radians) {
	return radians * 180 / Math.PI;
};

function setup() {
	var svg = d3.select('#playfield').append("svg")
		.attr("width",fieldWidth)
		.attr("height",fieldHeight)
		.attr("id","field");
	field = d3.select('#field');
	svg.append("rect")
		.attr("width",fieldWidth)
		.attr("height",fieldHeight)
		.attr("fill","black");

	svg.append("circle") //sun
		.attr("cx",fieldWidth/2)
		.attr("cy",fieldHeight/2)
		.attr("r", 5*SCALE)
		.style("fill","white")
		.attr("id","sun");

	d3.select('svg').selectAll(".ship").data(teams).enter().append("polygon")
		.attr("points",-8*SCALE+","+16*SCALE+" 0,"+-8*SCALE+" "+8*SCALE+","+16*SCALE)
		.attr("id", function(d){console.log(d.color); return d.color;})
		.attr("fill", function(d){return d.color;})
		.attr("class", "ship");

	red.x = 50;
	red.y = Math.floor((fieldHeight-100)*Math.random())+50;
	red.rot = 90;
	red.xv = 0.0;
	red.yv = 0.0;
	red.fireTime = new Date() - 1000;
	red.missileReady = true;

	blue.x = fieldWidth-50;
	blue.y = Math.floor((fieldHeight-100)*Math.random())+50;
	blue.rot = -90;
	blue.xv = 0.0;
	blue.yv = 0.0;
	blue.fireTime = new Date() - 1000;
	blue.missileReady = true;

	updateGraphics();
}

function updatePositions(){
	var sun = d3.select('#sun');

	teams.forEach(function(teamObj){
		var dx = teamObj.x - sun.attr('cx');
		var dy = teamObj.y - sun.attr('cy');
		var dis = Math.sqrt(dx*dx+dy*dy);
		if (dx*dx+dy*dy > 10){
			var force = gravityStrength / (dx*dx+dy*dy);
		} else {
			var force = gravityStrength;
		}
		teamObj.xv += -force*dx/dis;
		teamObj.yv += -force*dy/dis;

		var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv;
		if (speed > maxSpeed*maxSpeed) {
			teamObj.xv = maxSpeed*teamObj.xv/Math.sqrt(speed);
			teamObj.yv = maxSpeed*teamObj.yv/Math.sqrt(speed);
		}

		teamObj.x += teamObj.xv;
		teamObj.x = (teamObj.x+fieldWidth)%fieldWidth;
		teamObj.y += teamObj.yv;
		teamObj.y = (teamObj.y+fieldHeight)%fieldHeight;
	});

	missiles.forEach(function(m){
		var dx = m.x - sun.attr('cx');
		var dy = m.y - sun.attr('cy');
		var dis = Math.sqrt(dx*dx+dy*dy);
		if (dx*dx+dy*dy > 100){
			var force = gravityStrength / (dx*dx+dy*dy);
		} else {
			var force = gravityStrength/100;
		}
		m.xv += -force*dx/dis;
		m.yv += -force*dy/dis;

		var speed = m.xv*m.xv + m.yv*m.yv;
		if (speed > maxSpeed*maxSpeed*2) {
			m.xv = 1.414*maxSpeed*m.xv/Math.sqrt(speed);
			m.yv = 1.414*maxSpeed*m.yv/Math.sqrt(speed);
		}
	});
}

function updateGraphics(team){
	teams.forEach(function(teamObj){
		d3.select("#"+teamObj.color).attr("transform","translate("+teamObj.x+","+teamObj.y+"),rotate("+teamObj.rot+")");
	});
}

function update() {
	checkKeys();

	if (missiles.length){
		var filteredMissiles = [];
		for (var i=0; i<missiles.length; i++) {
			var m = missiles[i];
			if (new Date() - m.time < missileTimeout){
				m.x += m.xv;
				m.x = (m.x+fieldWidth)%fieldWidth;
				m.y += m.yv;
				m.y = (m.y+fieldHeight)%fieldHeight;
				filteredMissiles.push(m);
			}
		}
		missiles = filteredMissiles;

		var dots = d3.select("#field").selectAll('.missile').data(missiles);
		dots.attr("cx", function(d){ return d.x; })
			.attr("cy", function(d){ return d.y; });
		dots.exit().remove();
	}

	updatePositions();
	updateGraphics();
}

function teamMove(team,action) {
	var teamObj = window[team];
	switch (action){
		case "thrust":
			fireEngine(team);
			break;
		case "fire":
			fireMissile(team);
			break;
		case "turn right":
			teamObj.rot = teamObj.rot + 5;
			break;
		case "turn left":
			teamObj.rot = teamObj.rot - 5;
			break;
		case "hyperspace":
			break;
	}
}

function fireEngine(team) {
	var teamObj = window[team];
	var speed = teamObj.xv*teamObj.xv + teamObj.yv*teamObj.yv;

	var nxv = teamObj.xv + 0.5*Math.cos(Math.radians(teamObj.rot-90));
	var nyv = teamObj.yv + 0.5*Math.sin(Math.radians(teamObj.rot-90));
	var speed2 = nxv*nxv + nyv*nyv;

	if (speed < speedLimit*speedLimit || speed2 < speed) { //either slow enough or slowing down
		teamObj.xv = nxv;
		teamObj.yv = nyv;

		if (speed2 > speed && speed2 > speedLimit*speedLimit) {
			teamObj.xv = speedLimit*teamObj.xv/Math.sqrt(speed2);
			teamObj.yv = speedLimit*teamObj.yv/Math.sqrt(speed2);
		}
	}
}

var missiles = [];
/* class Missile {
	constructor(x,y,xv,yv) {
		this.x = x;
		this.y = y;
		this.xv = xv;
		this.yv = yv;
		if (missiles.length > 0){
			this.id = missiles[missiles.length-1].id + 1;
		} else {
			this.id = 1;
		}
		this.name = "missile"+this.id;
	}
} */

function fireMissile(team) {
	var mx,my,mxv,myv;
	var p = window[team];
	mx = p.x;
	my = p.y;
	mxv = p.xv + 10*Math.cos(Math.radians(p.rot-90));
	myv = p.yv + 10*Math.sin(Math.radians(p.rot-90));

	// missiles.push(new Missile(mx,my,mxv,myv));
	missiles.push({'x':mx, 'y':my, 'xv':mxv, 'yv':myv, 'time':new Date()});
	missiles[missiles.length-1]['id'] = missiles.length;

	d3.select("#field").selectAll(".missile")
		.data(missiles)
	  .enter().append("circle")
		.attr("cx", function(d){ return d.x; })
		.attr("cy", function(d){ return d.y; })
		.attr("r", 1.5)
		.style("fill","white")
		.attr("class", "missile");
}

var keystates = {};
function handleInput(event) {
	if (event.which == 27){
		clearInterval(renderLoop);
		renderLoop = false;
		return;
	} else if (event.which == 13){
		event.preventDefault();
		if (!renderLoop){ renderLoop = setInterval(update, 30); }
		return;
	}

	if (event.which == 191){ event.preventDefault(); };

	if (event.type == 'keydown'){ keystates[event.which] = true;  }
	if (event.type == 'keyup')  {
		keystates[event.which] = false;

		if (event.which == 66) {
			window["red"].missileReady = true;
		} else if (event.which == 191) {
			window["blue"].missileReady = true;
		}
	}
}

var keysOfInterest = [
			90,88,67,86,66,
			78,77,188,190,191
		     ];
function checkKeys() {
	keysOfInterest.forEach(function(k){
		if (keystates[k]){
			switch (k){
				// RED
				case 90:
					teamMove("red","turn left");
					break;
				case 88:
					teamMove("red","turn right");
					break;
				case 67:
					teamMove("red","hyperspace");
					break;
				case 86:
					teamMove("red","thrust");
					break;
				case 66:
					if (new Date() - window["red"].fireTime > fireRateLimit && window["red"].missileReady) {
						teamMove("red","fire");
						window["red"].fireTime = new Date();
						window["red"].missileReady = false;
					}
					break;

				// BLUE
				case 78:
					teamMove("blue","turn left");
					break;
				case 77:
					teamMove("blue","turn right");
					break;
				case 188:
					teamMove("blue","hyperspace");
					break;
				case 190:
					teamMove("blue","thrust");
					break;
				case 191:
					if (new Date() - window["blue"].fireTime > fireRateLimit && window["blue"].missileReady) {
						teamMove("blue","fire");
						window["blue"].fireTime = new Date();
						window["blue"].missileReady = false;
					}
					break;
			}
		}
	});
}
<|endoftext|>


<commit_before>var fs = require('fs'),
	source_file = __dirname + "/themevariables.json",
	target_file = __dirname + "/variables.less",
	variables = "",
 	count = 0;
fs.readFile(source_file, 'utf8', function(err,data){
	data = JSON.parse(data);
	for(var key in data){
		if(data.hasOwnProperty(key)){
			variables += '@'+key+':'+data[key]+';';
			count += 1;
			if(count<=Object.keys(data).length-1){
				variables += '\n'
			}
		}
	}
	fs.writeFile(target_file, variables, function(err){
		if(err){
			console.log(err);
		}else {
			console.log("The file was saved");
		}
	})
});<commit_msg>test commit to check for audit<commit_after>var fs = require('fs'),
	source_file = __dirname + "/themevariables.json",
	target_file = __dirname + "/variables.less",
	variables = "",
 	count = 0;
fs.readFile(source_file, 'utf8', function(err,data){
	data = JSON.parse(data);
	for(var key in data){
		if(data.hasOwnProperty(key)){
			variables += '@'+key+':'+data[key]+';';
			count += 1;
			if(count<=Object.keys(data).length-1){
				variables += '\n'
			}
		}
	}
	fs.writeFile(target_file, variables, function(err){
		if(err){
			console.log(err);
		}else {
			console.log("The file was saved");
		}
	})
});

<|endoftext|>


<commit_before>import React from "react";

var Component = React.createClass({
    getInitialState: function() {
        return {
            state: "hidden",
            count: 0
        }
    },

    getDefaultProps: function() {
        return {
            cls: ""
        }
    },

    render: function() {
        var cls = "loader-60devs " + this.props.cls;

        return (

        );
    },

    show: function() {
        clearTimeout(this.state.hidingTimerId);

        this.setState({
            count: this.state.count + 1
        });

        if(this.state.count > 1)
            return ;

        this.setState({
            state: ""
        });

        var timerId = setTimeout(this.toRunningState, 1);

        this.setState({
            runningTimerId: timerId
        });
    },

    toRunningState: function() {
        this.setState({
            state: "running"
        });
    },

    hide: function() {
        clearTimeout(this.state.runningTimerId);

        if(-- this.state.count > 0)
            return ;

        this.setState({
            state: "finishing"
        });

        var timerId = setTimeout(this.toHiddenState, 500);

        this.setState({
            hidingTimerId: timerId
        });
    },

    toHiddenState: function() {
        this.setState({
            state: "hidden"
        });
    },

    componentWillMount: function() {
        $(window).on('loader.show', this.show)
        $(window).on('loader.hide', this.hide);
    },

    componentWillUnmount: function() {
        $(window).off('loader.show', this.show);
        $(window).off('loader.hide', this.hide);
    }
});

var instance = <Component />;

export default {
    instance: instance,
    show: function() {
        instance.show();
    },
    hide: function() {
        instance.hide();
    }
}<commit_msg>fixed bugs<commit_after>import React from "react";

var Component = React.createClass({
    getInitialState: function() {
        return {
            state: "hidden",
            count: 0
        }
    },

    getDefaultProps: function() {
        return {
            cls: ""
        }
    },

    render: function() {
        var cls = "loader-60devs " + this.props.cls;

        return (

        );
    },

    show: function() {
        console.log("show");
        this.setState({
            count: this.state.count + 1
        });

        if(this.state.count > 1)
            return ;

        console.log("show == 1");

        clearTimeout(this.state.hidingTimerId);

        this.refs.element.dataset.state = "hidden";
        this.refs.element.offsetTop;

        this.setState({
            state: "",
            runningTimerId: setTimeout(this.toRunningState, 10)
        });
    },

    hide: function() {
        this.setState({
            count: this.state.count - 1
        });

        if(this.state.state == "hidden")
            return ;

        if(this.state.count > 0)
            return ;

        clearTimeout(this.state.runningTimerId);
        this.setState({
            state: "finishing",
            hidingTimerId: setTimeout(this.toHiddenState, 500)
        });
    },

    toRunningState: function() {
        this.setState({
            state: "running"
        });
    },

    toHiddenState: function() {
        this.setState({
            state: "hidden"
        });
    },

    componentWillMount: function() {
        Component.instance = this;
    },

    componentWillUnmount: function() {
        delete Component.instance;
    }
});

export default {
    Component: Component,
    show: function() {
        Component.instance.show();
    },
    hide: function() {
        Component.instance.hide();
    }
}<|endoftext|>


<commit_before>require("dotenv").load()
var SlackClient = require("slack-client")
var shuffle = require("shuffle-array")

var token = process.env.SLACK_TOKEN // slackbot's integration token.
var autoReconnect = true // Automatically reconnect after an error response from Slack.
var autoMark = true // Automatically mark each message as read after it is processed.
var channels = {}

var slackbot = new SlackClient(token, autoReconnect, autoMark)

slackbot.on("open", slackopened)
slackbot.on("message", slackmessage)

function slackopened() {
	console.log("I'm alive!")
}

function isMessageForMe(message) {
  return (message.text && message.text.substr(0, 12) === `<@${slackbot.self.id}>`);
}

function startretro(channelID) {
	channels[channelID] = {
		plus: [],
		minus: [],
		question: [],
		idea: [],
		props: []
	}
	var channel = slackbot.getChannelGroupOrDMByID(channelID)
	console.log("Starting Retro")
	channel.send("<!here|here>: Starting Retro Recording. \n Please use `+` for positive, `-` for needs improvement, `?` for questions, `!` for ideas, and `*` to give props to someone!")
}

function stopretro(channelID) {
	if (channels[channelID] === undefined) { return }
	// Shuffle Retro Feedback
	shuffle(channels[channelID].plus)
	shuffle(channels[channelID].minus)
	shuffle(channels[channelID].question)
	shuffle(channels[channelID].idea)
	shuffle(channels[channelID].props)
	// Send the full retro to post
	var channel = slackbot.getChannelGroupOrDMByID(channelID)
	var summary = "```Randomized Summary of Inputs From This Retrospective \n\n"
	summary += "# Positives: \n" + channels[channelID].plus.join("\n")
	summary += "\n\n# Negatives: \n" + channels[channelID].minus.join("\n")
	summary += "\n\n# Questions: \n" + channels[channelID].question.join("\n")
	summary += "\n\n# Ideas: \n" + channels[channelID].idea.join("\n")
	summary += "\n\n# Props: \n" + channels[channelID].props.join("\n")
	summary += "```"
	channel.send(summary)
	// Delete retro to reset
	delete channels[channelID]
}

function addtoarray(channelID, line, type) {
	if (line.length > 2) {
		channels[channelID][type].push(line)
		console.log(channels)
	}
}

function slackmessage(message) {
	// console.log(message.text, message.channel, message.user)
	if (! message.text) { return }
	var channel = slackbot.getChannelGroupOrDMByID(message.channel)
	if (isMessageForMe(message)) {
	    if (message.text.indexOf("start") >= 0) {
	    	startretro(message.channel)
	    }
	    else if (message.text.indexOf("stop") >= 0) {
	    	stopretro(message.channel)
	    }
	    else if (message.text.indexOf("help") >=0) {
	    	channel.send("Let me help you make retrospectives great!\n"
	    		+ "To start your retrospective type `@retrobot start`. "
	    		+ "To end the retrospective and print out a randomized summary of feedback type `@retrobot stop`.\n\n"
	    		+ "To make a positive remark, start your message with `+`. Negative or needs improvement, start with `-`. "
	    		+ "For questions you may have, start your messsage with a `?`.\n\n"
	    		+ "For ideas you may have, start your messsage with a `!`.\n\n"
	    		+ "To give props to someone for a job well done or help you got, start your messsage with a `*` and mention what they did to be awesome!\n\n"
	    		+ "You can put multiple pieces of feedback in one message if you'd rather not print each thought on a new line.\n\n"
	    		+ "I was made by kat. Please direct questions or feedback to her.")
	    }
	    else {
	    	channel.send("That is not a retro command! (Try @retrobot help)")
	    }
    }

	else if (channels[message.channel] !== undefined) {

		var lines = message.text.split("\n")
		console.log(lines)
		for (i in lines) {
			console.log(lines[i])
			var char1 = lines[i].substr(0,1)
			switch(char1) {
				case "+":
					addtoarray(message.channel, lines[i], "plus")
					break
				case "-":
					addtoarray(message.channel, lines[i], "minus")
					break
				case "?":
					addtoarray(message.channel, lines[i], "question")
					break
				case "!":
					addtoarray(message.channel, lines[i], "idea")
					break
				case "*":
					addtoarray(message.channel, lines[i], "props")
					break
			}
		}
	}
}

slackbot.login()

<commit_msg>don't display empty sections<commit_after>require("dotenv").load()
var SlackClient = require("slack-client")
var shuffle = require("shuffle-array")

var token = process.env.SLACK_TOKEN // slackbot's integration token.
var autoReconnect = true // Automatically reconnect after an error response from Slack.
var autoMark = true // Automatically mark each message as read after it is processed.
var channels = {}

var slackbot = new SlackClient(token, autoReconnect, autoMark)

slackbot.on("open", slackopened)
slackbot.on("message", slackmessage)

function slackopened() {
	console.log("I'm alive!")
}

function isMessageForMe(message) {
  return (message.text && message.text.substr(0, 12) === `<@${slackbot.self.id}>`);
}

function startretro(channelID) {
	channels[channelID] = {
		plus: [],
		minus: [],
		question: [],
		idea: [],
		props: []
	}
	var channel = slackbot.getChannelGroupOrDMByID(channelID)
	console.log("Starting Retro")
	channel.send("<!here|here>: Starting Retro Recording. \n Please use `+` for positive, `-` for needs improvement, `?` for questions, `!` for ideas, and `*` to give props to someone!")
}

function stopretro(channelID) {
	if (channels[channelID] === undefined) { return }
	// Shuffle Retro Feedback
	shuffle(channels[channelID].plus)
	shuffle(channels[channelID].minus)
	shuffle(channels[channelID].question)
	shuffle(channels[channelID].idea)
	shuffle(channels[channelID].props)
	// Send the full retro to post
	var channel = slackbot.getChannelGroupOrDMByID(channelID)
	var summary = "```Randomized Summary of Inputs From This Retrospective"
	summary += display(channelID, "Positives", "plus")
	summary += display(channelID, "Negatives", "minus")
	summary += display(channelID, "Questions", "question")
	summary += display(channelID, "Ideas", "idea")
	summary += display(channelID, "Props", "props")
	summary += "```"
	channel.send(summary)
	// Delete retro to reset
	delete channels[channelID]
}

function display(channelID, name, type) {
	if (channels[channelID][type].length !== 0) {
		return "\n\n# " + name + ": \n" + channels[channelID][type].join("\n")
	}
	return ""
}

function addtoarray(channelID, line, type) {
	if (line.length > 2) {
		channels[channelID][type].push(line)
		console.log(channels)
	}
}

function slackmessage(message) {
	// console.log(message.text, message.channel, message.user)
	if (! message.text) { return }
	var channel = slackbot.getChannelGroupOrDMByID(message.channel)
	if (isMessageForMe(message)) {
	    if (message.text.indexOf("start") >= 0) {
	    	startretro(message.channel)
	    }
	    else if (message.text.indexOf("stop") >= 0) {
	    	stopretro(message.channel)
	    }
	    else if (message.text.indexOf("help") >=0) {
	    	channel.send("Let me help you make retrospectives great!\n"
	    		+ "To start your retrospective type `@retrobot start`. "
	    		+ "To end the retrospective and print out a randomized summary of feedback type `@retrobot stop`.\n\n"
	    		+ "To make a positive remark, start your message with `+`. Negative or needs improvement, start with `-`. "
	    		+ "For questions you may have, start your messsage with a `?`.\n\n"
	    		+ "For ideas you may have, start your messsage with a `!`.\n\n"
	    		+ "To give props to someone for a job well done or help you got, start your messsage with a `*` and mention what they did to be awesome!\n\n"
	    		+ "You can put multiple pieces of feedback in one message if you'd rather not print each thought on a new line.\n\n"
	    		+ "I was made by kat. Please direct questions or feedback to her.")
	    }
	    else {
	    	channel.send("That is not a retro command! (Try @retrobot help)")
	    }
    }

	else if (channels[message.channel] !== undefined) {

		var lines = message.text.split("\n")
		console.log(lines)
		for (i in lines) {
			console.log(lines[i])
			var char1 = lines[i].substr(0,1)
			switch(char1) {
				case "+":
					addtoarray(message.channel, lines[i], "plus")
					break
				case "-":
					addtoarray(message.channel, lines[i], "minus")
					break
				case "?":
					addtoarray(message.channel, lines[i], "question")
					break
				case "!":
					addtoarray(message.channel, lines[i], "idea")
					break
				case "*":
					addtoarray(message.channel, lines[i], "props")
					break
			}
		}
	}
}

slackbot.login()

<|endoftext|>


<commit_before>Vps.Auto.FormPanel = Ext.extend(Vps.Binding.AbstractPanel, {
    autoScroll: true, //um scrollbars zu bekommen
    border: false,
    maskDisabled: true,
    layout: 'fit',

    initComponent: function()
    {
        if (!this.formConfig) this.formConfig = {};
        if (!this.baseParams) this.baseParams = {};
        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        this.addEvents(
            'loadform',
            'deleteaction',
            'addaction',
            'renderform'
        );
        this.actions.save = new Ext.Action({
            text    : trlVps('Save'),
            icon    : '/assets/silkicons/table_save.png',
            cls     : 'x-btn-text-icon',
            handler : this.onSave,
            scope   : this
        });
        this.actions.saveBack = new Ext.Action({
            text    : trlVps('Save and Back'),
            icon    : '/assets/silkicons/table_save.png',
            cls     : 'x-btn-text-icon',
            handler : this.onSaveBack,
            scope   : this,
            hidden  : true //standardmäßig versteckt, ComponentPanel ruft show() auf
        });
        this.actions['delete'] = new Ext.Action({
            text    : trlVps('Delete'),
            icon    : '/assets/silkicons/table_delete.png',
            cls     : 'x-btn-text-icon',
            handler : this.onDelete,
            scope   : this
        });
        this.actions.add = new Ext.Action({
            text    : trlVps('New Entry'),
            icon    : '/assets/silkicons/table_add.png',
            cls     : 'x-btn-text-icon',
            handler : this.onAdd,
            scope   : this
        });

        Vps.Auto.FormPanel.superclass.initComponent.call(this);

        if (!this.formConfig) this.formConfig = {};
        Ext.applyIf(this.formConfig, {
            baseParams       : {},
            trackResetOnLoad : true,
            maskDisabled     : false,
        });

        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoForm.');
        }
        this.formConfig.url = this.controllerUrl + '/json-save';
    },

    doAutoLoad : function()
    {
        //autoLoad kann in der zwischenzeit abgeschaltet werden, zB wenn
        //wir in einem Binding sind
        if (!this.autoLoad) return;

        this.load();
    },

    onMetaChange : function(meta)
    {
        Ext.applyIf(meta.form, this.formConfig);

        if (this.baseCls) meta.form.baseCls = this.baseCls; //use the same

        for (var i in this.actions) {
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        if (meta.buttons && typeof meta.form.tbar == 'undefined') {
            for (var b in meta.buttons) {
                if (!meta.form.tbar) meta.form.tbar = [];
                meta.form.tbar.push(this.getAction(b));
            }
	        if (meta.helpText) {
				meta.form.tbar.push('->');
	            meta.form.tbar.push(new Ext.Action({
	                icon : '/assets/silkicons/information.png',
	                cls : 'x-btn-icon',
	                handler : function (a) {
	                    var helpWindow = new Ext.Window({
	                        html: meta.helpText,
	                        width: 400,
	                        bodyStyle: 'padding: 10px; background-color: white;',
	                        autoHeight: true,
	                        bodyBorder : false,
	                        title: trlVps('Info'),
	                        resize: false
	                    });
	                    helpWindow.show();
	                },
	                scope: this
	            }));
	        }
        }
        if (this.formPanel != undefined) {
            this.remove(this.formPanel, true);
        }

        this.formPanel = new Ext.FormPanel({
            autoScroll: true,
            items: meta.form
        });
        this.formPanel.on('render', function() {
            this.fireEvent('renderform', this.getForm());
        }, this);
        this.add(this.formPanel);
        this.doLayout();
        this.getForm().baseParams = this.baseParams;
    },

    isDirty : function() {
        var f = this.getForm();
        if (!f) return false;
        return f.isDirty();
    },

    load : function(params, options) {

        if (this.el) this.el.mask(trlVps('Loading...'));

        if (!params) params = {};

        //es kann auch direkt die id übergeben werden
        if (typeof params != 'object') params = { id: params };

        this.applyBaseParams(params);

        if (!this.getForm()) {
            params.meta = true; //wenn noch keine form vorhanden metaDaten anfordern
        }
        Ext.applyIf(params, this.baseParams);

        if (this.getForm()) {
            this.getForm().clearValues();
            this.getForm().clearInvalid();
            this.getForm().resetDirty();
        }

        Ext.Ajax.request({
            mask: !this.el, //globale mask wenn kein el vorhanden
            loadOptions: options,
            url: this.controllerUrl+'/json-load',
            params: params,
            success: function(response, options, result) {
                if (result.meta) {
                    this.onMetaChange(result.meta);
                }
                if (result.data && this.getForm()) {
                    if (this.actions['delete']) this.actions['delete'].enable();
//                     if (this.getForm()) {
                        this.getForm().setValues(result.data);
                    this.fireEvent('loadform', this.getForm(), result.data);
//todo: werte zwischenspeichern und setzen wenn form gerendered wurde?
//erstmal auskommentiert, da das eher nach hack aussschaut und womöglich eh gar nicht gebraucht wird...
//                     } else {
//                         this.on('renderform', function(form) {
//                             form.setValues(this.data);
//                             form.resetDirty();
//                         }, result);
//                     }
                }
                if (this.getForm()) {
                    this.getForm().clearInvalid();
                    this.getForm().resetDirty();
                }
                var lo = options.loadOptions;
                if (lo && lo.success) {
                    lo.success.call(lo.scope || this, this, result);
                }
            },
            failure: function(response, options, result){
                var lo = options.loadOptions;
                if (lo && lo.failure) {
                    lo.failure.call(lo.scope || this, this, result);
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
            },
            scope: this
        });
    },

    //für AbstractPanel
    reset : function() {
        this.getForm().reset();
        this.getForm().resetDirty();
    },

    //deprecated
    onSubmit : function(options, successCallback) {
        if (!options) options = {};
        options.success = successCallback.callback;
        this.submit(options, successCallback);
    },

    //private
    onSave : function() {
        this.submit();
    },

    onSaveBack : function() {
        this.submit({
            success: function() {
                this.fireEvent('savebackaction', this);
            },
            scope: this
        });
    },

    //für AbstractPanel
    submit: function(options)
    {
        if (!this.getForm().isValid()) {
            Ext.Msg.alert(trlVps('Save'),
                trlVps("Can't save, please fill all marked fields correctly."));
            return;
        }

        this.getAction('save').disable();

        if (!options) options = {};

        var cb = {
            success: options.success,
            failure: options.failure,
            callback: options.callback,
            scope: options.scope || this
        };

        if (this.el) this.el.mask(trlVps('Saving...'));

        var params = this.getForm().getValues();
        for (var i in params) {
            if (typeof params[i] == 'object') {
                params[i] = Ext.encode(params[i]);
            } else if (typeof params[i] == 'boolean') {
                params[i] = params[i] ? '1' : '0';
            }
        }

        Ext.apply(params, this.getBaseParams());
        Ext.Ajax.request(Ext.apply(options, {
            params: params,
            url: this.controllerUrl+'/json-save',
            success: function() {
                this.onSubmitSuccess.apply(this, arguments);
                if (cb.success) {
                    cb.success.apply(cb.scope, arguments);
                }
            },
            failure: function() {
                this.onSubmitFailure.apply(this, arguments);
                if (cb.failure) {
                    cb.failure.apply(cb.scope, arguments);
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
                if (cb.callback) {
                    cb.callback.apply(cb.scope, arguments);
                }
            },
            scope: this
        }));
    },
    onSubmitFailure: function(form, action) {
        if(action.failureType == Ext.form.Action.CLIENT_INVALID) {
            Ext.Msg.alert(trlVps('Save'),
                trlVps("Can't save, please fill all marked fields correctly."));
        }
        this.getAction('save').enable();
    },

    onSubmitSuccess: function(response, options, result) {
        this.getForm().resetDirty();
        this.fireEvent('datachange', result);

        var reEnableSubmitButton = function() {
            this.getAction('save').enable();
        };
        reEnableSubmitButton.defer(1000, this);

        if(result.data && result.data.addedId) {
            this.getForm().baseParams.id = result.data.addedId;
            this.getAction('delete').enable();
            this.getAction('save').enable();
        }
        if (this.getForm().loadAfterSave) {
            //bei file-upload neu laden
            this.reload();
        }
    },
    onDelete : function() {
        Ext.Msg.show({
        title:trlVps('delete?'),
        msg: trlVps('Do you really want to delete this entry?'),
        buttons: Ext.Msg.YESNO,
        scope: this,
        fn: function(button) {
            if (button == 'yes') {

                Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: {id: this.getForm().baseParams.id},
                        success: function(response, options, r) {
                            this.fireEvent('datachange', r);
                            this.getForm().clearValues();
                            this.getForm().clearInvalid();
                            this.getForm().resetDirty();
                            this.disable();
                            this.fireEvent('deleteaction', this);
                        },
                        scope: this
                    });
            }
        }
        });
    },
    onAdd : function() {
        var cb = function() {
            this.enable();
            if (this.deleteButton) this.deleteButton.disable();
            this.getAction('delete').disable();
            this.applyBaseParams({id: 0});
            this.getForm().setDefaultValues();
            this.getForm().clearInvalid();
            this.fireEvent('addaction', this);

            //wenn  form in einem tab, die form anzeigen
            //nach addaction, damit in grid an dem die form gebunden ist die activeId
            //auf 0 gesetzt werden kann
            if (this.ownerCt instanceof Ext.TabPanel) {
                this.ownerCt.setActiveTab(this);
            }
        };
        if (!this.getForm()) {
            //meta-daten wurden noch nicht geladen
            this.load({}, {success: cb, scope: this});
        } else {
            if (this.mabySubmit({ callback: cb, scope: this})) {
                cb.call(this);
            }
        }
    },
    findField: function(id) {
        return this.getForm().findField(id);
    },
    getForm : function() {
        if (!this.getFormPanel()) return null;
        return this.getFormPanel().getForm();
    },
    getFormPanel : function() {
        return this.formPanel;
    },
    setBaseParams : function(baseParams) {
        this.baseParams = baseParams;
        if (this.getForm()) {
            this.getForm().baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        Ext.apply(this.baseParams, baseParams);
        if (this.getForm()) {
            Ext.apply(this.getForm().baseParams, baseParams);
        }
    },
    getBaseParams : function() {
        return this.baseParams;
    }
});

Ext.reg('vps.autoform', Vps.Auto.FormPanel);
<commit_msg>hintergrundfarbe in popup nicht weiss<commit_after>Vps.Auto.FormPanel = Ext.extend(Vps.Binding.AbstractPanel, {
    autoScroll: true, //um scrollbars zu bekommen
    border: false,
    maskDisabled: true,
    layout: 'fit',

    initComponent: function()
    {
        if (!this.formConfig) this.formConfig = {};
        if (!this.baseParams) this.baseParams = {};
        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        this.addEvents(
            'loadform',
            'deleteaction',
            'addaction',
            'renderform'
        );
        this.actions.save = new Ext.Action({
            text    : trlVps('Save'),
            icon    : '/assets/silkicons/table_save.png',
            cls     : 'x-btn-text-icon',
            handler : this.onSave,
            scope   : this
        });
        this.actions.saveBack = new Ext.Action({
            text    : trlVps('Save and Back'),
            icon    : '/assets/silkicons/table_save.png',
            cls     : 'x-btn-text-icon',
            handler : this.onSaveBack,
            scope   : this,
            hidden  : true //standardmäßig versteckt, ComponentPanel ruft show() auf
        });
        this.actions['delete'] = new Ext.Action({
            text    : trlVps('Delete'),
            icon    : '/assets/silkicons/table_delete.png',
            cls     : 'x-btn-text-icon',
            handler : this.onDelete,
            scope   : this
        });
        this.actions.add = new Ext.Action({
            text    : trlVps('New Entry'),
            icon    : '/assets/silkicons/table_add.png',
            cls     : 'x-btn-text-icon',
            handler : this.onAdd,
            scope   : this
        });

        Vps.Auto.FormPanel.superclass.initComponent.call(this);

        if (!this.formConfig) this.formConfig = {};
        Ext.applyIf(this.formConfig, {
            baseParams       : {},
            trackResetOnLoad : true,
            maskDisabled     : false,
        });

        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoForm.');
        }
        this.formConfig.url = this.controllerUrl + '/json-save';
    },

    doAutoLoad : function()
    {
        //autoLoad kann in der zwischenzeit abgeschaltet werden, zB wenn
        //wir in einem Binding sind
        if (!this.autoLoad) return;

        this.load();
    },

    onMetaChange : function(meta)
    {
        Ext.applyIf(meta.form, this.formConfig);

        if (this.baseCls) meta.form.baseCls = this.baseCls; //use the same

        for (var i in this.actions) {
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        if (meta.buttons && typeof meta.form.tbar == 'undefined') {
            for (var b in meta.buttons) {
                if (!meta.form.tbar) meta.form.tbar = [];
                meta.form.tbar.push(this.getAction(b));
            }
	        if (meta.helpText) {
				meta.form.tbar.push('->');
	            meta.form.tbar.push(new Ext.Action({
	                icon : '/assets/silkicons/information.png',
	                cls : 'x-btn-icon',
	                handler : function (a) {
	                    var helpWindow = new Ext.Window({
	                        html: meta.helpText,
	                        width: 400,
	                        bodyStyle: 'padding: 10px; background-color: white;',
	                        autoHeight: true,
	                        bodyBorder : false,
	                        title: trlVps('Info'),
	                        resize: false
	                    });
	                    helpWindow.show();
	                },
	                scope: this
	            }));
	        }
        }
        if (this.formPanel != undefined) {
            this.remove(this.formPanel, true);
        }

        this.formPanel = new Ext.FormPanel({
            baseCls: 'x-plain',
            autoScroll: true,
            items: meta.form
        });
        this.formPanel.on('render', function() {
            this.fireEvent('renderform', this.getForm());
        }, this);
        this.add(this.formPanel);
        this.doLayout();
        this.getForm().baseParams = this.baseParams;
    },

    isDirty : function() {
        var f = this.getForm();
        if (!f) return false;
        return f.isDirty();
    },

    load : function(params, options) {

        if (this.el) this.el.mask(trlVps('Loading...'));

        if (!params) params = {};

        //es kann auch direkt die id übergeben werden
        if (typeof params != 'object') params = { id: params };

        this.applyBaseParams(params);

        if (!this.getForm()) {
            params.meta = true; //wenn noch keine form vorhanden metaDaten anfordern
        }
        Ext.applyIf(params, this.baseParams);

        if (this.getForm()) {
            this.getForm().clearValues();
            this.getForm().clearInvalid();
            this.getForm().resetDirty();
        }

        Ext.Ajax.request({
            mask: !this.el, //globale mask wenn kein el vorhanden
            loadOptions: options,
            url: this.controllerUrl+'/json-load',
            params: params,
            success: function(response, options, result) {
                if (result.meta) {
                    this.onMetaChange(result.meta);
                }
                if (result.data && this.getForm()) {
                    if (this.actions['delete']) this.actions['delete'].enable();
//                     if (this.getForm()) {
                        this.getForm().setValues(result.data);
                    this.fireEvent('loadform', this.getForm(), result.data);
//todo: werte zwischenspeichern und setzen wenn form gerendered wurde?
//erstmal auskommentiert, da das eher nach hack aussschaut und womöglich eh gar nicht gebraucht wird...
//                     } else {
//                         this.on('renderform', function(form) {
//                             form.setValues(this.data);
//                             form.resetDirty();
//                         }, result);
//                     }
                }
                if (this.getForm()) {
                    this.getForm().clearInvalid();
                    this.getForm().resetDirty();
                }
                var lo = options.loadOptions;
                if (lo && lo.success) {
                    lo.success.call(lo.scope || this, this, result);
                }
            },
            failure: function(response, options, result){
                var lo = options.loadOptions;
                if (lo && lo.failure) {
                    lo.failure.call(lo.scope || this, this, result);
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
            },
            scope: this
        });
    },

    //für AbstractPanel
    reset : function() {
        this.getForm().reset();
        this.getForm().resetDirty();
    },

    //deprecated
    onSubmit : function(options, successCallback) {
        if (!options) options = {};
        options.success = successCallback.callback;
        this.submit(options, successCallback);
    },

    //private
    onSave : function() {
        this.submit();
    },

    onSaveBack : function() {
        this.submit({
            success: function() {
                this.fireEvent('savebackaction', this);
            },
            scope: this
        });
    },

    //für AbstractPanel
    submit: function(options)
    {
        if (!this.getForm().isValid()) {
            Ext.Msg.alert(trlVps('Save'),
                trlVps("Can't save, please fill all marked fields correctly."));
            return;
        }

        this.getAction('save').disable();

        if (!options) options = {};

        var cb = {
            success: options.success,
            failure: options.failure,
            callback: options.callback,
            scope: options.scope || this
        };

        if (this.el) this.el.mask(trlVps('Saving...'));

        var params = this.getForm().getValues();
        for (var i in params) {
            if (typeof params[i] == 'object') {
                params[i] = Ext.encode(params[i]);
            } else if (typeof params[i] == 'boolean') {
                params[i] = params[i] ? '1' : '0';
            }
        }

        Ext.apply(params, this.getBaseParams());
        Ext.Ajax.request(Ext.apply(options, {
            params: params,
            url: this.controllerUrl+'/json-save',
            success: function() {
                this.onSubmitSuccess.apply(this, arguments);
                if (cb.success) {
                    cb.success.apply(cb.scope, arguments);
                }
            },
            failure: function() {
                this.onSubmitFailure.apply(this, arguments);
                if (cb.failure) {
                    cb.failure.apply(cb.scope, arguments);
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
                if (cb.callback) {
                    cb.callback.apply(cb.scope, arguments);
                }
            },
            scope: this
        }));
    },
    onSubmitFailure: function(form, action) {
        if(action.failureType == Ext.form.Action.CLIENT_INVALID) {
            Ext.Msg.alert(trlVps('Save'),
                trlVps("Can't save, please fill all marked fields correctly."));
        }
        this.getAction('save').enable();
    },

    onSubmitSuccess: function(response, options, result) {
        this.getForm().resetDirty();
        this.fireEvent('datachange', result);

        var reEnableSubmitButton = function() {
            this.getAction('save').enable();
        };
        reEnableSubmitButton.defer(1000, this);

        if(result.data && result.data.addedId) {
            this.getForm().baseParams.id = result.data.addedId;
            this.getAction('delete').enable();
            this.getAction('save').enable();
        }
        if (this.getForm().loadAfterSave) {
            //bei file-upload neu laden
            this.reload();
        }
    },
    onDelete : function() {
        Ext.Msg.show({
        title:trlVps('delete?'),
        msg: trlVps('Do you really want to delete this entry?'),
        buttons: Ext.Msg.YESNO,
        scope: this,
        fn: function(button) {
            if (button == 'yes') {

                Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: {id: this.getForm().baseParams.id},
                        success: function(response, options, r) {
                            this.fireEvent('datachange', r);
                            this.getForm().clearValues();
                            this.getForm().clearInvalid();
                            this.getForm().resetDirty();
                            this.disable();
                            this.fireEvent('deleteaction', this);
                        },
                        scope: this
                    });
            }
        }
        });
    },
    onAdd : function() {
        var cb = function() {
            this.enable();
            if (this.deleteButton) this.deleteButton.disable();
            this.getAction('delete').disable();
            this.applyBaseParams({id: 0});
            this.getForm().setDefaultValues();
            this.getForm().clearInvalid();
            this.fireEvent('addaction', this);

            //wenn  form in einem tab, die form anzeigen
            //nach addaction, damit in grid an dem die form gebunden ist die activeId
            //auf 0 gesetzt werden kann
            if (this.ownerCt instanceof Ext.TabPanel) {
                this.ownerCt.setActiveTab(this);
            }
        };
        if (!this.getForm()) {
            //meta-daten wurden noch nicht geladen
            this.load({}, {success: cb, scope: this});
        } else {
            if (this.mabySubmit({ callback: cb, scope: this})) {
                cb.call(this);
            }
        }
    },
    findField: function(id) {
        return this.getForm().findField(id);
    },
    getForm : function() {
        if (!this.getFormPanel()) return null;
        return this.getFormPanel().getForm();
    },
    getFormPanel : function() {
        return this.formPanel;
    },
    setBaseParams : function(baseParams) {
        this.baseParams = baseParams;
        if (this.getForm()) {
            this.getForm().baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        Ext.apply(this.baseParams, baseParams);
        if (this.getForm()) {
            Ext.apply(this.getForm().baseParams, baseParams);
        }
    },
    getBaseParams : function() {
        return this.baseParams;
    }
});

Ext.reg('vps.autoform', Vps.Auto.FormPanel);
<|endoftext|>