//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.Models.Recipient = Backbone.Epoxy.Model.extend({
            defaults: {
                eventId: null,
                email: null
            },

            parse: function (obj) {

                var result = {
                    eventId: obj.eventId,
                    email: obj.email
                };
                return result;
            }
        });

        Screen.Collections.Recipients = Backbone.Collection.extend({
            model: Screen.Models.Recipient,
            comparator: 'email',
            parse: function (recipientArray) {
                this.set(recipientArray);
            },

            updateEventRecipients: function (recipients, action, success, error) {
                var that = this;

                //LLAMADA SQL
                switch (action.toUpperCase()) {
                    case 'DELETE':
                        recipients.collection.remove(recipients);
                        break;
                    case 'ADD':
                        this.add(recipients);
                        break;
                }
                var commaSeparatedRecipients = this.pluck('email').join(';');

                var QP = new QueryParameters();

                QP.Add('@eventId', 'INT', recipients.get('eventId'));
                QP.Add('@recipients', 'VARCHAR', commaSeparatedRecipients);

               
                Core.Json.CallProcedure(app.DatabaseNames.MES + '.MAIL.UpdateEventRecipients', 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);

            },
        });

        Screen.Models.Item = Backbone.Epoxy.Model.extend({
            defaults: {
                eventId: null,
                eventName: null,
                schedule: null,
                recipients: null,
            },

            parse: function (obj) {
                var result = {
                    eventId: obj.EventId,
                    eventName: obj.EventName,
                    schedule: obj.Schedule,
                    recipients: obj.Recipients,
                };
                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 + '.MAIL.GetEventsScheduleRecipients',
                    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;
            },

        });

        Screen.Models.AddRecipientModal = Backbone.Epoxy.Model.extend({
            defaults: {
                newRecipients: null,
            },
        });

        Screen.Views.AddRecipientModal = Backbone.Epoxy.View.extend({
            template: "emails-configuration",
            className: "modal modal-assign-heats hide fade",
            bindings: "data-bind",
            title: "Add Recipient",
            isCacheable: true,
            events: function () {
                return {
                    "click #acceptBtn": this.acceptBtn_click,
                    "click #cancelBtn": this.cancelBtn_click,
                    "submit form": this.form_submit,
                    "keypress": this.modal_keypress,
                    "show.bs.modal": this.modal_show,
                    "shown.bs.modal": this.modal_shown,
                    "hidden.bs.modal": this.modal_hidden,
                };
            },
            container: null,
            disposed: false,
            isRendered: false,
            preventDispose: false,
            visible: false,
            row: [],
            grid: [],
            initialize: function (options) {
                _.extend(this, options);
                if (!this.model) {
                    this.model = new Screen.Models.AddRecipientModal();
                }
                this.parent = options.parent;
                this.bindEvents();

                return this;
            },
            hide: function (preventDispose) {
                this.preventDispose = (preventDispose);

                this.$el.modal('hide');

            },
            render: function (container) {
                if (container)
                    this.container = container;

                var that = this;
                var customPath = '/app/custom-screens/' + this.template + '/';
                T.render.call(this, this.template, function (tmp) {
                    if (!that.i18n) that.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        that.i18n[that.template] = i18nJED;
                        that.$el.html(tmp(that.model.toJSON()));
                        that.applyBindings();

                        that.isRendered = true;



                        that.trigger("render");


                    }, true, customPath);

                }, customPath, "recipients_modal");

            },
            show: function () {
                if (!this.isRendered) {

                    this.render();
                }
                else {
                    this.$el.modal({
                        keyboard: true,
                        backdrop: 'both',
                    });
                }

                return this;
            },

            bindEvents: function () {
                this.listenToOnce(this, "render", this.view_render);


            },

            close: function () {
                if (this.disposed == false) {
                    if (this.visible == true) {
                        this.hide();
                    }
                    else {
                        this.trigger('close');

                        this.remove();
                        this.unbind();

                        this.disposed = true;
                    }
                }
            },
            preRender: function () {
                app.models.subnavbar.set("dateControl", false);
            },
            reRender: function () {
            },

            acceptBtn_click: function () {
                try {
                    var newRecipient = this.model.get('newRecipients');
                    if (!this.isValidEmail(newRecipient)) {
                        app.views.topMessages.showMessage('Email is not valid ', { stay: 2000, });
                    }
                    else {
                        this.model.set({ newRecipients: this.model.get('newRecipients') });
                        this.parent.addRecipientItem();
                        this.close();
                    }

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

            isValidEmail: function (email) {
                var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                return emailRegex.test(email);
            },
            form_submit: function (e) {
                try {
                    e.preventDefault();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_hidden: function (e) {
                try {
                    this.visible = false;

                    if (!this.preventDispose)
                        this.close();
                    else
                        this.preventDispose = false;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_show: function (e) {
                try {
                    this.visible = true;
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            modal_shown: function (e) {
                try {
                    this.$el.find(".autofocus").focus();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },
            view_render: function () {
                try {
                    this.show();
                }
                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
            },

        });

        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,
                recipients: null,
                newRecipients: null,
                selectedMaterialSystem: null,
                deleteBtnPressed: false,

                showMaterialSystemsGrid: false,
                isLoadingSystems: false,
            },

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

        });

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

        Screen.Views.Main = Backbone.Epoxy.View.extend({
            template: 'emails-configuration',
            id: 'emails-configuration',
            title: 'Emails Configuration',
            //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 {
                    'click #addRecipient': this.addRecipientBtn_click,
                };
            },

            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 #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: 'eventName',
                                            label: app.translate(that, 'name_col'),
                                            editable: false,
                                            sortable: false,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            name: 'schedule',
                                            label: 'Schedule',
                                            editable: false,
                                            sortable: true,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            })
                                        },
                                        {
                                            name: 'status',
                                            label: 'Status',
                                            editable: false,
                                            sortable: true,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                                render: function () {
                                                    var celText = $('<a style="color:#6bd28d;">Running</a>')
                                                    this.$el.append(celText);
                                                    return this;
                                                },
                                            }),
                                        }
                                    ],
                                    row: Backgrid.Row.extend({
                                        initialize: function (options) {
                                            Backgrid.Row.prototype.initialize.apply(this, arguments);

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

                                        click: function (e) {
                                            try {
                                                that.model.set({ eventId: this.model.get('eventId') });
                                                that.model.set({ selectedRecipients: this.model.get('recipients') });
                                                that.model.set({ showMaterialSystemsGrid: true });
                                                ; if (!this.$el.hasClass("selectedItemMainGrid")) {
                                                    contents = $('.selectedItemMainGrid');
                                                    if (contents) contents.removeClass('selectedItemMainGrid');
                                                    this.$el.addClass("selectedItemMainGrid");
                                                }
                                            }
                                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                        },
                                    }),
                                    collection: that.model.get('items'),
                                });

                                var grid_emails = new Backgrid.Grid({
                                    className: 'backgrid table table-hover',
                                    columns: [
                                        {
                                            name: 'email',
                                            label: app.translate(that, 'name_col'),
                                            sortable: false,
                                            editable:false,
                                            cell: Backgrid.StringCell.extend({
                                                orderSeparator: '',
                                                className: 'string-cell align-center-cell',
                                            }),
                                        },
                                        {
                                            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');
                                                    if (val) {
                                                        btnRemove.addClass('hide');
                                                    } else {
                                                        btnRemove.removeClass('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({ selectedRecipient: this.model.get('email') });


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

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


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

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

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

                                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,
                    showMaterialSystemsGrid: false,
                });

                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:selectedRecipients', this.selectedRecipients_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();
            },
            selectedRecipients_changed: function () {
                var modelArray = [];
                var eventId = this.model.get('eventId');
                this.model.get('selectedRecipients').split(/[;]+/).forEach(function (str) {
                    var recipientModel = new Screen.Models.Recipient({ email: str, eventId: eventId });
                    modelArray.push(recipientModel);
                });
                this.model.get('recipients').parse(modelArray);
            },
            _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,
                });

            },
            addRecipientItem: function () {
                var newRecipient = new Screen.Models.Recipient({ email: this.model.get('newRecipients'), eventId: this.model.get('eventId') });
                this.actionOnRow(newRecipient, 'ADD');

            },
            removeRow: function (model) {
                var that = this;
                model.collection.updateEventRecipients(
                    model,
                    'DELETE',
                    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 (model) {
                var that = this;
                this.model.get('recipients').updateEventRecipients(
                    model,
                    'ADD',
                    function (coll, data) {
                        that.refreshBtn_click();
                    }
                    , function (coll, msg) {
                        that.refreshBtn_click();
                    }
                );

                that.refreshBtn_click();


            },
            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 'ADD':
                            var that = this;
                            that.saveRow(model);

                            break;
                        case 'DISCARD':
                            this.discardRow(model);
                            break;
                    }
                }
                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
            },

            openModal: function () {
                var modal = new Screen.Views.AddRecipientModal({
                    newRecipients: '',
                });
                modal.show();
            },
            addRecipientBtn_click: function (e) {
                try {
                    var that = this;

                    //var modal = 
                    var modal = new Screen.Views.AddRecipientModal({
                        model: that.model,
                        parent: that,
                    });

                    this.model.set({ newRecipients: '' });
                    modal.show();
                }
                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); }
            },
            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: 'emails-configuration',

            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/emails-configuration/';

                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;

    });
