//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class="content"> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  "app",

  //templates-loader: this loads templates async.
  "js/templates-loader",

  "modules/modal2",

  "Mousetrap",

  "js/bootstrap-select/bootstrap-select",
  "js/bootstrap-select/FormSelectBootstrap",

  "js/jstree/jstree",

],

function (app, T, Modal, Mousetrap) {

    var TREE_NODE_ROOT_ID = -1;

    //replace all "Screen" with your view's name.
    var Screen = { Models: {}, Views: {} }

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            id: 0,
            ihId: app.models.ihDataSources.get('id'),
            typeId: 0,
            search: '',

            procedure: '',

            collapsed: false,

            selected: null,

            models: [],
            icons: [],
        },
        computeds: {
            hasModels: {
                deps: ['models'],
                get: function (models) {
                    return models.length != 0;
                },
            },
        },
        fetchModels: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            //qp.Add('@onlyEnabled', 'BIT', 1);
            qp.Add('@ihId', 'INT', app.models.ihDataSources.get('id'));

            Core.Json.CallProcedure(
                app.DatabaseNames.System + ".EQUIP.GetAssignableEquipmentModels",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                
                                var newItems = _.map(records, function (obj) { return { value: obj.Id, label: obj.TypeName, iconId: obj.IconId, typeId: obj.TypeId, style: (obj.ChildHierarchyId.IsNull != true) ? 'font-weight:bold;' : '', Template: 'main' }; });

                                that.set("models", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        fetchIcons: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            //qp.Add('@onlyEnabled', 'BIT', 1);
            qp.Add('@ihId', 'INT', app.models.ihDataSources.get('id'));

            Core.Json.CallProcedure(
                app.DatabaseNames.System + ".EQUIP.GetEquipmentTypeIcons",
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var records = resp.Table;

                                var newItems = _.map(records, function (obj) { return { id: obj.Id, name: obj.Name, data: obj.Data, Template: obj.Template}; });

                                that.set("icons", newItems);
                            }
                            else {
                                if ((resp) && (resp.Message))
                                    console.error(resp.Message);
                                else
                                    console.error("Server response not valid.");
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onFailure: function (resp) {
                        console.error(resp);
                    },
                    Secured: true,
                    Async: false,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        initialize: function () {
        },
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    Screen.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "equipment-types";
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: "equipment-types"
        , id: "equipment-types"
        , title: "Equipment Types"
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        , isCacheable: false

        , items: null
        , subviews: null

        , templates: null
        , currentModal: null

        , initialize: function () {
            _.extend(this, this.options);

            this.state = app.view_states.loading;
            this.onappend = (_.isFunction(this.onappend)) ? this.onappend : function () { };

            var that = this;

            this.tree = null;

            this.templates = {
                addExistingModal: null,
            };

            var model = new Screen.Models.Main();
            
            this.model = model;
            this.model.fetchModels();
            this.model.fetchIcons();
            
            this.items = new Screen.Models.Items();

            this.autoRefresh = {
                    enabled: false
                    , toid: null
                    , every: 30 * 1000
                };

            this.subviews = {
                newMachine: {
                    view: null,
                    model: null,
                },
                machineConfiguration: {
                    view: null,
                    model: null
                },
                subnavbarControls: new Screen.Views.SubnavBarControls({
                    model: this.model,
                    parent: this,
                    container: app.views.subnavbar.getSectionContainer(1, 12),
                    events:
                        function () {
                            try {
                                return {
                                    'click .btn-add-item': _.bind(that.btnAddItem_click, that),
                                    'click .btn-tree': _.bind(that.btnCollapseExpandTree, that),
                                };
                            } catch (Error) { console.error(Error); }
                    },
                }),
            };

            if (this.viewParams.sectionParam1) {
                this.model.set('typeId', this.viewParams.sectionParam1)
            }
            
            this.bindEvents();
        }

        , events: {
            //"click .btn-add-item": "addItem",
            //"click .btn-add-area": "addArea",
            //"click .btn-add-line": "addLine",
            //"click .btn-add-machine": "addMachine",
        }
        
        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.items, "add", this.itemsChanged);
            this.listenTo(this.items, "remove", this.itemsChanged);
            this.listenTo(this.items, "change", this.itemsChanged);
            this.listenTo(this.model, "change:typeId", this.search_filters_changed);
            this.listenTo(this.model, "change:search", _.debounce(this._search_changed, 800));
            
        }

        , _refresh: function (opt) {
            try {
                //console.log('autorefresh: ' + new Date().toString()); 
                if (this.autoRefresh.toid != null) {
                    clearTimeout(this.autoRefresh.toid);
                    this.autoRefresh.toid = null;
                }

                var attrs = this.model.toJSON();

                this.refreshItemsColl(_.extend(
                    {},
                    opt,
                    {
                        params: {
                            id: attrs.Id,
                            search: attrs.search,
                            ihId: attrs.ihId,
                        }
                    })
                );

                if (this.autoRefresh.enabled == true) {
                    this.autoRefresh.toid = setTimeout(
                        _.bind(this._refresh, this),
                        this.autoRefresh.every
                    );
                }
            } catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        refresh: function (options) {
            try {
                var that = this,
                    opt = _.extend({}, options);

                //If currentModal exists, hide it and erase it.
                if (this.currentModal) {
                    this.currentModal.hide();
                    this.currentModal = null;
                }

                //if (this.viewParams.sectionParam1 != this.model.get('typeId')) {
                //    this.model.set('typeId', this.viewParams.sectionParam1)
                //}

                var params = this.model.toJSON();

                this._refresh(_.extend(
                    {},
                    params,
                    {   
                        reset: true,
                    }
                ));
            } catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        refreshItemsColl: function (options) {
            try {
                var that = this,
                    attrs = this.model.toJSON(),
                    opt = _.extend({}, { params: {}, refresh: true, }, options);

                if (opt.reset == true) {
                    this.model.set({
                        isLoading: true,
                    });
                }
                //this.setTreeLoadingState(true);

                //Parameter details:
                // > Parameter 'reset' is used to reload only the first page of records and
                // show the 'Loading' poster.
                // > Parameter 'refresh' is uset to reload all the currently loaded records
                // without showing the 'Loading' poster.
                this.items.fetch(_.extend(
                    {},
                    opt,
                    {
                        params: {
                            id: (attrs.id > 0) ? attrs.id : null,
                            search: attrs.search,
                            ihId: attrs.ihId,
                        },
                        codesText: app.translate(that, "root_tree_text"),
                        callback: function () {
                             

                            //Force to set loading state to false if action is MOVE because the refresh after
                            //this transaction does not modify the collection. So callback of tree changes is not
                            //fired and laoding state and jstree objects are not refreshed. Due to that it is necessary
                            //do it here.
                            //if (opt.action == 'MOVE') {
                            if (opt.action == 'insert') {
                                that.tree.select_node(opt.node);
                            }

                            that.setTreeLoadingState(false);

                            this.items.fetchModels();
                            //    that.tree.refresh(true);
                            //}
                        },
                    })
                );

            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

        render: function (container) {
            var that = this;
            var thatContainer = (container != null && container != undefined) ? container : this.container;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/modules/equipments/configuration/equipment-types/";

            T.render.call(this, this.template, function (tmp) {
                if (!that.i18n) that.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.i18n[that.template] = i18nJED;
                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)

                    //end:

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp());

                    that.applyBindings();

                    that.bindViewScopedEvents();

                    that.subviews.subnavbarControls.render();

                    //start: the view was already loaded an is on a div element, but not appended to the main container
                    //here you can perform anything you want DOM related, by getting the dom element via that.$el.find("#id")
                    //or this.$("#id")
                    //end

                    $.jstree.defaults.core.themes.variant = "large";
                    var times = 0;
                    that.$el.find(".tree").jstree({
                        core: {
                            check_callback: true,
                            data: function (obj, cb) {
                                var data = that.items.toJSON();

                                //setting disabled nodes
                                _.each(data, function (t) { t.li_attr = { "class": (t.enabled) ? "" : "node-disabled" } });

                                cb.call(this, data);
                            },
                            expand_selected_onload: true,
                        },
                        types: {
                            //"root": {
                            //    icon: 'data:image/gif;base64, ',
                            //},
                            //"#": {
                            //    valid_children: ['root', 'area', 'line'],
                            //    //max_children: 1,
                            //},
                            //"root": {
                            //    icon: "fa fa-building",
                            //    valid_children: ['area', 'line'],
                            //},
                            //"area": {
                            //    icon: "fa fa-th-large",
                            //    valid_children: ['line']
                            //},
                            //"line": {
                            //    "icon": "fa fa-sitemap",
                            //    valid_children: ['machine'],
                            //},
                            //"machine": {
                            //    "icon": "fa fa-cog",
                            //    max_children: 0
                            //},
                            //"loading": {
                            //    "icon": "fa fa-spinner fa-spin",
                            //    valid_children: ['area', 'line', 'machine'],
                            //},
                        },
                        contextmenu: {
                            items: _.bind(that.customTreeCtxMenu, that),
                        },
                        sort: function (a, b) {
                            var nodea = this.get_node(a);
                            var nodeb = this.get_node(b);

                            var collection = that.items;
                            var model_a = collection.get(nodea.id);
                            var model_b = collection.get(nodeb.id);

                            if (model_a && model_b)
                                return model_a.get("order") > model_b.get("order") ? 1 : -1;
                            else if (model_a) return -1;
                            else if (model_b) return 1;
                            else return -1;
                        },
                        plugins: [
                            "contextmenu",
                            //"dnd", //Drag and drop
                            "wholerow",
                            "types",
                            "sort",
                        ],
                    });

                    that.tree = that.$el.find(".tree").jstree(true);

                    //Configure types for the tree
                    //for (var i = 0; i < that.model.get('types').length; i++) {
                    //    if (that.model.get('types')[i].iconId)
                    //        that.tree.settings.types[that.model.get('types')[i].label.toLowerCase()] =
                    //            {
                    //                icon: 'data:image/png;base64,' + that.model.get('types')[i].iconData,
                    //                    //_.findWhere(
                    //                    //    that.model.get('icons'),
                    //                    //    { id: that.model.get('types')[i].iconId }
                    //                    //).data
                    //            };
                    //}

                    that.$el.find(".tree").bind({
                        "rename_node.jstree": _.bind(that.onRenameNode, that),
                        "create_node.jstree": _.bind(that.onCreateNode, that),
                        //"delete_node.jstree": _.bind(that.onDeleteNode, that),
                        //"enable_node.jstree": _.bind(that.onEnableNode, that), 
                        "move_node.jstree": _.bind(that.onMoveNode, that),
                        "select_node.jstree": _.bind(that.onSelectNode, that),
                        "deselect_node.jstree": _.bind(that.onDeselectNode, that),
                        "deselect_all.jstree": _.bind(that.onDeselectNode, that),
                        "refresh.jstree": _.once(function () {
                            //that.$el.find(".tree").jstree("open_all");
                        }),
                        "refresh.jstree": _.bind(function () {
                            //that.$el.find(".tree").jstree("open_all");
                            //var id = that.$el.find(".tree").jstree("get_selected");
                            that.$el.find(".tree").jstree(true).deselect_all();
                            var node = that.$el.find(".tree").jstree("get_node",that.model.get('selected'));
                            that.$el.find(".tree").jstree("select_node", node);
                            that.$el.find(".tree").jstree("open_node", node);

                            if (node) {
                                that.$el.find(".tree").jstree(true).get_node(node.id, true).children('.jstree-anchor').focus();
                                that.$el.find(".tree").jstree(true).select_node(node);
                                that.model.set('selected', null);
                            }
                        }),
                    });

                    //that.subviews.machineConfiguration.view = new Screen.Views.MachineConfiguration({
                    //    container: that.$el.find(".machine-configuration-container"),
                    //    model: new Screen.Models.MachineConfiguration(), 
                    //}); 

                    //that.subviews.machineConfiguration.view.render(); 

                    that.templates.addExistingModal = Handlebars.compile(that.$el.find('#add_existing_modal_template').html());

                    //appending view to the main container
                    that.append(thatContainer, that.$el);

                    that.startAutoRefresh();
                }, true, customPath);

            //Deprecated parameter "main template" because of issue when finding scripts in the template.
            }, customPath /*, "main template"*/);
        },
        search_filters_changed: function () {
            try {
                var params = this.model.toJSON();

                app.router.navigate(
                    app.router.resolveURL(
                        app.router.currentModule,
                        _.extend(
                            {},
                            params,
                            {
                                section: app.router.currentParameters.section,
                                sectionParam1: params.typeId,
                            }
                        ),
                        false
                    ),
                    { trigger: false, }
                );

                this._refresh({ reset: true, });
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        add_node: function (a,b) {
            try {
                this.addItem(b);
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }, 
        update_node: function (a , b) {
            try {
                //this.updateItem(b);
                this.setTreeLoadingState(true);
                this.model.set('selected', b.Id);
                this._autoRefresh();
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        _search_changed: function () {
            try {
                this.doSearch.call(this); 
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        doSearch: function () {
            var search = this.model.get("search");
            
            this.model.set('search', search);

            this._refresh({ reset: true, });
        },
        btnCollapseExpandTree: function (e) {
            var collapsed = this.model.get('collapsed');

            var btn_collapse = this.$el.find('.btn-collapse-tree');
            var btn_expand = this.$el.find('.btn-expand-tree');

            if (collapsed) {
                this.tree.open_all();
                $('.btn-collapse-tree').removeClass('hide');
                $('.btn-expand-tree').addClass('hide');

                this.model.set('collapsed', false); 
            } else {
                this.tree.close_all();
                $('.btn-collapse-tree').addClass('hide');
                $('.btn-expand-tree').removeClass('hide');

                this.model.set('collapsed', true); 
            }

        },
        btnAddItem_click: function(e) {
            try {
                var that = this;

                if (this.subviews.machineConfiguration.view)
                    this.subviews.machineConfiguration.view.close();

                if (this.subviews.newMachine.view)
                    this.subviews.newMachine.view.close();


                var newMachineContainer = this.$el.find(".new-machine-container");

                var model = new Screen.Models.MachineConfiguration({
                    parent: that,
                    ihId: that.model.get('ihId'),
                    icons: that.model.get('icons'),
                });

                this.subviews.newMachine.view = new Screen.Views.NewMachine({
                    container: newMachineContainer,
                    model: model,
                    parent: that,
                });

                var selected = this.tree.get_selected(true);
                var data = (selected) ? selected[0] : -1;

                model.fetchDetails({
                    data: {
                        id: (data) ? data.original.id : -1,
                        ihId: that.model.get('ihId'),
                    }
                });

                this.subviews.newMachine.view.render();

                this.listenToOnce(this.subviews.newMachine.view, "addNode", this.add_node);
                //var selected = this.tree.get_selected();
                //var isTemplate = (selected.length > 0 && selected[0] != -1);
                //this.addItem(isTemplate);
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

        onCreateNode: function (e, obj) {
            var that = this;
            var node = obj.node;
            var instance = obj.instance;
            var parent;
            var collection = this.items;
            var currentTreeNodeNum = this.tree.get_json(null, { flat: true }).length;

            parent = node.parent;

            if (parent == null) {
                parent = TREE_NODE_ROOT_ID;
            }

            this.setTreeLoadingState(true);

            try {
                obj.event = {
                    button: 0
                };
                    //obj.selected = [node.id],
                    //obj.node = node,
                    //that.tree.deselect_node(node);
                    //that.onDeselectNode(e, obj);
                    that.tree.deselect_all();
                    
                    instance.set_id(node, node.original.typeId);
                    node.data = { enabled: true, };

                    that.setTreeLoadingState(false);

                    
                    obj.selected = [node.id],
                    obj.node = node,
                    //that.tree.get_node(node.id, true).children('.jstree-anchor').focus();
                    node.parent = null,
                    node.parentId = null,
                    that.tree.select_node(node);
                    that.onSelectNode(e, obj);
                
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
                this.startAutoRefresh();
            }
        },
        onEnableNode: function (e, obj) {
            var that = this;
            var node = obj.node;
            var instance = obj.instance;

            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();

            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();

            this.setTreeLoadingState(true);

            try {
                var collection = this.items;
                collection.enableNode(node.id, function (ref, ids) {
                    instance.refresh(true);

                }, function (ref, code) {
                    var errorCode = 'UNKNOWN';
                    errorCode = code && _.isString(code) && code.length > 0 ? code : errorCode;

                    app.views.topMessages.showMessage(app.translate(that, errorCode.toString() + "_error_code_message"));
                    instance.refresh(true);
                });
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
            }
        },
        onMoveNode: function (e, obj) {
            var that = this;
            var node = obj.node;
            var instance = obj.instance;
            var parent;
            var collection = this.items;

            parent = node.parent;

            if (parent == null) {
                parent = TREE_NODE_ROOT_ID;
            }

            this.setTreeLoadingState(true);

            try {
                collection.reorderNode(node.id, parent, obj.position + 1, function (ref, ids) {
                    //instance.refresh(true); 
                    that._autoRefresh({ action: 'MOVE', });
                }, function () {
                    instance.refresh(true);
                });
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
            }
        },
        onRenameNode: function (e, obj) {
            var that = this;
            var node = obj.node;
            var instance = obj.instance;
            var collection = this.items;
            //var typeId = collection.get(node.id).attributes.typeId;
            //var parentTypeId = collection.get(node.id).attributes.parentTypeId;

            this.setTreeLoadingState(true);

            try {
                    //instance.set_id(node, node.id);
                    //instance.set_id(node, ids[0]);
                    //instance.refresh_node(node);
                    that.setTreeLoadingState(false);

                    that.startAutoRefresh();

                    instance.refresh(true);
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
            }
        },
        onSelectNode: function (e, obj) {
            //Select node event is fired event for right click. We don't want that because
            //we don't want to refresh item selected data on right click. So return if it is
            //right click.
            
            //Right click = 2. Also check if 'obj.event.button' because select node also is fired by
            //keyboard. In that case 'obj.event.button' is undefined. Also 'obj.event' can be undefined (but don't know why!).
            if (obj.event) {
                if ((obj.event) && (obj.event.button) && (obj.event.button == 2))
                    return;
            }

            this.checkAddLineMachineButtons(e, obj);

            var that = this;
            var node = obj.node;
            var instance = obj.instance;
            var collection = this.items;

            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();

            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();

            if (obj.selected.length < 2) {
                if (node && node.data && node.data.enabled) {
                    var machineConfigurationContainer = this.$el.find(".machine-configuration-container");

                    var model = new Screen.Models.MachineConfiguration({
                        parent: that,
                        ihId: that.model.get('ihId'),
                        icons: that.model.get('icons'),
                    });

                    this.subviews.machineConfiguration.view = new Screen.Views.MachineConfiguration({
                        container: machineConfigurationContainer,
                        model: model,
                        parent: that,
                    });

                    model.fetchDetails({
                        data: {
                            id: node.original.id,
                            ihId: that.model.get('ihId'),
                        }
                    });

                    this.subviews.machineConfiguration.view.render();

                    this.listenToOnce(this.subviews.machineConfiguration.view, "updatedNode", this.update_node);
                }
            }
        },
        onDeselectNode: function (e, obj) {
            var that = this;
            var node = obj.node;
            var instance = obj.instance;

            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();

            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();
        },
        deleteNode: function (data) {
            var tree = this.tree,
                selected = tree.get_selected(),
                collection = this.items,
                node = data,
                that = this;

            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();

            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();

            this.setTreeLoadingState(true);

            try {
                var collection_deleteNode = function (/*checkHasData*/) {
                    collection.deleteNode(node.id, node.parentId, that.model.get('ihId'), function (ref, ids) {
                        that.setTreeLoadingState(true);
                        that._autoRefresh();

                        that.model.fetchModels();
                        app.views.topMessages.showMessage(app.translate(that, "item_deleted"));
                        //tree.refresh(true);
                    }, function (ref, code) {
                        var errorCode = 'UNKNOWN';
                        errorCode = code && _.isString(code) && code.length > 0 ? code : errorCode;

                        {
                            app.views.topMessages.showMessage(app.translate(that, errorCode.toString() + "_error_code_message"));
                        }

                        that._autoRefresh();
                        //tree.refresh(true);
                    });
                }

                collection_deleteNode(/*true, false*/);
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
            }
        },
        unassignNode: function (data) {
            var tree = this.tree;
            var selected = tree.get_selected();

            //if (selected.length > 0)
            //    data = selected;

            //tree.delete_node(data);

            var that = this;
            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();

            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();

            var node = data;
            var instance = tree;
            //var node = obj.node;
            //var instance = obj.instance;
            var collection = this.items;

            this.setTreeLoadingState(true);

            try {
                var collection_unassignNode = function () {
                    collection.unassignNode(node.id, that.model.get('ihId'), function (ref, ids) {

                        that._autoRefresh();
                        app.views.topMessages.showMessage(app.translate(that, "item_unassigned"));
                        //instance.refresh(true);
                    }, function (ref, code) {
                        var errorCode = 'UNKNOWN';
                        errorCode = code && _.isString(code) && code.length > 0 ? code : errorCode;

                        {
                            app.views.topMessages.showMessage(app.translate(that, errorCode.toString() + "_error_code_message"));
                        }

                        that._autoRefresh();
                        //instance.refresh(true);
                    });
                }

                collection_unassignNode(/*true, false*/);
            }
            catch (e) {
                console.error((e.stack) ? e.stack : new Error(e).stack);

                this.setTreeLoadingState(false);
            }
        },
        enableNode: function (data, a, b, c) {
            var tree = this.tree;
            var selected = tree.get_selected();

            //if (selected.length > 0)
            //    data = selected; 

            this.onEnableNode(null, {
                node: data,
                instance: tree,
            });
            //tree.enable_node(data); 
        },
        renameNode: function (data) {
            var tree = this.tree;
            var selected = tree.get_selected();

            if (selected.length > 0)
                data = selected[0];

            if (data) {
                tree.edit((data.id) ? data.id : data);
            }
        },
        //, nodeDoubleClick: function (e, data) {
        //    var node = $(e.target).closest("li");
        //    var data = this.tree.get_node(node.prop("id"));

        //    if (data && data.id) {
        //        this.tree.edit(data.id);
        //    }
        //}

        filterModels: function (id, typeId) {
            //The param typeId indicates the type to be exclude
            //(including his direct childrens and all of his parents)

            var models = this.model.get('models'),
                items = this.items,
                excludeModels = [],
                childs = [],
                parents = [],
                currentParent = null,
                i = 0;
            
            //First, exclude the type itself
            var itself = _.findWhere(models, { typeId: typeId });

            if(itself)
                excludeModels.push(itself.value);

            //Get items where this type exists
            if (items.where({ typeId: typeId }))
                var existing = items.where({ typeId: typeId });

            //Exclude parents where this type exists
            for (i = 0; i < existing.length; i++) {
                //Exclude direct parent
                currentitem = existing[i];
                //excludeModels.push(currentParent.attributes.parent);
                while (currentitem = items.where({ id: currentitem.attributes.parent })[0]) {
                    //Exclude parent from current parent
                    var excludeId = _.findWhere(models, { typeId: currentitem.attributes.typeId });
                    if (excludeId)
                        excludeModels.push(excludeId.value);
                }
            }

            //Exclude all parents
            for (i = 0; i < parents.length; i++) {
                //Exclude direct parent
                currentParent = parents[i];
                //excludeModels.push(currentParent.attributes.parent);
                while (currentParent = items.where({ id: currentParent.attributes.parent })[0]) {
                    //Exclude parent from current parent
                    var excludeId = _.findWhere(models, { typeId: currentParent.attributes.typeId });
                    if(excludeId)
                      excludeModels.push(excludeId.value);
                }
            }


            //Return valid child types
            return _.reject(this.model.get('models'), function (obj) { return _.indexOf(excludeModels, obj.value) != -1; });
        },
        //filterTypes: function (typeId) {
        //    //The param typeId indicates the type to be exclude
        //    //(including his direct childrens and all of his parents)

        //    var items = this.items,
        //        excludeTypes = [],
        //        childs = [],
        //        parents = [],
        //        currentParent = null,
        //        i = 0;

        //    //First, exclude the type itself
        //    excludeTypes.push(typeId);

        //    //Exclude the direct childrens
        //    if (items.where({ parentTypeId: typeId }))
        //        childs = items.where({ parentTypeId: typeId });

        //    for (i = 0; i < childs.length; i++)
        //        excludeTypes.push(childs[i].attributes.typeId);

        //    //Get direct parents
        //    if (items.where({ typeId: typeId }))
        //        parents = items.where({ typeId: typeId });

        //    //Exclude all parents
        //    for (i = 0; i < parents.length; i++) {
        //        //Exclude direct parent
        //        currentParent = parents[i];
        //        excludeTypes.push(currentParent.attributes.typeId);
        //        while (currentParent = items.where({ id: currentParent.attributes.parent })[0]) {
        //            //Exclude parent from current parent
        //            excludeTypes.push(currentParent.attributes.typeId);
        //        }
        //    }

        //    //Return valid child types
        //    return _.reject(this.model.get('types'), function (obj) { return _.indexOf(excludeTypes, obj.value) != -1; });
        //},
        getDefaultName: function (tree, props, success, error) {
            var defaultName = "";

            var that = this;
            var QP = new QueryParameters();

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.GetEquipmentTypeNewDefaultName", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;

                        if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
                            var failureCode = "UNKNOWN";
                            failureCode = (data[0].Code) ? data[0].Code : failureCode;

                            if (error != null && _.isFunction(error))
                                error.call(this, that, failureCode);
                        } else {
                            defaultName = data[0].DefaultName;

                            if (success != null && _.isFunction(success))
                                success.call(this, defaultName);
                        }
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        addItem: function (item) {
            this.stopAutoRefresh();

            var that = this;
            

            var selected = this.tree.get_selected();
            var sel = null;
            var selected_node = null;

            if (!selected.length) {
                selected[0] = TREE_NODE_ROOT_ID;
            }

            sel = selected[0];
            selected_node = this.tree.get_node(sel);

    
            //this.tree.create_node(sel, {
            //    "id": item.Id.toString(),
            //    "typeId": item.TypeId.toString(),
            //    "text": item.TypeName,
            //    "parentId": (item.ParentId) ? item.ParentId.toString() : TREE_NODE_ROOT_ID,
            //    "icon": (item.IconData) ? item.IconData : 'fa fa-minus',
            //    "deleted": !item.Enabled,
            //    "type": "default",
            //    "a_attr": {
            //        style: "background: #f1f1f1; border: 2px dotted #c1c1c1; border-radius:5px; margin-bottom:5px; margin-top:-2px;padding-right: 10px; text-decoration:none;"
            //    }
            //},
            //"last", function (a, b, c) {
            //    a;
            //});

            //var node = this.tree.get_node(item.Id.toString(), true);

            //this.tree.get_node(item.Id.toString(), true).children('.jstree-anchor').focus();
            //this.tree.select_node(node);
            //var node = this.tree.get_node(this.tree.get_selected()[0]);
            this.model.set('selected', item.Id);

            this.setTreeLoadingState(true);
            this._autoRefresh();
            this.model.fetchModels();
            
            if (this.subviews.newMachine.view)
                this.subviews.newMachine.view.close();
        },
        updateItem: function (item) {
            this.stopAutoRefresh();

            var that = this;


            var selected = this.tree.get_selected();
            var sel = null;
            var selected_node = null;

            if (!selected.length) {
                selected[0] = TREE_NODE_ROOT_ID;
            }

            sel = selected[0];
            selected_node = this.tree.get_node(sel);

            if (selected_node.text != item.Name) 
                this.tree.rename_node(selected_node, item.Name);

            if (selected_node.icon != item.IconData)
                this.tree.set_icon(selected_node, item.IconData);


            if (this.subviews.machineConfiguration.view)
                this.subviews.machineConfiguration.view.close();
        },
        addExistingItem: function () {
            try {
                var that = this,
                    attrs = this.tree._model.data[this.tree.get_selected()].original,
                    modelsFiltered = this.filterModels(attrs.id, attrs.typeId);

                this.currentModal = new Screen.Views.AddExistingModal({
                    model: new Screen.Models.AddExistingModal({
                        parent: attrs.id,
                        ihId: attrs.ihId,
                        parentTypeId: attrs.typeId,
                        models: modelsFiltered,
                    }),
                    i18n: this.i18n[this.template],
                    template: this.templates.addExistingModal,
                });

                //var fn_modal_shown_hidden = function () {
                //    try {
                //        //Enable button in both events, shown and hidden, just to prevent issues if one of them fails
                //        //or it is not executed for some reason.
                //        clickedBtn.attr("disabled", false);
                //    }
                //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                //};

                //this.listenToOnce(this.currentModal, 'shown', fn_modal_shown_hidden)
                //    .listenToOnce(this.currentModal, 'hidden', fn_modal_shown_hidden)
                this.listenTo(this.currentModal, 'saving', function (modal, data, callbacks) {
                        try {
                            that.items.AssignExistingModel(
                                [
                                    { name: 'ihId', type: 'INT', value: data.ihId },
                                    { name: "Id", type: "INT", value: data.id },
                                    { name: "ParentId", type: "INT", value: data.parent },
                                    { name: "Name", type: "VARCHAR", value: data.name }
                                ],
                                function (coll, id) {
                                    try {
                                        callbacks.success(id);
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                },
                                function (coll, msg) {
                                    try {
                                        callbacks.error(msg);
                                    }
                                    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                }
                            );
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    })
                    .listenToOnce(this.currentModal, 'finish', function (modal, output) {
                        try {
                            if (output.result == 'SUCCESS') {
                                var params = that.model.toJSON();

                                that.currentModal = null;

                                that.model.set('selected', output.id);

                                that._refresh(_.extend(
                                    {},
                                    params,
                                    {
                                        refresh: true,
                                        //params: _.extend(
                                        //    {},
                                        //    params,
                                        //    {
                                        //        start: new moment(params.start, "MM/DD/YYYY").format("YYYY-MM-DD"),
                                        //        end: new moment(params.end, "MM/DD/YYYY").format("YYYY-MM-DD"),
                                        //        stand: (params.standId != '0')
                                        //                   ? params.standId
                                        //                   : null
                                        //    }
                                        //),
                                    }
                                ));
                                
                                that.setTreeLoadingState(true);
                                that.model.fetchModels();
                                //var node = _.where(that.tree.get_json(null, { flat: true }), { id: output.id.toString() });
                                
                                //that.tree.deselect_all();
                                //that.tree.select_node(node);
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    });;

                this.currentModal.show();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        addArea: function () {
            var tree = this.tree;
            var newArea = tree.create_node(null, { type: "area" });
            //if (newArea) tree.edit(newArea); 
        },
        addLine: function () {
            //var tree = this.tree;
            //var newLine = tree.create_node(null, { type: "line" });
            ////if (newLine) tree.edit(newLine); 

            var tree = this.tree;
            var selected = tree.get_selected();
            var sel = null;
            var selected_node = null;

            if (selected.length) {
                var sel = selected[0];
                var selected_node = tree.get_node(sel);
            }

            if ((!selected_node) || (selected_node.type == "area") || (selected_node.type == "root")) {
                sel = tree.create_node(sel, { "type": "line" }, "last", function (a, b, c) {
                    a;
                });
                //if (sel) {
                //    tree.edit(sel);
                //}
            }
        },
        addMachine: function (e, data) {
            var tree = this.tree;
            var selected = tree.get_selected();

            if (!selected.length) { return false; }
            var sel = selected[0];
            var selected_node = tree.get_node(sel);

            if (selected_node.type == "line") {
                sel = tree.create_node(sel, { "type": "machine" }, "last", function (a, b, c) {
                    a;
                });
                //if (sel) {
                //    tree.edit(sel);
                //}
            }
        },

        checkAddLineMachineButtons: function (e, data) {
            var btnAddArea = this.$el.find(".btn-add-area"),
                btnAddLine = this.$el.find(".btn-add-line"),
                btnAddMachine = this.$el.find(".btn-add-machine");

            switch (data.node.type.toUpperCase()) {
                case "AREA":
                    btnAddArea.prop("disabled", true);
                    btnAddLine.prop("disabled", false);
                    btnAddMachine.prop("disabled", true);
                    break;
                case "LINE":
                    btnAddArea.prop("disabled", true);
                    btnAddLine.prop("disabled", true);
                    btnAddMachine.prop("disabled", false);
                    break;
                case "MACHINE":
                    btnAddArea.prop("disabled", true);
                    btnAddLine.prop("disabled", true);
                    btnAddMachine.prop("disabled", true);
                    break;
                default:
                    btnAddArea.prop("disabled", false);
                    btnAddLine.prop("disabled", false);
                    btnAddMachine.prop("disabled", true);
                    break;
            }

            //if (data.node.type == "line") {
            //    btnAddMachine.prop("disabled", false);
            //} else {
            //    btnAddMachine.prop("disabled", true);
            //}
        },
        customTreeCtxMenu: function (node) {
            var that = this;

            //Return empty if node is disabled (disabled here means the jstree disabled, not the production item disabled status).
            if (node.state.disabled == true)
                return [];

            // The default set of all items
            var items = {
                createItem: {
                    label: app.translate([this, that], 'add_new_model'),
                    action: function (obj) {
                        that.btnAddItem_click();
                        //that.addItem(true);
                    },
                    //this.addItem(),
                },
                addExistingItem: {
                    label: app.translate([this, that], 'assign_model'),
                    action: function (obj) {
                        that.addExistingItem();
                    },
                    //this.addItem(),
                },
                //renameItem: {
                //    label: "Rename",
                //    action: function (obj) {
                //        that.renameNode(node);
                //    },
                //},
                unassignItem: {
                    label: app.translate([this, that], 'unassign_model'),
                    action: function (obj) {
                        that.currentModal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([that, app], "unassign_template_confirm_title"),
                            message: app.translate([that, app], "unassign_template_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        that.listenToOnce(that.currentModal, "continue", function (modal) {
                            try {
                                that.unassignNode(node);
                                that.currentModal = null;
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        that.currentModal.show();

                        //that.unassignNode(node);
                    },
                },
                deleteItem: {
                    label: app.translate([this, that], 'delete'),
                    action: function (obj) {
                        that.currentModal = new Modal.Views.Main({
                            focusOk: false,
                            focusSelector: '#btn-cancel',
                            title: app.translate([that, app], "delete_type_confirm_title"),
                            message: app.translate([that, app], "delete_type_message"),
                            buttons_type: "CONTINUE-CANCEL",
                        });

                        that.listenToOnce(that.currentModal, "continue", function (modal) {
                            try {
                                that.deleteNode(node);
                                that.currentModal = null;
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        that.currentModal.show();

                        //that.deleteNode(node);
                    },
                },
                
                enableItem: {
                    label: "Enable",
                    action: function (obj) {
                        that.enableNode(node);
                    }
                }
            };

            switch (node.type.toUpperCase()) {
                //case "AREA":
                //    break;
                //case "LINE":
                //    break;
                case "MACHINE":
                    delete items["createAreaItem"];
                    break;
                case "ROOT":
                    delete items["addExistingItem"];
                    delete items["deleteItem"];
                    delete items["enableItem"];
                    delete items["renameItem"];
                    break;
            }

            //if (node.type != "line") {
            //    delete items["createItem"]; 
            //}

            if (node && node.data && !node.data.enabled) {
                delete items["createItem"];
                delete items["addExistingItem"];
                delete items["unassignItem"];
                delete items["deleteItem"];
            } else {
                delete items["enableItem"];
            }

            if (node && node.parent == TREE_NODE_ROOT_ID)
                delete items["unassignItem"];

            if (node && node.parent == '#') {
                delete items["addExistingItem"];
                delete items["renameItem"];
                delete items["unassignItem"];
                delete items["deleteItem"];
                delete items["enableItem"];
            }

            return items;
        },
        setTreeLoadingState: function (isLoading) {
            var tree = this.tree;

            var rootNode = tree.get_node(TREE_NODE_ROOT_ID);

            if (isLoading == true) {
                tree.set_type(rootNode, 'loading');

                $('.tree li').each(function () {
                    tree.disable_node(this.id);
                });
            }
            else {
                tree.set_type(rootNode, 'root');

                $('.tree li').each(function () {
                    tree.enable_node(this.id);
                });
            }
        },
        itemsChanged: function (a, b, c) {
            var fromFetch = (
                            (c && c.from && c.from == "fetch") ||
                            (!c && b && b.from == "fetch")
                            ) ? true : false;

            if (fromFetch) {
                var nodeId = (a) ? a.attributes.id : null;

                this.debounced_refreshTree(nodeId);

                
            }
        },
        debounced_refreshTree: _.debounce(function (nodeId) {
            var that = this;
            var types = [];

            //Force to set loading state to false. Maybe it is not necessary all the times
            //but some transactions do not set loading state to false because they call for a refresh.
            this.setTreeLoadingState(false);

            //Configure types for the tree
            //for (var i = 0; i < that.model.get('types').length; i++) {
            //    if (this.model.get('types')[i].iconId)
            //        this.tree.settings.types[this.model.get('types')[i].label.toLowerCase()] =
            //            {
            //                icon: 'data:image/png;base64,' + this.model.get('types')[i].iconData,
            //                //_.findWhere(
            //                //    that.model.get('icons'),
            //                //    { id: that.model.get('types')[i].iconId }
            //                //).data
            //            };
            //}

            for (var i = 0; i < this.items.models.length; i++) {
                if (_.indexOf(types, this.items.models[i].attributes.text.toLowerCase()) == -1 && this.items.models[i].attributes.iconId) {
                    this.tree.settings.types[this.items.models[i].attributes.text.toLowerCase()] =
                        {
                            icon: 'data:image/png;base64,' + this.items.models[i].attributes.iconData,
                            //_.findWhere(
                            //    that.model.get('icons'),
                            //    { id: that.model.get('types')[i].iconId }
                            //).data
                        };
                    types.push(that.items.models[i].attributes.text.toLowerCase());
                }
            }

            this.tree.refresh(true);

            if (nodeId) {
                var node = this.tree.get_node({id: nodeId.toString() });

                if (node != false)
                    this.select_node(node);
            }
        }, 500),

        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.state == app.view_states.loading
                || this.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.state = app.view_states.shown;
                container.append(el);

                this.onappend(this);
            }

            if (this.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        _autoRefresh: function (opt) {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refresh(opt);

            if (this.autoRefresh.enabled == true) {
                this.autoRefresh.toid = setTimeout(_.bind(this._autoRefresh, this), 30 * 1000);
            }
        },
        bindViewScopedEvents: function () {
        },
        close: function () {
            this.state = app.view_states.closed;

            //If currentModal exists, hide it and erase it.
            if (this.currentModal) {
                this.currentModal.hide();
                this.currentModal = null;
            }

            this.stopAutoRefresh();
            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.close();
            });
        },
        hide: function () {
            this.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        preRender: function () {
            app.models.subnavbar.set("dateControl", false);
            app.models.subnavbar.set("notificationBar", false);
            app.models.subnavbar.set("dateTimeScopeControl", false);
            app.models.subnavbar.set("subnavbar", true);
            app.models.subnavbar.set("sections", "12");
        },
        reRender: function () {
        },
        show: function () {
            this.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        },
        startAutoRefresh: function () {
            try {
                if (this.autoRefresh.enabled !== true) {
                    var that = this;

                    if (this.autoRefresh.toid != null) {
                        clearTimeout(this.autoRefresh.toid);
                        this.autoRefresh.toid = null;
                    }

                    this.autoRefresh.enabled = true;

                    //use a timeout to execute the first refresh to return the handle to the start function caller.
                    //So when the caller finish it will do the first refresh.
                    this.autoRefresh.toid = setTimeout(
                        _.bind(this._refresh, this),
                        1
                    );
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        stopAutoRefresh: function () {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }
            this.autoRefresh.enabled = false;
        },
        unbindViewScopedEvents: function () {
        },
    });

    Screen.Models.Item = Backbone.Model.extend({
        initialize: function () {
        }
        , defaults: {
            id: null,
            ihId: null,
            parent: null,
            templateId: null,
            typeId: null,
            parentTypeId: null,
            type: null,
            text: null,
            //order: null,
            iconId: null,
            deleted: false,
            enabled: true,
        }
    });

    Screen.Models.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,
        initialize: function () {
            //_.bindAll(this);

            this.bindEvents();
        },
        fetch: function (opt) {
            var options = {
                method: "set",
                async: true,
                callback: null,
                codesText: "",
            };

            options = _.extend(options, (opt) ? opt : {});

            var that = this,
                QP = new Core.Database.QueryParameters();

            if (options.params) {
                if (options.params.ihId) QP.Add('ihId', 'INT', options.params.ihId);
            }
            var items = [];
            items.push({
                id: TREE_NODE_ROOT_ID,
                parent: '#',
                type: "root",
                text: options.codesText,
                state: {
                    opened: true,
                },
                icon: 'fa fa-cogs icon-style',
                a_attr: { style: "background : #c1c1c1; border: 2px solid #c1c1c1; border-radius:5px;margin-bottom:3px; line-height: 28px;height: 28px;padding-right: 10px; text-decoration:none;" }
            });

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.GetEquipmentTypeTemplates", QP, {
                onSuccess: function (data) {
                    if (Core.Object.Eval(data, "Table")) {
                        var models = data.Table;
                        //var templates = data.Table1
                        //var icons = data.Table1;

                        for (var i = 0; i < models.length; i++) {
                            var itemData = models[i];
                            var equipmentModel = {
                                id: itemData.Id,
                                parent: ((itemData.ParentId != null) && (itemData.ParentId != -1))
                                        ? itemData.ParentId
                                            : TREE_NODE_ROOT_ID,
                                //templateId: itemData.Id,
                                typeId: itemData.TypeId,
                                //parentTypeId: itemData.ParentId,
                                text: (itemData.Name) ? itemData.Name + ' - ' + itemData.TypeName : itemData.TypeName,
                                order: itemData.Order - 1,
                                //order: 0,
                                //deleted: !itemData.Enabled,
                                //enabled: itemData.Enabled,
                                hasChildren: !itemData.ChildHierarchyId,
                                //state: {
                                //    opened: (itemData.ParentId != null && itemData.ParentId != -1) ? false : true,
                                //},
                                data: {
                                    enabled: itemData.Enabled,
                                },
                                //name: itemData.Name.toLowerCase(),
                                //iconId: itemData.IconId,
                                icon: (itemData.IconData) ? itemData.IconData : 'fa fa-minus',
                                a_attr: {
                                    style: "background: #f1f1f1; border: 2px dotted #c1c1c1; border-radius:5px; margin-bottom:3px; line-height: 28px;height: 28px;padding-right: 10px; text-decoration:none;" }
                            };

                            items.push(equipmentModel);
                        }

                        //for (var i = 0; i < templates.length; i++) {
                        //    var itemData = templates[i];
                        //    var equipmentTypeTemplate = {
                        //        id: itemData.Id,
                        //        parent: ((itemData.ParentId != null) && (itemData.ParentId != -1))
                        //                    ? itemData.ParentId
                        //                    : TREE_NODE_ROOT_ID,
                        //        //type: itemData.TypeName.toLowerCase(),
                        //        //type: 'unknown',
                        //        text: itemData.Name,
                        //        //order: itemData.Order - 1,
                        //        //order: 0,
                        //        deleted: !itemData.Enabled,
                        //        enabled: itemData.Enabled,
                        //        data: {
                        //            enabled: itemData.Enabled,
                        //        }
                        //    };

                        //    items.push(equipmentTypeTemplate);
                        //}

                    }

                    that[options.method](items, { from: "fetch" });

                    if (options.callback != null && _.isFunction(options.callback))
                        options.callback.call(this, that);
                },
                Async: options.async,
                Secured: true,
            }, app.ConnectionStrings.app);

            return this;
        },
        fetchPreview: function (options) {
            var that = this;

            var QP = new QueryParameters();
            if (options && options.params) {
                if (options.params.id) QP.Add("Id", "INT", options.params.id);
                if (options.params.ihId) QP.Add("ihId", "INT", options.params.ihId);
            }

            //QP.Add("includeIcons", "BIT", 1);

            var items = [];
            items.push({
                id: TREE_NODE_ROOT_ID,
                parent: '#',
                type: "root",
                text: options.codesText,
                state: {
                    opened: true,
                },
                icon: 'fa fa-cogs icon-style',
                a_attr: { style: "background : #c1c1c1; border: 2px solid #c1c1c1; border-radius:5px;  margin-bottom:3px; line-height: 28px;height: 28px;padding-right: 10px; text-decoration:none;" }
            });

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.GetEquipmentTypeTemplatePreview", QP, {
                onSuccess: function (data) {
                    if (Core.Object.Eval(data, "Table")) {
                        var models = data.Table;
                        //var templates = data.Table1
                        //var icons = data.Table1;

                        for (var i = 0; i < models.length; i++) {
                            var itemData = models[i];
                            var equipmentModel = {
                                id: itemData.Id,
                                parent: ((itemData.ParentId != null) && (itemData.ParentId != -1))
                                    ? itemData.ParentId
                                    : TREE_NODE_ROOT_ID,
                                typeId: itemData.TypeId,
                                text: itemData.TypeName,
                                state: {
                                    opened: true,
                                },
                                order: itemData.Order - 1,
                                //order: 0,
                                data: {
                                    enabled: itemData.Enabled,
                                },
                                icon: (itemData.IconData) ? itemData.IconData : 'fa fa-minus',
                                a_attr: { style: "background: #f1f1f1; border: 2px dotted #c1c1c1; border-radius:5px;  margin-bottom:3px; line-height: 28px;height: 28px;padding-right: 10px; text-decoration:none;" }
                            };

                            items.push(equipmentModel);
                        }

                    }

                    that['set'](items, { from: "fetch" });

                    if (options.callback != null && _.isFunction(options.callback))
                        options.callback.call(this, that);
                },
                Secured: true
            }, app.ConnectionStrings.app);

            return this;
        },
        bindEvents: function () {
            //this.listenTo(this, "add", this.syncToDB);
            //this.listenTo(this, "remove", this.syncToDB);
            //this.listenTo(this, "change", this.syncChangeToDB);
        },
        syncChangeToDB: function (a, b, c) {
            var from = (c && c.from) ? c.from : "unknown";
            if (from != "fetch") {
                if (a && a.changed && a.changed["text"]) {
                    this.upsertType(a.get("typeId"), null, [
                        { name: "Name", type: "VARCHAR", value: a.get("text") }
                    ]);
                }
            }
        },

        //upsertTemplate: function (id, currentTreeParent, currentTreeNodeNum, props, success, error) {
        //    var that = this;
        //    var QP = new QueryParameters();
        //    QP.Add("Id", "INT", id);
        //    //QP.Add("IncludeHierarchy", "BIT", 1);

        //    for (var q in props) {
        //        QP.Add(props[q].name, props[q].type, props[q].value);
        //    }

        //    Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.UpsertEquipmentTypeTemplate", QP, {
        //        onSuccess: function (data) {
        //            if (data && data.Table) {
        //                var data = data.Table;
        //                //var icons = data.Table1;
        //                //var ids = [];

        //                if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
        //                    var failureCode = "UNKNOWN";
        //                    failureCode = (data[0].Code) ? data[0].Code : failureCode;

        //                    if (error != null && _.isFunction(error))
        //                        error.call(this, that, failureCode);
        //                } else {
        //                    //ids = _.pluck(data, 'Id');

        //                    //if (success != null && _.isFunction(success))
        //                    //    success.call(this, that, ids);

        //                    var itemData = data[0];

        //                    var item = {
        //                        //id: (typeof currentTreeNodeNum === "string") ? parseInt(currentTreeNodeNum, 10) : currentTreeNodeNum + 1,
        //                        id: itemData.Id,
        //                        parentId: ((itemData.ParentId != null) && (itemData.ParentId != -1))
        //                                    ? itemData.ParentId
        //                                    : TREE_NODE_ROOT_ID,
        //                        //parent: ((itemData.ParentId != null) && (itemData.ParentId != -1))
        //                        //            ? itemData.ParentId
        //                        //            : TREE_NODE_ROOT_ID,
        //                        typeId: itemData.TypeId,
        //                        //type: itemData.Type,//.toLowerCase(),
        //                        text: itemData.TypeName,
        //                        name: itemData.Name,
        //                        icon: (itemData.IconData) ? itemData.IconData : 'fa fa-minus',
        //                        //order: itemData.Order - 1,
        //                        deleted: !itemData.Enabled,
        //                        enabled: itemData.Enabled,
        //                        data: {
        //                            enabled: itemData.Enabled,
        //                        }
        //                    };

        //                    if (success != null && _.isFunction(success))
        //                        success.call(this, that, item);
        //                }
        //            } else {
        //                error.call(this, that);
        //            }
        //        },
        //        Async: true,
        //        Secured: true,
        //    }, app.ConnectionStrings.app);
        //},
        AssignExistingModel: function (props, success, error) {
            var that = this;
            var QP = new QueryParameters();
            //QP.Add("IncludeHierarchy", "BIT", 1);

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.AssignExistingModel", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        //var ids = [];

                        if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
                            var failureCode = "UNKNOWN";
                            failureCode = (data[0].Code) ? data[0].Code : failureCode;

                            if (error != null && _.isFunction(error))
                                error.call(this, that, failureCode);
                        } else {
                            var id = data[0].NewId;
                                

                            if (success != null && _.isFunction(success))
                                success.call(this, that, id);
                        }
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        deleteItem: function (id, props, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.RemoveEquipmentModel", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = [];

                        if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
                            var failureCode = "UNKNOWN";
                            failureCode = (data[0].Code) ? data[0].Code : failureCode;

                            if (error != null && _.isFunction(error))
                                error.call(this, that, failureCode);
                        } else {
                            ids = _.pluck(data, 'Id');

                            if (success != null && _.isFunction(success))
                                success.call(this, that, ids);
                        }
                    } else {
                        error.call(this, that, data.Message);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        unassignItem: function (id, props, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.UnassignEquipmentModel", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = [];

                        if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
                            var failureCode = "UNKNOWN";
                            failureCode = (data[0].Code) ? data[0].Code : failureCode;

                            if (error != null && _.isFunction(error))
                                error.call(this, that, failureCode);
                        } else {
                            ids = _.pluck(data, 'Id');

                            if (success != null && _.isFunction(success))
                                success.call(this, that, ids);
                        }
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        enableItem: function (id, props, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);
            QP.Add("@Enabled", "INT", 1);

            for (var q in props) {
                QP.Add(props[q].name, props[q].type, props[q].value);
            }

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.SetEquipmentTypeEnabled", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = [];

                        if (data && data.length > 0 && data[0].Status && data[0].Status == "FAILURE") {
                            var failureCode = "UNKNOWN";
                            failureCode = (data[0].Code) ? data[0].Code : failureCode;

                            if (error != null && _.isFunction(error))
                                error.call(this, that, failureCode);
                        } else {
                            ids = _.pluck(data, 'Id');

                            if (success != null && _.isFunction(success))
                                success.call(this, that, ids);
                        }
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        reorderItem: function (id, parent, order, success, error) {
            var that = this;
            var QP = new QueryParameters();

            QP.Add("@Id", "INT", id);
            QP.Add("@ParentId", "INT", parent);
            QP.Add("@Order", "INT", order);

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.MoveEquipment", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        var data = data.Table;
                        var ids = _.pluck(data, 'Id');

                        if (success != null && _.isFunction(success))
                            success.call(this, that, ids);
                    } else {
                        error.call(this, that);
                    }
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        //addNode: function (text, currentTreeParent, currentTreeNodeNum, parent, type, position, success, error) {
        //    var that = this;
        //    if (currentTreeParent == TREE_NODE_ROOT_ID) {
        //        this.upsertType(null, currentTreeNodeNum, [
        //            { name: "Name", type: "VARCHAR", value: text },
        //        ], function (ref, item) {
        //            that.add(item);

        //            if (success && _.isFunction(success))
        //                success.call(this, that, item);
        //        },
        //        function (ref, code) {
        //            if (error && _.isFunction(error))
        //                error.call(this, that, code);

        //            that.startAutoRefresh();
        //        });
        //    } else {
        //        this.upsertTemplate(null, currentTreeParent, currentTreeNodeNum, [
        //            { name: "ParentId", type: "INT", value: parent },
        //            //{ name: "TypeId", type: "INT", value: type },
        //            { name: "Name", type: "VARCHAR", value: text },
        //        ], function (ref, item) {
                   

        //            that.add(item);

        //            if (success && _.isFunction(success))
        //                success.call(this, that, item);
        //        },
        //        function (ref, code) {
        //            if (error && _.isFunction(error))
        //                error.call(this, that, code);

        //            that.startAutoRefresh();
        //        });
        //    }
        //},
        //renameNode: function (id, typeId, text, success, error) {
        //    var that = this;
        //    var model = this.get(id);
        //    if (model) {
        //        this.upsertType(id, typeId, [
        //            { name: "Name", type: "VARCHAR", value: text },
        //            //{ name: "ParentId", type: "INT", value: parentTypeId }
        //        ], function (ref, item) {
        //            if (item.id == id) {
        //                model.set("text", item.text);

        //                if (success && _.isFunction(success))
        //                    success.call(this, that, item);
        //            } else {
        //                if (error && _.isFunction(error))
        //                    error.call(this, that);
        //            }
        //        }, function (ref) {
        //            if (error && _.isFunction(error))
        //                error.call(this, that);
        //        });
        //    } else {
        //        if (error && _.isFunction(error))
        //            error.call(this, that);
        //    }
        //},
        deleteNode: function (id, parentId, ihId, success, error) {
            var that = this;
            var model = this.get(id);
            if (model) {
                id = model.get('id'); 

                this.deleteItem(
                    id,
                    [
                        { name: 'ihId', type: 'INT', value: ihId },
                        { name: "parentId", type: "INT", value: model.get('parent') }
                    ]
                    , function (ref, ids) {
                        //Comment out remove from coll because this will be done by a refresh later.
                        ////removing from collection; 
                        //that.remove(model);

                        if (success && _.isFunction(success))
                            success.call(this, that, ids);
                    },
                    function (ref, code) {
                        if (error && _.isFunction(error))
                            error.call(this, that, code);
                    }
                );
            }
        },
        unassignNode: function (id, ihId, success, error) {
            var that = this;
            var model = this.get(id);
            if (model) {
                this.unassignItem(
                    model.get('id'),
                    [
                        { name: "ihId", type: "INT", value: ihId},
                        { name: "parentId", type: "INT", value: model.get('parent')},
                    ]
                    , function (ref, ids) {
                        //Comment out remove from coll because this will be done by a refresh later.
                        ////removing from collection; 
                        //that.remove(model);

                        if (success && _.isFunction(success))
                            success.call(this, that, ids);
                    },
                    function (ref, code) {
                        if (error && _.isFunction(error))
                            error.call(this, that, code);
                    }
                );
            }
        },
        enableNode: function (id, success, error) {
            var that = this;
            var model = this.get(id);
            if (model) {
                this.enableItem(
                    model.get('typeId'),
                    [
                    ]
                    , function (ref, ids) {
                        if (success && _.isFunction(success))
                            success.call(this, that, ids);
                    },
                    function (ref, code) {
                        if (error && _.isFunction(error))
                            error.call(this, that, code);
                    }
                );
            }
        },
        reorderNode: function (id, parent, order, success, error) {
            var that = this;
            var model = this.get(id);
            if (model) {
                this.reorderItem(id, parent, order, function (ref, ids) {
                    if (_.indexOf(ids, parseInt(id)) != -1) {
                        //model.set({
                        //    parent: (parent == "#") ? TREE_NODE_ROOT_ID : parseInt(parent),
                        //    order: order,
                        //});

                        if (success && _.isFunction(success))
                            success.call(this, that, ids);
                    } else {
                        if (error && _.isFunction(error))
                            error.call(this, that);
                    }
                }, function (ref) {
                    if (error && _.isFunction(error))
                        error.call(this, that);
                });
            } else {
                if (error && _.isFunction(error))
                    error.call(this, that);
            }
        }
    });



    Screen.Models.MachineConfiguration = Backbone.Epoxy.Model.extend({
         defaults: {
            id: null,
            ihId: null,
            typeId: null,
            name: null,
            type: null,
            typeName: null,
            statusCode: null,
            deleted: null,
            iconId: null,
            parentId: null,


            newMachineName: null,
            newMachineIcon: null,
            hierarchyList: '/',

                ////behind the scenes
            icons: [],
            //statusCodes: [],
            //statusCodesBinding: [],
            types: [],
            typesBinding: [],
            }
        , computeds: {
            hasIcons: {
                deps: ['icons'],
                get: function (icons) {
                    return icons.length != 0;
                },
            },
        }
        , initialize: function () {
            _.extend(
                this, 
                { 
                    loaded: false,
                }, 
                this.options
            );
        }
        , fetch: function (options) {
            var that = this;

            this.fetchTemplate(options);
        }
       
        , fetchTemplate: function (options) {
            var that = this;

            var QP = new QueryParameters();
            if (options.data) {
                if (options.data.id) {
                    QP.Add("Id", "INT", options.data.id);
                    QP.Add("ihId", "INT", options.data.ihId);

                    if (options.data.id == -1)
                        this.loaded = true;
                }

                
            }

            //QP.Add("includeIcons", "BIT", 1);

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.GetEquipmentTypeTemplates", QP, {
                onSuccess: function (data) {
                    if (Core.Object.Eval(data, "Table.0")) {
                        var machineData = data.Table[0];

                        var machineConfiguration = _.extend({}, that.attributes, {
                            id: machineData.Id,
                            typeId: machineData.TypeId,
                            typeName: machineData.TypeName,
                            iconId: machineData.IconId,
                            parentId: ((machineData.ParentId != null) && (machineData.ParentId != -1))
                                        ? machineData.ParentId
                                        : TREE_NODE_ROOT_ID,
                            name: machineData.Name,
                            quantity: machineData.Quantity,
                            deleted: !machineData.Enabled,
                            hierarchyList: (machineData.HierarchyList) ? machineData.HierarchyList : '/' 
                        });
                        
                        //if (data.Table1) {
                        //    var iconsData = data.Table1;

                        //    var icons = _.extend({}, {
                        //        id: iconsData.Id,
                        //        name: iconsData.Name,
                        //        data: iconsData.Data,
                        //    });

                        //    that.set('icons', icons);
                        //}

                        that.loaded = true;

                        that.set(machineConfiguration, { from: "fetch" });
                    }
                },
                Secured: true
            }, app.ConnectionStrings.app);

        }
        , fetchDetails: function (options) {
            var that = this;

            var QP = new QueryParameters();
            if (options.data) {
                if (options.data.id) {
                    QP.Add("Id", "INT", options.data.id);
                    QP.Add("ihId", "INT", options.data.ihId);

                    if (options.data.id == -1)
                        this.loaded = true;
                }


            }

            //QP.Add("includeIcons", "BIT", 1);

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.GetEquipmentModelDetails", QP, {
                onSuccess: function (data) {
                    if (Core.Object.Eval(data, "Table.0")) {
                        var machineData = data.Table[0];

                        var machineConfiguration = _.extend({}, that.attributes, {
                            id: machineData.Id,
                            typeName: machineData.TypeName,
                            iconId: machineData.IconId,
                            typeId: machineData.TypeId,
                            parentId: ((machineData.ParentId != null) && (machineData.ParentId != -1))
                                ? machineData.ParentId
                                : TREE_NODE_ROOT_ID,
                            name: machineData.Name,
                            quantity: machineData.Quantity,
                            deleted: !machineData.Enabled,
                            hierarchyList: (machineData.HierarchyList) ? machineData.HierarchyList : '/'
                        });

                        //if (data.Table1) {
                        //    var iconsData = data.Table1;

                        //    var icons = _.extend({}, {
                        //        id: iconsData.Id,
                        //        name: iconsData.Name,
                        //        data: iconsData.Data,
                        //    });

                        //    that.set('icons', icons);
                        //}

                        that.loaded = true;

                        that.set(machineConfiguration, { from: "fetch" });
                    }
                },
                Secured: true
            }, app.ConnectionStrings.app);
        }
        , save: function (opt) {
            var that = this;
            var options = {
                 callback: function () { }
            };

            _.extend(options, opt);

            var QP = new QueryParameters();

            var params = [
                ["@Id", "INT", "id"],
                ['@ihId', 'INT', 'ihId'],
                ["@Name", "VARCHAR", "name"],
                ["@IconId", "VARCHAR", "iconId"],
                ["@ParentId", "VARCHAR", "parentId"],
                ["@TypeName", "VARCHAR", "typeName"],
                ["@TypeId", "INT", "typeId"],
            ];

            
            if (options.params ) {
                for (var i = 0, len = params.length; i < len; i++) {
                    var param = params[i];
                    QP.Add(param[0], param[1], options.params[param[2]]);
                }
            } else {

                this.set('name', null);
                this.set('typeName', this.get('newMachineName'));
                this.set('parentId', this.get('id'));
                this.set('iconId', this.get('newMachineIcon'));
                this.set('id', null);
                this.set('typeId', null);

                for (var i = 0, len = params.length; i < len; i++) {
                    var param = params[i];

                    QP.Add(param[0], param[1],this.get(param[2]));
                }
            }

            QP.Add("@ReturnData", "BIT", 1);

            Core.Json.CallProcedure(app.DatabaseNames.System + ".EQUIP.UpsertEquipmentTypeTemplate", QP, {
                onSuccess: function (data) {
                    try {
                        if (Core.Object.Eval(data, "Table.0")) {
                            if (options.callback != null && _.isFunction(options.callback))
                                options.callback.call(this, that, data.Table[0]);
                        } else {
                            if (Core.Object.Eval(data, "Message")) {
                                if (options.callback != null && _.isFunction(options.callback)) {
                                    options.callback.call(this, that, data);
                                }
                                
                                console.error(data.Message);
                            }
                            else
                                console.error("Server response not valid.");
                        }
                    }
                    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }

                    
                },
                Async: true,
                Secured: true
            }, app.ConnectionStrings.app);
        },
    });

    Screen.Views.NewMachine = Backbone.Epoxy.View.extend({
        template: "equipment-types"
        , id: "equipment-types"
        , title: "Equipment Types"
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , ignoreDropdownEvent: false
        , bindings: "data-bind"
        , currentModal: null
        , initialize: function () {
            _.extend(this, this.options);

            this.state = app.view_states.loading;
            this.onappend = (_.isFunction(this.onappend)) ? this.onappend : function () { };

            if (this.viewParams) {
            }

            this.autoRefresh = {
                enabled: true
                , toid: null
            };

            this.subviews = {};

            this.bindEvents();
            //_.bindAll(this);

            this.advancedOptions = false;
            var that = this;
            Mousetrap.bind('b a c k d o o r', function (e) {
                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    // internet explorer
                    e.returnValue = false;
                }

                that.advancedOptions = !that.advancedOptions;
                that.advopt(that.advancedOptions);
                return false;
            });
        },

        events: {
            "click .btn-save": "saveNewMachine",
            "click .btn-cancel": "cancelNewMachine",
            "submit #addMachineForm": "formPreventSubmit",
        },

        formPreventSubmit: function (e) {
            e.preventDefault();
        },

        render: function (container, viewParams) {
            var that = this;
            var thatContainer = this.container;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/modules/equipments/configuration/" + this.template + "/";

            if (this.model.loaded) {
                T.render.call(this, this.template, function (tmp) {
                    //getInternationalizationData
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        if (!that.i18n[that.template])
                            that.i18n[that.template] = i18nJED;


                        Core.Include({
                            Widgets: []
                            , Events: {
                                onLoad: function () {

                                    //loading the view and appeding it to the views's $el.
                                    that.$el.html(tmp(that.model.toJSON()));

                                    that.applyBindings();

                                    that.iconsSelect = new FormSelectBootstrap(that.$("#newMachineIcon").get(0), {
                                        Events: {
                                            onValueChange: [_.bind(that.iconsSelectChanged, that)]
                                        }
                                        , Templates: {
                                            //"parent": "<option value={{Id}} data-content='<span>{{Name}}</span><img data=\"data:image/gif;base64,{{Data}}\"></img>'></option>"
                                            "default": "<option value={{id}} data-content='<span>{{name}}</span>'></option>",
                                            "main": "<option value={{id}} data-content='<span class=\" {{data}} \" style=\" margin-right:2px; \">  {{name}}</span>' > </option>"
                                        }
                                    });

                                    that.ignoreDropdownEvent = true;

                                    that.iconsSelect.SetOptionsData(
                                        [{ "id": 0, "name": "Choose...", data: "", Template: "default" }].concat(that.model.get('icons'))
                                    );

                                    that.ignoreDropdownEvent = false;

                                    //that.iconsSelect.SetValue(that.model.get('iconId'), { silent: true, force: true });

                                    //appending view to the main container
                                    that.append(thatContainer, that.$el);

                                    //onViewComplete();
                                }
                            }
                            , ExternalWidgets: [
                                { Name: 'FormWidgetBase', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidgetBase/', JS: ['FormWidgetBase.js'] }
                                , { Name: 'FormWidget', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidget/', JS: ['FormWidget.js'], CSS: ['FormWidget.css'] }
                            ]
                        });

                    }, true, customPath);
                }, customPath, "add_machine");
            } else {
                setTimeout(function () {
                    if (!that.model.loaded) {
                        that.$el.html('<div style="text-align:center;margin-top:10px;"><i class="fa fa-5x fa-cog fa-spin"></i><br /></div>');
                        that.append(thatContainer, that.$el);
                    }
                }, 300);
            }
        }

        , iconsSelectChanged: function (e) {
            try {
                if (!this.ignoreDropdownEvent) {
                    var iconId = this.iconsSelect.GetValue();

                    this.model.set({
                        newMachineIcon: (parseInt(iconId, 10) == 0) ? null : iconId
                    });
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.state == app.view_states.loading
                || this.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.state = app.view_states.shown;
                container.append(el);

                this.onappend(this);
            }

            if (this.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }

        , reRender: function (viewParams) {
            try {
            } catch (Error) { }
        }

        , refresh: function (mm, force) {
            try {

                var iconId = this.iconsSelect.GetValue();

                if (mm && ((mm.changed["iconId"]) || force)) {
                    if (mm.get("iconId") != iconId) {
                        var optionID = mm.get("iconId");
                        this.iconsSelect.SetValue(optionID, { silent: true, force: true });
                    }
                }

            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , checkButtonsState: function (a, b, c) {
            var fromFetch = (b && b.from == "fetch") ? true : false;
            if (!fromFetch) {
                this.setSaveCancelButtons(true);
            }
        }

        , checkRender: function (a, b, c) {
            var fromFetch = (b && b.from == "fetch") ? true : false;
            if (fromFetch) {
                this.render();
            }
        }

        , setSaveCancelButtons: function (val) {
            var btnSave = this.$el.find(".btn-save");
            var btnCancel = this.$el.find(".btn-cancel");

            btnSave.prop("disabled", !val);
            btnCancel.prop("disabled", !val);
        }

        , saveNewMachine: function () {
            var that = this,
                attrs = this.model.toJSON();

            var name = (attrs.typeName) ? attrs.typeName : 'ROOT';
            this.currentModal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-cancel',
                title: app.translate([that, app], "add_new_machine_title"),
                message: ((app.translate([this, app], "add_new_machine_message")).replace("$1", name , "gi")) ,
                buttons_type: "CONTINUE-CANCEL",
            });

            that.listenToOnce(that.currentModal, "continue", function (modal) {
                try {
                    that.setSaveCancelButtons(false);
                    that.model.save({
                        callback: function (model, item) {
                            if (item.Message) {
                                app.views.topMessages.showMessage(app.translate(that.parent, item.Message));
                            } else {
                                app.views.topMessages.showMessage(app.translate(that.parent, "type_configuration_saved"));
                                that.trigger(
                                    'addNode',
                                    this,
                                    item,
                                );

                                that.model.fetchTemplate({
                                    data: {
                                        id: item.Id,
                                        ihId: that.model.get('ihId'),
                                    }
                                });
                            }
                        }
                    });

                    that.currentModal = null;
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            });

            that.currentModal.show();
        }

        , cancelNewMachine: function () {
            this.setSaveCancelButtons(false);
                this.model.fetchTemplate({
                    data: {
                        id: this.model.get("id"),
                        ihId: this.model.get('ihId'),
                    }
                });
        }

        , checkUnitProducedFlankOpt: function () {
            var chkbox = this.$el.find("#unitProducedChkboxContainer");
            var tagid = this.model.get("unitProducedTagId");
            chkbox.css("visibility", "hidden");

            var tag = _.findWhere(this.model.get("tags"), { Id: tagid });
            if (_.isObject(tag)) {
                if (tag.DataType == 'DIGITAL') {
                    chkbox.css("visibility", "visible");
                }
            }
        }

        , advopt: function (e) {
            this.$el.find(".counter-resets-at").css('display', e ? 'block' : 'none');
        }

        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.model, "change", this.checkRender);
            this.listenTo(this.model, "change", this.checkButtonsState);
        }

        , bindViewScopedEvents: function () {
        }

        , unbindViewScopedEvents: function () {
        }

        , close: function () {
            this.state = app.view_states.closed;

            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }

        , closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.close();
            });
        }

        , show: function () {
            this.state = app.view_states.shown;

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        }

        , showSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.show();
            });
        }

        , resetModel: function () {
            this.model.set(this.model.defaults);
        }

        , hide: function () {
            this.state = app.view_states.hidden;

            this.resetModel();
            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        }

        , hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.hide();
            });
        }

        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
            app.models.subnavbar.set("dateTimeScopeControl", false);
            app.models.subnavbar.set("sections", "4-4-4");
            app.models.subnavbar.set("subnavbar", true);
        }
    });

    Screen.Views.MachineConfiguration = Backbone.Epoxy.View.extend({
        template: "equipment-types"
        , id: "equipment-types"
        , title: "Equipment Types"
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        , isCacheable: false
        , ignoreDropdownEvent: false
        , bindings: "data-bind"
        , initialize: function () {
            _.extend(this, this.options);

            this.state = app.view_states.loading;
            this.onappend = (_.isFunction(this.onappend)) ? this.onappend : function () { };

            if (this.viewParams) {
            }

            this.autoRefresh = {
                    enabled: true
                    , toid: null
                };

            this.subviews = {};

            this.bindEvents();
            //_.bindAll(this);

            this.advancedOptions = false;
            var that = this;
            Mousetrap.bind('b a c k d o o r', function (e) {
                if (e.preventDefault) {
                    e.preventDefault();
                } else {
                    // internet explorer
                    e.returnValue = false;
                }

                that.advancedOptions = !that.advancedOptions;
                that.advopt(that.advancedOptions);
                return false;
            });
        },

        events: {
            "click .btn-save": "saveMachineConfiguration",
            "click .btn-cancel": "cancelMachineConfiguration",
            "submit #detailsForm": "formPreventSubmit",
        },

        formPreventSubmit: function (e) {
            e.preventDefault();
        },

        render: function (container, viewParams) {
            var that = this;
            var thatContainer = this.container;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/modules/equipments/configuration/" + this.template + "/";

            if (this.model.loaded) {
                T.render.call(this, this.template, function (tmp) {
                    //getInternationalizationData
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        if (!that.i18n[that.template])
                            that.i18n[that.template] = i18nJED;


                        Core.Include({
                            Widgets: []
                            , Events: {
                                onLoad: function () {

                                    //loading the view and appeding it to the views's $el.
                                    that.$el.html(tmp(that.model.toJSON()));

                                    that.applyBindings();

                                    that.iconsSelect = new FormSelectBootstrap(that.$("#iconsSelect").get(0), {
                                        Events: {
                                            onValueChange: [_.bind(that.iconsSelectChanged, that)]
                                        }
                                        , Templates: {
                                            //"parent": "<option value={{Id}} data-content='<span>{{Name}}</span><img data=\"data:image/gif;base64,{{Data}}\"></img>'></option>"
                                            "default" : "<option value={{id}} data-content='<span>{{name}}</span>'></option>",
                                            "main": "<option value={{id}} data-content='<span class=\" {{data}} \" style=\" margin-right:2px; \">  {{name}}</span>' > </option>"
                                        }
                                    });

                                    that.ignoreDropdownEvent = true;

                                    that.iconsSelect.SetOptionsData(
                                        [{ "id": 0, "name": "Choose...", data: "", Template: "default" }].concat(that.model.get('icons'))
                                    );

                                    that.ignoreDropdownEvent = false;

                                    that.iconsSelect.SetValue(that.model.get('iconId'), { silent: true, force: true });

                                    //appending view to the main container
                                    that.append(thatContainer, that.$el);

                                    //onViewComplete();
                                }
                            }
                            , ExternalWidgets: [
                                { Name: 'FormWidgetBase', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidgetBase/', JS: ['FormWidgetBase.js'] }
                                , { Name: 'FormWidget', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidget/', JS: ['FormWidget.js'], CSS: ['FormWidget.css'] }
                            ]
                        });

                    }, true, customPath);
                }, customPath, "machine_configuration");
            } else {
                setTimeout(function () {
                    if (!that.model.loaded) {
                        that.$el.html('<div style="text-align:center;margin-top:10px;"><i class="fa fa-5x fa-cog fa-spin"></i><br /></div>');
                        that.append(thatContainer, that.$el);
                    }
                }, 300);
            }
        }

        , iconsSelectChanged: function (e) {
            try {
                if (!this.ignoreDropdownEvent) {
                    var iconId = this.iconsSelect.GetValue();

                    this.model.set({
                        iconId: (parseInt(iconId, 10) == 0) ? null : iconId
                    });
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.state == app.view_states.loading
                || this.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.state = app.view_states.shown;
                container.append(el);

                this.onappend(this);
            }

            if (this.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }

        , reRender: function (viewParams) {
            try {
            } catch (Error) { }
        }

        , refresh: function (mm, force) {
            try {

                var iconId = this.iconsSelect.GetValue();

                if (mm && ((mm.changed["iconId"]) || force)) {
                    if (mm.get("iconId") != iconId) {
                        var optionID = mm.get("iconId");
                        this.iconsSelect.SetValue(optionID, { silent: true, force: true });
                    }
                }

            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        }

        , checkButtonsState: function (a, b, c) {
            var fromFetch = (b && b.from == "fetch") ? true : false;
            if (!fromFetch) {
                this.setSaveCancelButtons(true);
            }
        }

        , checkRender: function (a, b, c) {
            var fromFetch = (b && b.from == "fetch") ? true : false;
            if (fromFetch) {
                this.render();
            }
        }

        , setSaveCancelButtons: function (val) {
            var btnSave = this.$el.find(".btn-save");
            var btnCancel = this.$el.find(".btn-cancel");

            btnSave.prop("disabled", !val);
            btnCancel.prop("disabled", !val);
        }

        , saveMachineConfiguration: function () {
            var that = this,
                attrs = this.model.toJSON();

            this.setSaveCancelButtons(false);
            this.model.save({
                params: {
                    ihId: attrs.ihId,
                    id: attrs.id,
                    typeId: attrs.typeId,
                    name: attrs.name,
                    typeName: attrs.typeName,
                    parentId: attrs.parentId,
                    iconId: attrs.iconId
                },
                callback: function (model, item) {
                    app.views.topMessages.showMessage(app.translate(that.parent, "type_configuration_saved"));
                    //if (that.model.get("templateId") > 0) {
                    //    that.model.fetchTemplate({
                    //        data: {
                    //            templateId: that.model.get("templateId"),
                    //        }
                    //    });
                    //} else {
                        that.trigger(
                            'updatedNode',
                            this,
                            item,

                        );

                        that.model.fetchTemplate({
                            data: {
                                id: that.model.get("id"),
                                ihId: that.model.get('ihId'),
                            }
                        });
                    //}
                }
            });
        }

        , cancelMachineConfiguration: function () {
            this.setSaveCancelButtons(false);
            this.model.fetchTemplate({
                data: {
                    id: this.model.get("id"),
                    ihId: this.model.get("ihId"),
                }
            });
        }

        , checkUnitProducedFlankOpt: function () {
            var chkbox = this.$el.find("#unitProducedChkboxContainer");
            var tagid = this.model.get("unitProducedTagId");
            chkbox.css("visibility", "hidden");

            var tag = _.findWhere(this.model.get("tags"), { Id: tagid });
            if (_.isObject(tag)) {
                if (tag.DataType == 'DIGITAL') {
                    chkbox.css("visibility", "visible");
                }
            }
        }

        , advopt: function (e) {
            this.$el.find(".counter-resets-at").css('display', e ? 'block' : 'none');
        }

        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.model, "change", this.checkRender);
            this.listenTo(this.model, "change", this.checkButtonsState);
        }

        , bindViewScopedEvents: function () {
        }

        , unbindViewScopedEvents: function () {
        }

        , close: function () {
            this.state = app.view_states.closed;

            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }

        , closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.close();
            });
        }

        , show: function () {
            this.state = app.view_states.shown;

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        }

        , showSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.show();
            });
        }

        , resetModel: function () {
            this.model.set(this.model.defaults);
        }

        , hide: function () {
            this.state = app.view_states.hidden;

            this.resetModel();
            this.hideSubviews();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        }

        , hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                if (sview.cid) sview.hide();
            });
        }

        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
            app.models.subnavbar.set("dateTimeScopeControl", false);
            app.models.subnavbar.set("sections", "4-4-4");
            app.models.subnavbar.set("subnavbar", true);
        }
    });
    
    //subview for the subnavbar controls
    Screen.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: 'equipment-types-subnavbar-controls',
        title: '',
        template: 'equipment-types',

        initialize: function () {
            _.extend(this, this.options);

            this.state = app.view_states.loading;
            this.onappend = (_.isFunction(this.onappend)) ? this.onappend : function () { };

            if (this.model == null)
                this.model = new Screen.Models.Main();

            this.bindEvents();
        },
        events: {
        },

        render: function (container, onComplete) {
            var that = this;
            var thatContainer = (container) ? container : (this.container) ? this.container : null;
            var onViewComplete = (onComplete) ? onComplete : function () { };

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/modules/equipments/configuration/" + this.template + "/";

            T.render.call(this, this.template, function (tmp) {
                if (!that.i18n) that.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.i18n[that.template] = i18nJED;

                    var ctx = {
                        editable: (($.inArray('AdminUserRole', app.models.user.get('roles')) != -1
                            || $.inArray('SupervisorUserRole', app.models.user.get('roles')) != -1) ? true : false),
                    };

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp(
                        _.extend({}, ctx, (that.model) ? that.model.toJSON() : {})
                    ));

                    that.applyBindings();

                    //that.$el.find('.clear-search').clearSearch();

                    that.append(thatContainer, that.$el);

                }, true, customPath);
            }, customPath, 'subnavbar_controls');

        },
        bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
        },

        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.state == app.view_states.loading
                || this.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.state = app.view_states.shown;
                container.append(el);

                this.onappend(this);
            }

            if (this.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        close: function () {
            this.state = app.view_states.closed;

            this.remove();
            this.unbind();
        },
        show: function () {
            this.state = app.view_states.shown;

            this.bindEvents();
            this.$el.show();
        },
        hide: function () {
            this.state = app.view_states.hidden;

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
    });

    Screen.Models.AddExistingModal = Backbone.Epoxy.Model.extend({
        defaults: {
            parent: null,
            ihId: null,
            id: null,
            name: null,

            models: [],

            //parent: null,

            errorMsg: "",
            processing: false,
        },
        
    });

    Screen.Views.AddExistingModal = Modal.Views.SimpleModal.extend({
        className: Modal.Views.SimpleModal.prototype.className + ' add-existing-modal',

        i18n: null,

        items: null,
        grid: null,
        
        initialize: function (options) {
            _.extend(this, options);

            if (!this.model)
                this.model = new Screen.Models.AddExistingModal();

            //this.model.fetchTypes();

            this.items = new Screen.Models.Items();
            
            //this.items.fetch(
            //    {
            //        params: [
            //            //{ Name: 'scriptId', Type: 'INT', Value: this.model.get('scriptId') },
            //            //{ Name: 'includeExamples', Type: 'INT', Value: 1 },
            //            //{ Name: 'includeOnline', Type: 'INT', Value: 1 },
            //            //{ Name: 'timezoneCode', Type: 'VARCHAR', Value: app.models.user.get("timezoneCode") },
            //        ],
            //    }
            //)

            this.bindEvents();

            return this;
        },
        bindEvents: function () {
            Modal.Views.SimpleModal.prototype.bindEvents.apply(this, arguments);
            //this.listenTo(this.items, 'fetch', this.collection_fetch);
            this.listenTo(this.model, "change:id", this.idChanged);
        },

        render: function () {
           
            Modal.Views.SimpleModal.prototype.render.apply(this, arguments);
            var that = this;

            this.tree = null;

            //loading the view and appeding it to the views's $el.
            //that.$el.html(tmp(that.model.toJSON()));

            Core.Include({
                Widgets: []
                , Events: {
                    onLoad: function () {

                        that.applyBindings();

                        that.modelsSelect = new FormSelectBootstrap(that.$("#selectType").get(0), {
                            Events: {
                                onValueChange: [_.bind(that.modelSelectChanged, that)]
                            }
                            , Templates: {
                                //"parent": "<option value={{Id}} data-content='<span>{{Name}}</span><img data=\"data:image/gif;base64,{{Data}}\"></img>'></option>"
                                "default": "<option value={{value}} data-content='<span>{{label}}</span>'></option>",
                                "main": "<option value={{value}} style=\"{{style}}\" data-content='<span  >{{label}}</span>' > </option>"
                            }
                        });

                        that.ignoreDropdownEvent = true;

                        that.modelsSelect.SetOptionsData(
                            [{ "value": 0, "label": "Choose...", Template: "default" }].concat(that.model.get('models'))
                        );

                        that.ignoreDropdownEvent = false;

                        //onViewComplete();
                    }
                }
                , ExternalWidgets: [
                    { Name: 'FormWidgetBase', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidgetBase/', JS: ['FormWidgetBase.js'] }
                    , { Name: 'FormWidget', URL: '/IndustrialDashboard/Widgets/FormWidgets2/FormWidget/', JS: ['FormWidget.js'], CSS: ['FormWidget.css'] }
                ]
            });

           

            //that.modelsSelect.SetValue(that.model.get('iconId'), { silent: true, force: true });

            //appending view to the main container
            //that.append(thatContainer, that.$el);

            //onViewComplete();
           
        },
        modelSelectChanged: function (e) {
            try {
                if (!this.ignoreDropdownEvent) {
                    var modelId = this.modelsSelect.GetValue();

                    this.model.set({
                        id: (parseInt(modelId, 10) == 0) ? null : modelId
                    });
                }
            } catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        idChanged: function (a, b) {
            var that = this,
                text = app.translate([this, that],  "root_tree_preview");

            
            this.items.fetchPreview(_.extend(
                {},
                {
                    params: {
                        id: b,
                        ihId: that.model.get('ihId'),
                    },
                    codesText: text,
                    callback: function () {
                        //that.tree.refresh(); 

                        //Force to set loading state to false if action is MOVE because the refresh after
                        //this transaction does not modify the collection. So callback of tree changes is not
                        //fired and laoding state and jstree objects are not refreshed. Due to that it is necessary
                        //do it here.
                        //if (opt.action == 'MOVE') {
                        

                        if (that.tree == null) {

                            $.jstree.defaults.core.themes.variant = "large";
                            var times = 0;
                            that.$el.find(".jstreePreview").jstree({
                                core: {
                                    check_callback: true,
                                    data: function (obj, cb) {
                                        var data = that.items.toJSON();

                                        //setting disabled nodes
                                        _.each(data, function (t) { t.li_attr = { "class": (t.enabled) ? "" : "node-disabled" } });

                                        data[1].parent = TREE_NODE_ROOT_ID;

                                        cb.call(this, data);
                                    },
                                },
                                types: {
                                    //"root": {
                                    //    icon: 'data:image/gif;base64, ',
                                    //},
                                    //"#": {
                                    //    valid_children: ['root', 'area', 'line'],
                                    //    //max_children: 1,
                                    //},
                                    //"root": {
                                    //    icon: "fa fa-building",
                                    //    valid_children: ['area', 'line'],
                                    //},
                                    //"area": {
                                    //    icon: "fa fa-th-large",
                                    //    valid_children: ['line']
                                    //},
                                    //"line": {
                                    //    "icon": "fa fa-sitemap",
                                    //    valid_children: ['machine'],
                                    //},
                                    //"machine": {
                                    //    "icon": "fa fa-cog",
                                    //    max_children: 0
                                    //},
                                    //"loading": {
                                    //    "icon": "fa fa-spinner fa-spin",
                                    //    valid_children: ['area', 'line', 'machine'],
                                    //},
                                },
                                //contextmenu: {
                                //    items: _.bind(that.customTreeCtxMenu, that),
                                //},
                                sort: function (a, b) {
                                    var nodea = this.get_node(a);
                                    var nodeb = this.get_node(b);

                                    var collection = that.items;
                                    var model_a = collection.get(nodea.id);
                                    var model_b = collection.get(nodeb.id);

                                    if (model_a && model_b)
                                        return model_a.get("order") > model_b.get("order") ? 1 : -1;
                                    else if (model_a) return -1;
                                    else if (model_b) return 1;
                                    else return -1;
                                },
                                plugins: [
                                    //"contextmenu",
                                    //"dnd", //Drag and drop
                                    "wholerow",
                                    "types",
                                    "sort",
                                ],
                            });

                            that.tree = that.$el.find(".jstreePreview").jstree(true);
                        } else {
                            var data = that.items.toJSON();

                            //setting disabled nodes
                            _.each(data, function (t) { t.li_attr = { "class": (t.enabled) ? "" : "node-disabled" } });

                            data[1].parent = TREE_NODE_ROOT_ID;
                            that.tree.settings.core.data = data;
                            that.tree.refresh();
                        }

                        that.$el.find(".jstreePreview").jstree('open_all');

                        that.setTreeLoadingState(false);

                        //    that.tree.refresh(true);
                        //}
                    },
                }));
        },
        setTreeLoadingState: function (isLoading) {
            var tree = this.tree;

            var rootNode = tree.get_node(TREE_NODE_ROOT_ID);

            if (isLoading == true) {
                tree.set_type(rootNode, 'loading');

                $('.tree li').each(function () {
                    tree.disable_node(this.id);
                });
            }
            else {
                tree.set_type(rootNode, 'root');

                $('.tree li').each(function () {
                    tree.enable_node(this.id);
                });
            }
        },
        save: function () {
            var that = this,
                attrs = this.model.toJSON();

            if (attrs.processing == false) {
                this.model.set('processing', true);

                try {
                    this.trigger(
                        'saving',
                        this,
                        attrs,
                        {
                            success: function (id) {
                                try {
                                    that.model.set('processing', false);

                                    that.finish({ result: 'SUCCESS', id: id});

                                    that.hide();
                                    //setTimeout(_.bind(that.hide, that), 1500);
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            error: function (errorMsg) {
                                try {
                                    app.views.topMessages.showMessage(app.translate([{ options: { i18n: { 1: that.i18n, }, }, template: 1, }, app], errorMsg), { stay: 5 * 1000, });
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                finally {
                                    that.model.set('processing', false);
                                }
                            },
                        }
                    );
                }
                catch (e) {
                    this.model.set('processing', false);
                    throw e;
                }
            }
        },
        show: function () {
            if (!this.isRendered) {
                this.render();
            }
            else {
                this.$el.modal({
                    keyboard: false,
                    backdrop: 'static',
                });
            }

            return this;
        },
        hide: function () {
            if (this.innerModal)
                this.innerModal.hide();

            var result = Modal.Views.SimpleModal.prototype.hide.apply(this, arguments);
            return result;
        },
        removeRow: function (model) {
            var that = this;
            model.collection.removeItem(
                model.get('id')
                , function (coll, data) {
                    app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });

                    that.items.remove(model);

                    that.collection_fetch();
                }
                , function (coll, msg) {
                    app.views.topMessages.showMessage(app.translate([that, app], msg), { stay: 10 * 1000, });
                }
            );
        },
        downloadScript: function (m) {
            try {
                var that = this;

                Script.download(
                    {
                        params: {
                            id: m.get('id')
                        },
                        success: function (model, data) {
                            try {
                                // Blob for saving.
                                var blob = new Blob([new Uint8Array(data.Content)], { type: 'application/octet-stream' });

                                // Tell the browser to download the file.
                                saveAs(blob, data.FileName);
                            }
                            catch (error) {
                                console.error((error.stack) ? error.stack : new Error(error).stack);
                            }
                        },
                        error: function (model, msg) {
                            try {
                                app.views.topMessages.showMessage(app.translate([that, app], msg), { stay: 5 * 1000, });
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        },
                    }
                );
            }
            catch (error) {
                console.error((error.stack) ? error.stack : new Error(error).stack);
            }
        },

        acceptBtn_click: function (e) {
            try {
                this.save();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        collection_fetch: function (col, resp) {
            var that = this;
            var s = [];
            var e = [];

            this.items.each(
                function (m) {
                    if (m.get('statusCode') == 'EXAMPLE') {
                        e.push(m);
                    }
                    else {
                        s.push(m);
                    }
                }
            );

            s.forEach(function (model, index) {
                model.set('curSourceId', that.model.get('curSourceId'));
            });

            this.sources.set(s);

            this.examples.set(e);

            if (this.toCloneSource && !this.sources.findWhere({ id: -1 })) {
                this.addNewClone(this.toCloneSource);
            }
        },
    });

    // Required, return the module for AMD compliance.
    return Screen;

});
