//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',
  'backgrid',
  'modules/modal',
],

function (app, T, Backgrid, Modal) {

    var Screen = { Models: {}, Views: {}, Collections: {} }

    Screen.Collections.Systems = Backbone.Collection.extend({

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

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetMaterialSystems',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var newColl = [];
                                _.map(resp.Table, function (obj) {
                                    obj['active'] = false;
                                    newColl.push(obj);
                                });
                                that.set(newColl);
                            }
                            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); }
                    },
                    Async: true,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },

        update: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@MaterialId', 'INT', params.materialId);
            qp.Add('@systems', 'VARCHAR', params.systems);

            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.UpdateMaterialsMaterialSystems',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                
                            }
                            else {
                                if ((resp) && (resp.Message)) {
                                    app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                    console.error(resp.Message);
                                }
                                else {
                                    app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                    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.Models.Item = Backbone.Epoxy.Model.extend({
        defaults: {
            id: null,
            active: null,
            name: null,
            l1Code: null,
            systems: null,
            l3Code: null,
        },

        parse: function (obj) {
            var result = {
                id: obj.Id,
                active: obj.Active,
                name: obj.Name,
                l1Code: obj.L1Code,
                systems: obj.Systems,
                l3Code: obj.L3Code,
            };
            return result;
        }
    });
    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Item,

        fixedParameters: [],

        
        fetch: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();
            qp.Add('@rowsToFetch', 'INT', 100);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetMaterials',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var newColl = _.map(resp.Table, that.model.prototype.parse);

                                that.set(newColl)
                                    .trigger('fetch', that, resp);
                            }
                            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); }
                    },
                    Async: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        upsertItem: 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);
            }
            console.log("props", props);

            Core.Json.CallProcedure(app.DatabaseNames.MES + '.CAT.UpsertMaterial', QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table.length > 0) {
                        var data = data.Table;

                        if (!data[0].Message) {
                            var ids = _.pluck(data, 'Id');

                            if (success != null && _.isFunction(success))
                                success.call(this, that, ids);
                        }
                        else {
                            error.call(this, that, data[0].Message);
                        }
                    } else {
                        if (data.Message)
                            error.call(this, that, data.Message);
                        else
                            error.call(this, that);
                    }
                },
                onError: function (data) {
                    if (error != null && _.isFunction(error))
                        error.call(this, that);
                },
                Async: true,
                Secured: true,
            }, app.ConnectionStrings.app);
        },
        removeItem: function (id, success, error) {
            var model = this.get(id);
            if (model) {
                var that = this;
                var QP = new QueryParameters();

                QP.Add('@id', 'INT', id);
                Core.Json.CallProcedure(
                    app.DatabaseNames.MES + '.CAT.RemoveMaterial',
                    QP,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp && resp.Table[0] && resp.Table[0].Success == 1) {
                                    that.trigger('removed');
                                    app.views.topMessages.showMessage('The Material Was Removed', { stay: 5000, });
                                    
                                }
                                else {
                                    if ((resp) && (resp.Table[0].Message)) {
                                        app.views.topMessages.showMessage(resp.Table[0].Message, { stay: 5000, });
                                        console.error(resp.Table[0].Message);
                                    }
                                    else {
                                        app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                        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.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            items: null,
            itemId: null,

            itemName: null,
            itemActive:false,
            itemEAFA: false,
            itemEAFB: false,
            itemLMFA: false,
            itemLMFB: false,

            hasItemData: false,
            hasItemSpecData: false,
            hasData: false,
            isLoading: true,
            isLoadingItemData: false,

            systems: null,
            selectedMaterialSystem: null,
            deleteBtnPressed: false,

            showMaterialSystemsGrid: false,
            isLoadingSystems: false,
        },

        initialize: function () {
            this.attributes.items = new Screen.Collections.Items();
            this.attributes.systems = new Screen.Collections.Systems();
            this.attributes.systems.fetch();
           
        },


        fetchSelectedMaterialSystem: function (params) {
            var that = this,
                qp = new Core.Database.QueryParameters();

            qp.Add('@id', 'INT', params.id);
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetMaterialsMaterialSystemsSP',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                that.set('selectedMaterialSystem',resp.Table[0].Systems)
                                    .trigger('fetchSystems', resp.Table[0].Systems);
                            }
                            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); }
                    },
                    Async: true,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },
       
    });

    //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 'materials'; 
        } catch (Error) { }
    }

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'materials',
        id: 'materials',
        title: 'Materials',
        //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,
        events: function () {
            return {
            };
        },

        autoRefresh: null,
        subviews: null,
        viewParams: null,

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

            var that = this;

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

            this.model = new Screen.Models.Main();
            this.item = new Screen.Collections.Items();

            this.subviews = {
                subnavbarControls: new Screen.Views.SubnavBarControls({
                    model: this.model,
                    parent: this,
                    container: app.views.subnavbar.getSectionContainer(1, 12),
                    events: function () {
                        return {
                            'click .add-item': _.bind(that.addNewBtn_click, that),
                            'click #refreshBtn': _.bind(that.refreshBtn_click, that),
                        };
                    },
                }),
            };


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

            this.viewParams = viewParams;

            var thatContainer = (this.options.container) ? this.options.container : container;
            this.options.container = thatContainer;

            //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/' + this.template + '/';

            T.render.call(
                this,
                this.template,
                function (tmp) {
                    if (!that.options.i18n) that.options.i18n = {};

                    app.getI18NJed(
                        that,
                        that.template,
                        function (i18nJED) {
                            //storing internationalization data
                            that.options.i18n[that.template] = i18nJED;

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

                            //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')

                            that.subviews.subnavbarControls.render();

                            
                            var grid = that.options.itemsGrid = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [
                                    {
                                        name: 'name',
                                        label: app.translate(that, 'name_col'),
                                        editable: true,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'l1Code',
                                        label: 'L1 Code',
                                        editable: true,
                                        sortable: true,
                                        cell: Backgrid.NumberCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                            decimals: 0,
                                        })
                                    },
                                    {
                                        name: 'l3Code',
                                        label: 'L3 Code',
                                        editable: true,
                                        sortable: true,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'active',
                                        label: app.translate(that, 'active_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Cell.extend({
                                            template: _.template("<input class='grid-checkbox' tabindex='-1' type='checkbox' />"),
                                            initialize: function () {
                                                Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                            },
                                            events: {
                                                "change .grid-checkbox": "chkboxChanged",
                                            },
                                            chkboxChanged: function (e) {
                                                this.model.set(this.column.get("name"), $(e.target).is(":checked"));
                                            },
                                            render: function () {
                                                this.$el.html(this.template());
                                                if (this.model.get(this.column.get("name"))) this.$el.find(".grid-checkbox").attr("checked", "checked");

                                                this.delegateEvents();
                                                return this;
                                            },
                                            className: "align-center-cell member",
                                        }),
                                    },
                                    {
                                        name: 'actions',
                                        label: '',
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Cell.extend({
                                            template: Handlebars.compile(that.$el.find('#actions_cell_template').html()),
                                            className: 'actions-cell',
                                            events: {
                                                'click .btn-cell-action': 'cellActionClick'
                                            },

                                            initialize: function () {
                                                Backgrid.Cell.prototype.initialize.apply(this, arguments);

                                                this.bindEvents();
                                            },
                                            render: function () {
                                                this.$el.html(this.template());

                                                this.$el.find('[data-toggle="tooltip"]').tooltip();

                                                this.checkMode();
                                                this.delegateEvents();
                                                return this;
                                            },
                                            bindEvents: function () {
                                                this.listenTo(this.model, 'change:isNew', this.checkMode);
                                            },
                                            checkMode: function () {
                                                var newRow = this.model.get('isNew');
                                                if (newRow) this.setNewRowMode(true);
                                                else this.setNewRowMode(false);
                                            },
                                            setNewRowMode: function (val) {
                                                var btnRemove = this.$el.find('.btn-remove');
                                                var btnSave = this.$el.find('.btn-save');
                                                var btnDiscard = this.$el.find('.btn-discard');
                                                if (val) {
                                                    btnRemove.addClass('hide');
                                                    btnSave.removeClass('hide');
                                                    btnDiscard.removeClass('hide');
                                                } else {
                                                    btnRemove.removeClass('hide');
                                                    btnSave.addClass('hide');
                                                    btnDiscard.addClass('hide');
                                                }
                                            },
                                            cellActionClick: function (e) {
                                                try {
                                                    var target = $(e.target);
                                                    var actionData = target.closest('[data-cell-action]').data('cell-action');
                                                    if (actionData) {
                                                        switch (actionData.toUpperCase()) {
                                                            case 'DELETE':
                                                                that.model.set({
                                                                    deleteBtnPressed: true,
                                                                });
                                                                break;
                                                        }

                                                        that.actionOnRow(this.model, actionData);
                                                    }
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                        }),
                                    },
                                ],
                                row: Backgrid.Row.extend({
                                    initialize: function (options) {
                                        Backgrid.Row.prototype.initialize.apply(this, arguments);

                                    },
                                    events: {
                                        click: 'click',
                                    },

                                    click: function (e) {
                                        try {
                                            if (that.model.get('deleteBtnPressed') == false) {

                                                that.model.set({ selectedMaterialId: this.model.get('id') });

                                                if (!this.$el.hasClass("selectedItem")) {
                                                    var contents = $('.selectedItem');
                                                    if (contents) contents.removeClass('selectedItem');
                                                    this.$el.addClass("selectedItem");
                                                }

                                            } else {
                                                that.model.set('deleteBtnPressed', false);
                                            }
                                         

                                        }
                                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                    },
                                }),
                                collection: that.model.get('items'),
                            });

                            var grid_systems = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [
                                    {
                                        name: 'Name',
                                        label: app.translate(that, 'name_col'),
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'active',
                                        label: app.translate(that, 'active_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.Cell.extend({
                                            template: _.template("<input class='grid-checkbox' tabindex='-1' type='checkbox' />"),
                                            initialize: function () {
                                                Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                            },
                                            events: {
                                                "change .grid-checkbox": "chkboxChanged",
                                            },
                                            chkboxChanged: function (e) {
                                                this.model.set(this.column.get("name"), $(e.target).is(":checked"));
                                            },
                                            render: function () {
                                                this.$el.html(this.template());
                                                if (this.model.get(this.column.get("name"))) this.$el.find(".grid-checkbox").attr("checked", "checked");

                                                this.delegateEvents();
                                                return this;
                                            },
                                            className: "align-center-cell member",
                                        }),
                                    }
                                ],
                                collection: that.model.get('systems'),

                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);
                            //end
                            that.$el.find('.items-grid-container-systems').append(grid_systems.render().el);

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

                            //Set model with view params here to prevent changes on the model when the view bindings are applied.
                            //if (viewParams) {
                            //    that.model.set({
                            //        itemId: (viewParams.sectionParam1) ? parseInt(viewParams.sectionParam1, 10) : null,
                            //    });
                            //}

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


        refreshBtn_click: function () {
            this.refreshColl();
        },
        refreshColl: function () {
            var that = this,
                modelAttrs = this.model.toJSON(),
                itemsColl = this.model.get('items');
          

            this.model.set({
                hasData: false,
                isLoading: true,
                selectedMaterialId : null,
            });

            this.stopListening(this.model.get('items'), 'change', this.collection_changed);

            itemsColl.fetch({
               // itemId: modelAttrs.itemId,
                refresh: true,
            })
        },


        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.item, 'fetch', this.item_fetch)
               // .listenTo(this.model, 'change:itemId', this.model_change_itemId)
                .listenTo(this.model, 'change:selectedMaterialId', this.selectedMaterialId_changed)
                .listenTo(this.model.get('systems'), 'change:active', this.systems_changed)
                .listenTo(this.model,'fetchSystems',this.systems_feched)
                .listenTo(this.model.get('items'), 'add remove', this.collectionAddRemove)
                .listenTo(this.model.get('items'),'removed',this.material_removed)
                .listenTo(this.model.get('items'), 'fetch', this.collection_fetch);
        },
        material_removed: function () {
            this.refreshItemsColl();
        },
        systems_feched: function (obj) {
            var model = [],
                collection = this.model.get('systems'),
                activeSystems = collection.toJSON(),
                string = this.model.get('selectedMaterialSystem');

            this.stopListening(collection, 'change:active', this.systems_changed);

            _.each(string, function (bit, i) {
                if (activeSystems[i]) {
                    model = collection.at(i);
                    model.set({ active: bit == 1 ? true : false });
                }
            })

            var models = this.model.get('items').toJSON()

            if (models[0].id > 0)
                this.model.set('showMaterialSystemsGrid', true);
            this.listenTo(collection, 'change:active', this.systems_changed);
        },

        selectedMaterialId_changed: function () {
            var materialId = this.model.get('selectedMaterialId');
            if (materialId) this.model.fetchSelectedMaterialSystem({ id: materialId });
            else {
                this.model.set('showMaterialSystemsGrid', false);
                var selectedRow = $('.selectedItem');
                if (selectedRow) selectedRow.removeClass('selectedItem');
            }
        },

        systems_changed: function () {
            var that = this,
                systems = this.model.get('systems'),
                systemJSON = systems.toJSON(),
                string = '';
            _.each(systemJSON, function (obj) {
                string = string + (obj.active == true ? '1' : '0');
            });
            systems.update({
                materialId: that.model.get('selectedMaterialId'),
                systems: string,
            });
           
        },
        _refresh: function (opt) {
            if (this.autoRefresh.toid != null) {
                clearTimeout(this.autoRefresh.toid);
                this.autoRefresh.toid = null;
            }

            this.refreshItemsColl(opt);

            if (this.autoRefresh.enabled == true) {
                var that = this;

                this.autoRefresh.toid = setTimeout(
                    function () { that._refresh(); },
                    this.autoRefresh.every
                );
            }
        },
        refresh: function (viewParams) {
        },
        refreshItemsColl: function (options) {
            var that = this,
                itemsColl = this.model.get('items'),
                opt = _.extend({}, options, { params: {}, refresh: true, });

            if (opt.reset == true)
                this.model.set('isLoading', true);

            var that = this,
                modelAttrs = this.model.toJSON();

            itemsColl.fetch(_.extend(
                opt,
                {
                    params: _.extend(
                        modelAttrs,
                        opt.params,
                        {
                            refresh: opt.refresh,
                            reset: opt.reset,
                        }
                    ),
                },
                {
                    success: function (record) {
                        that.model.set({
                            itemName: record[0].Name,
                            itemActive: record[0].Active
                        });
}
                }
            ));
        },
        refreshItem: function (options) {
            var opt = _.extend({}, options, { });

            this.model.set({
                hasItemData: false,
                hasItemSpecData: false,
                isLoadingItemData: true,
                isLoadingItemSpecData: true,
            });

        },

        addNew: function () {
            this.model.get('items').unshift({
                id: -1,
                isNew: true,
            });
        },
        removeRow: function (model) {
            var that = this;
            model.collection.removeItem(
                model.get('id')
                , function (coll, data) {
                    that.refreshBtn_click();
                }
                , function (coll, msg) {
                    that.refreshBtn_click();
                }
            );

            that.refreshBtn_click();
        },
        discardRow: function (m) {
            //to discard just remove the model from the collection.
            m.collection.remove(m);
        },
        saveRow: function (m) {
            var that = this;

            this.stopListening(this.model.get('items'), 'change', this.collection_changed);

            m.set('systems', that.getSystemValue(m.get('systems'), m.get('name'), m._previousAttributes.systems));
            m.collection.upsertItem(null, [
                { name: 'active', type: 'BIT', value: m.get('active') },
                { name: 'name', type: 'VARCHAR', value: m.get('name') },
                { name: 'l1Code', type: 'SMALLINT', value: m.get('l1Code') },
                { name: 'l3Code', type: 'VARCHAR', value: m.get('l3Code') },
                { name: 'systems', type: 'VARCHAR', value: m.get('systems') },
            ], function (ref, ids) {
                m.set({ id: ids[0], isNew: false }, { avoidSync: true });
                    that._refresh();

            }, function (coll, msg) {
                app.views.topMessages.showMessage(app.translate([app, that], msg), { stay: 10000, });
                    that._refresh();
            });
        },


        collection_changed: function (m, b, c) {
            var that = this;
            var fromFetch = (b && b.from == 'fetch') ? true : false;
            var avoidSync = (b && b.avoidSync) ? b.avoidSync : false;
            var isNewRow = m.get('isNew');


            if (!fromFetch && !isNewRow && !avoidSync) {
                m.set('systems', that.getSystemValue(m.get('systems'), m.get('name'), m._previousAttributes.systems));
                m.collection.upsertItem(m.get('id'), [
                    { name: 'active', type: 'BIT', value: m.get('active') },
                    { name: 'name', type: 'VARCHAR', value: m.get('name') },
                    { name: 'l3Code', type: 'VARCHAR', value: m.get('l3Code') },
                    { name: 'l1Code', type: 'SMALLINT', value: m.get('l1Code') },
                    { name: 'systems', type: 'VARCHAR', value: m.get('systems') },
                ], function (ref, ids) {
                }, function (coll, msg) {
                    app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                    that._refresh();
                });
            }
        },
        append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

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

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

                this.options.onappend(this);
            }

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

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        },
        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(
                        function () { that._refresh(); },
                        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;
        },
        bindViewScopedEvents: function () {
        },
        unbindViewScopedEvents: function () {
        },
        close: function () {
            this.options.state = app.view_states.closed;

            this.stopAutoRefresh();
            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        },
        closeSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.close();
            });
        },
        show: function () {
            this.options.state = app.view_states.shown;

            this.showSubviews();
            this.bindEvents();
            this.$el.show();
        },
        showSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.show();
            });
        },
        hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();
            this.stopAutoRefresh();

            this.$el.hide();
            this.unbind();
            this.stopListening();
        },
        hideSubviews: function () {
            _.each(this.subviews, function (sview) {
                sview.hide();
            });
        },
        preRender: function () {
            app.models.subnavbar.setAll(false);
            app.models.subnavbar.set('sections', '12');
            app.models.subnavbar.set('subnavbar', true);
        },
        reRender: function () {
            this.startAutoRefresh();
        },

        actionOnRow: function (model, action) {
            var that = this;
            try {
                switch (action.toUpperCase()) {
                    case 'DELETE':
                        var that = this,
                            modal = new Modal.Views.Main({
                                focusOk: false,
                                focusSelector: '#btn-cancel',
                                title: app.translate([this, app], "delete_item_modal_confirm_title"),
                                message: app.translate([this, app], "delete_item_modal_confirm_message"),
                                buttons_type: "CONTINUE-CANCEL",
                            });

                        this.listenToOnce(modal, "continue", function (modal) {
                            try {
                                that.removeRow(model);
                            }
                            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                        });

                        modal.show();
                        break;
                    case 'SAVE':
                        this.saveRow(model); 
                        break;
                    case 'DISCARD':
                        this.discardRow(model); 
                        break;
                }
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        addNewBtn_click: function (e) {
            try {
                this.addNew();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },

        getSystemValue: function (str, name, prev = null) {
            var validSystem = true;
            if (str && str != null && str.length > 0) {
                if (str.length <= 32) {
                    _.each(str, function (obj) {
                        
                        if (parseInt(obj) != 1 && parseInt(obj) != 0) {
                            validSystem = false;
                        }
                    })
                } else {
                    str = prev;
                    app.views.topMessages.showMessage('Maximum lenght 32', { stay: 2000, });
                }
                if (!validSystem) {
                    str = prev;
                    app.views.topMessages.showMessage('Only 1 and 0 are allowed', { stay: 2000, });
                }
            }
            return str;
        },



        collection_fetch: function (coll, resp) {
            try {
                this.model.set({
                    hasData: (this.model.get('items').length > 0),
                    isLoading: false,
                });
                this.listenTo(this.model.get('items'), 'change', this.collection_changed);
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        //model_change_itemId: function (model, value, opt) {
        //    try {
        //        var params = this.model.toJSON();

        //        app.router.navigate(
        //            app.router.resolveURL(
        //                app.router.currentModule,
        //                _.extend(
        //                    {},
        //                    params,
        //                    {
        //                        section: 'materials',
        //                        sectionParam1: (params.itemId) ? params.itemId : '',
        //                    }
        //                ),
        //                false
        //            ),
        //            { trigger: false, }
        //        );

        //        if (value) {
        //            this.refreshItem({
        //                params: _.extend(
        //                    {},
        //                    params,
        //                    {}
        //                ),
        //            });
        //        } 
        //        //Disable/enable main grid infinator.
        //        //this.options.itemsGrid.footer.setEnabled(!params.itemId);
        //    }
        //    catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        //},
        item_fetch: function (model, resp) {
            try {
                this.model.set({
                    isLoadingItemData: false,
                    hasItemData: this.model.get('itemId'),
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        model_change_pickers: function (model, value, opt) {
            try {
                var params = this.model.toJSON();

                this.refreshItemsColl({
                    reset: true,
                    params: _.extend(
                        {},
                        params,
                        {}
                    ),
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
    });

    //subview for the subnavbar controls
    Screen.Views.SubnavBarControls = Backbone.Epoxy.View.extend({
        id: 'materials-subnavbar-controls',
        title: '',
        template: 'materials',

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

            this.bindEvents();
        },
        render: function (container, onComplete) {
            var that = this;
            var thatContainer = (container) ? container : (this.options.container) ? this.options.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/materials/';

            T.render.call(this, this.template, function (tmp) {
                if (!that.options.i18n) that.options.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.options.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.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.options.state == app.view_states.loading
                || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

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

                this.options.onappend(this);
            }

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

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

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

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

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

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

});
