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

  'modules/grade/grade',
  'modules/grade-spec',

  'backgrid/infinator',
  'js/jquery.clearsearch/jquery.clearsearch',
],

function (app, T, Backgrid, Modal, Grade, GradeSpec) {

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


    Screen.Models.Grade = Backbone.Epoxy.Model.extend({
        defaults: {
            id: null,
            active: null,
            description: null,
            name: null,
            group: null,
            groupId: null,
            //recipeId: null,
            recipeName : null,
            //RecipeNameDefault: null,

        },

        parse: function (obj) {
            var result = {
                id: obj.Id,
                active: obj.Active,
                description: obj.Description,
                name: obj.Name,
                group: obj.Group,
                groupId: obj.GradeGroupId,                
                //recipeId: obj.RecipeId,
                recipeName: obj.ScrapRecipeName, 
                //recipeNameDefault: obj.RecipeNameDefault,
            };

            return result;
        }
    })


    Screen.Collections.Items = Backbone.Collection.extend({
        model: Screen.Models.Grade,

        fixedParameters: [],
        isFetching: false,
        currentPage: 1,
        pageSize: 50,
        transaction_timestamp: null,

        fetch: function (opt) {
            var that = this,
                qp = new Core.Database.QueryParameters(),
                ttimestamp = this.transaction_timestamp = new Date().getTime(),
                options = opt ? _.clone(opt) : {};

            qp.Add('@onlyActives', 'BIT', false);

            if (options.reset) {
                this.resetPagination(true);

                this.fixedParameters = [
                    { Name: '@search', Type: 'VARCHAR', Value: options.params.search, },
                ];
            }

            _.each(this.fixedParameters, function (qpParams) {
                qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
            });

            if (options.refresh) {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@rowsToFetch', 'INT', this.currentPage * this.pageSize);
            }
            else if (options.reset) {
                qp.Add('@fromRow', 'INT', 0);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }
            else {
                qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize);
                qp.Add('@rowsToFetch', 'INT', this.pageSize);
            }


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetGrades',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            //checking transaction timestamp
                            if (ttimestamp != that.transaction_timestamp)
                                return;

                            if ((resp) && (resp.Table)) {
                                var records = resp.Table,
                                    newColl;
                                newColl = _.map(records, that.model.prototype.parse);
                                var method = ((options.refresh) || ((options.reset))) ? 'set' : 'add';

                                //checking transaction timestamp
                                if (ttimestamp != that.transaction_timestamp)
                                    return;

                                var editingItems = _.where(that.toJSON(), { isNew: true });
                                [].push.apply(newColl, editingItems);

                                that[method](newColl, { from: 'fetch' })
                                    .trigger('fetch', that, records);

                                //decreasing page since we couldn't get any data on this page.
                                if (newColl.length == 0 && method == 'add')
                                    that.currentPage--;

                                that.isFetching = false;
                            }
                            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: options.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
        getNextPage: function (options) {
            if (!this.isFetching) {
                this.currentPage++;
                options = (_.isObject(options)) ? options : {};
                this.fetch(options);
            }
        },
        resetPagination: function (force) {
            if (!this.isFetching || force == true) {
                this.currentPage = 1;
            } else {
                _.delay(this.resetPagination, 100);
            }
        },

        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);
            }

            Core.Json.CallProcedure(app.DatabaseNames.MES + '.CAT.UpsertGrade', 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.RemoveGrade', QP, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table.length > 0) {
                            var data = data.Table[0];

                            if (data.Id) {
                                if (success != null && _.isFunction(success))
                                    success.call(this, that, data.Id);
                            }
                            else {
                                if (data.Message)
                                    error.call(this, that, data.Message);
                                else
                                    error.call(this, that);
                            }
                        } 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.Collections.GradeChemistry = Backbone.Collection.extend({

        fetch: function (gradeId) {
            var that = this,
                qp = new Core.Database.QueryParameters();
            qp.Add('@gradeId', 'INT', gradeId);


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetGradeChemistry',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var newColl = resp.Table;

                                that.set(newColl).trigger('fetch', that);

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            items: null,
            itemId: null,
            search: '',

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

            gradeName: null,
        },
        initialize: function () {
            this.attributes.gradeGroups = new Screen.Collections.GradeGroups();
            this.attributes.gradeGroups.fetch();
            this.attributes.items = new Screen.Collections.Items();
            this.recipes = this.fetchRecipes();
        },
        fetchRecipes: function () {
            var that = this,
                qp = new Core.Database.QueryParameters();

            var array = [];
            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetScrapRecipes',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                array = 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 array;
        },
    });


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

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


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.GetGradeGroups',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table)) {
                                var newColl = resp.Table;
                                  
                                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: false,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );

            return this;
        },
    });


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

    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: 'grades',
        id: 'grades',
        title: 'Grades',
        //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,

        item: null,
        specsColl: null,
        gradeChemistryColl:null,
        gradeGroupsArray: 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();

            var currModel = this.model.toJSON();
            var array = [];
            _.each(currModel.gradeGroups.toJSON(), function (obj, i) {
                array[i] = [obj.Name, obj.Id];
            });

            var array2 = [];
            array2[0] = ['', null];
            _.each(this.model.recipes.Table, function (obj, i) {
                 i = i + 1;
                array2[i] = [obj.Name, obj.Id];
            });
            this.recipes = array2;

            
            var array3 = [];
            array3[0] = ['', null];
            _.each(this.model.recipes.Table, function (obj, i) {
                 i = i + 1;
                array3[i] = [obj.Name, obj.Name];
            });
            this.recipeNames = array3;

            this.gradeGroupsArray = array;

            this.item = new Grade.Models.Grade();

            this.specsColl = new GradeSpec.Collections.GradeSpecs();

            this.gradeChemistryColl = new Screen.Collections.GradeChemistry();


            this.bindingSources = {
                item: this.item,
            };

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


            this.bindEvents();

        },
        getPermissions: function () {
            var write = $.inArray('mes_config_grades_readWrite', app.models.user.get('roles'));
       
            var ctx = {
                write: write != -1  ? true : false,
            };
            return ctx.write;

        },
        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 + '/';
            that.getPermissions();
            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 editableCell = that.getPermissions();

                            var grid = that.options.itemsGrid = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [
                                    {
                                        name: 'name',
                                        label: app.translate(that, 'name_col'),
                                        editable: editableCell,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell name',
                                        }),
                                    },
                                    {
                                        name: 'groupId',
                                        label: app.translate(that, 'group_col'),
                                        editable: editableCell,
                                        sortable: false,
                                        cell: Backgrid.SelectCell.extend({
                                            optionValues: function () {
                                                return that.gradeGroupsArray;

                                            },
                                            className: 'string-cell align-left-cell groupId',
                                        }) 
                                    },

                                    {
                                        name: 'description',
                                        label: app.translate(that, 'description_col'),
                                        editable: editableCell,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-left-cell description',
                                        })
                                    },
                                     {
                                        name: 'recipeName',
                                        label: app.translate(that, 'recipe_col'),
                                         editable: editableCell,
                                        sortable: false,
                                        cell: Backgrid.SelectCell.extend({
                                            optionValues: function () {
                                                return that.recipeNames;
                                            },
                                            className: 'string-cell align-center-cell',
                                        })
                                    },
                                    {
                                        name: 'active',
                                        label: app.translate(that, 'active_col'),
                                        editable: editableCell,
                                        sortable: false,
                                        cell: 'boolean',
                                    },
                                    {
                                        name: 'actions',
                                        label: '',
                                        editable: editableCell,
                                        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 (!editableCell) {
                                                    btnRemove.addClass('hide');
                                                    btnSave.addClass('hide');
                                                    btnDiscard.addClass('hide');

                                                    return;
                                                }

                                                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) {
                                                        that.actionOnRow(this.model, actionData);
                                                    }
                                                }
                                                catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                                            },
                                        }),
                                    },
                                ],
                                collection: that.model.get('items'),
                                footer: Backgrid.Extension.Infinator.extend({
                                    scrollToTop: false,
                                }),
                            });
                            that.$el.find('.items-grid-container').append(grid.render().el);

                            var grid = that.options.itemsGrid = new Backgrid.Grid({
                                className: 'backgrid table table-hover',
                                columns: [
                                    {
                                        name: 'ElementCode',
                                        label: app.translate(that, 'elementCode_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },

                                    {
                                        name: 'Min',
                                        label: app.translate(that, 'min_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                    {
                                        name: 'Aim',
                                        label: app.translate(that, 'aim_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },

                                    {
                                        name: 'Max',
                                        label: app.translate(that, 'max_col'),
                                        editable: false,
                                        sortable: false,
                                        cell: Backgrid.StringCell.extend({
                                            orderSeparator: '',
                                            className: 'string-cell align-center-cell',
                                        }),
                                    },
                                ],
                                collection: that.gradeChemistryColl,
                            });

                            that.$el.find('.specs-grid-container').append(grid.render().el);

                            //end

                            //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,
                            //    });
                            //}

                            //Call first refresh.
                            that.startAutoRefresh();
                        },
                        true,
                        customPath
                    );
                },
                customPath
            );
        },
        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:search', this.model_change_pickers)
                .listenTo(this.model.get('items'), 'change', this.collection_changed)
                //.listenTo(this.model.get('items'), 'add remove', this.collectionAddRemove)
                .listenTo(this.model.get('items'), 'fetch', this.collection_fetch)
                //.listenTo(this.specsColl, 'fetch', this.specsColl_fetch);
        },

        closeItemEdition: function () {
            this.model.set('itemId', null);
        },
        _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) {
            if (viewParams.sectionParam1)
                viewParams.sectionParam1 = parseInt(viewParams.sectionParam1, 10);
            else
                viewParams.sectionParam1 = Screen.Models.Main.prototype.defaults.itemId;

            this.model.set({
                itemId: viewParams.sectionParam1,
            });
        },
        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);
                this.model.set('itemId', null);
            }

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

            itemsColl.fetch(_.extend(
                opt,
                {
                    params: _.extend(
                        modelAttrs,
                        opt.params,
                        {
                            refresh: opt.refresh,
                            reset: opt.reset,
                        }
                    ),
                }
            ));
        },
        refreshItem: function (options) {
            var opt = _.extend({}, options, { params: {}, });

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


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

            var itemId = (opt.params.id) ? opt.params.id : (modelAttrs.itemId) ? modelAttrs.itemId : null;
            //this.item.fetch({
            //    params: {
            //        id: itemId,
            //    },
            //});

            this.gradeChemistryColl.fetch(itemId)

            //this.specsColl.fetch({
            //    reset: true,
            //    params: {
            //        gradeId: itemId,
            //        gradeVersionId: -1, //To get the current version
            //    },
            //});
        },

        addNew: function () {
            this.model.get('items').unshift({
                id: -1,
                isNew: true,
            });
        },
        discardRow: function (m) {
            //to discard just remove the model from the collection.
            m.collection.remove(m);
        },
        removeRow: function (model) {
            var that = this;
            model.collection.removeItem(
                model.get('id')
                , function (coll, data) {
                    that._refresh();
                }
                , function (coll, msg) {
                    app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                    that._refresh();
                }
            );
        },
        saveRow: function (m) {
            var that = this;
            m.collection.upsertItem(null, [
                { name: 'active', type: 'BIT', value: m.get('active') },
                { name: 'description', type: 'VARCHAR', value: m.get('description') },
                { name: 'name', type: 'VARCHAR', value: m.get('name') },
                { name: 'gradeGroupId', type: 'INT', value: m.get('groupId') },
                //{ name: 'recipeId', type: 'INT', value: Number(m.get('recipeId')) == 0 ? null : Number(m.get('recipeId')) },
                { name: 'recipeName', type: 'VARCHAR(MAX)', value: m.get('recipeName') ? m.get('recipeName') : null },
            ], function (ref, ids) {
                m.set({ id: ids[0], isNew: false }, { avoidSync: true });
                that.model.set('itemId', ids[0]);
                //that._refresh();
            }, function (coll, msg) {
                app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                that._refresh();
            });
        },
        saveDetails: function (options) {
            var that = this,
                itemAttrs = this.item.toJSON(),
                qp = new Core.Database.QueryParameters(),
                opt = _.extend({
                    async: true,
                }, options);

            qp.Add('gradeId', 'INT', itemAttrs.id);

            qp.Add(
                'spec',
                'XML',
                app.jsonArrayToXml(
                    that.specsColl.toJSON(),
                    [].concat(
                        [
                            'typeCode',
                        ],
                        app.chemistryElements
                    )
                )
            );


            Core.Json.CallProcedure(
                app.DatabaseNames.MES + '.CAT.CreateGradeSpec',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if ((resp) && (resp.Table) && (resp.Table.length > 0)) {

                                if (opt.success)
                                    opt.success(resp);
                            }
                            else {
                                var errorMsg = ((resp) && (resp.Message))
                                                            ? resp.Message
                                                            : 'SERVER_RESPONSE_NOT_VALID';
                                console.error(errorMsg);

                                if (opt.error)
                                    opt.error(errorMsg);
                            }
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            console.error(errorMsg);

                            if (opt.error)
                                opt.error(errorMsg);
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    Async: opt.async,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
        },

        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) {
            try {
                var that = this;
                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 'EDIT_DETAILS':
                        this.model.set('itemId', model.get('id'));
                        var items = that.model.get('items');
                        var currGrade = _.findWhere(items.toJSON(), { id: model.get('id') });
                        this.model.set({ gradeName: currGrade.name });
                        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); }
        },
        cancelItemEditionBtn_click: function (e) {
            try {
                this.closeItemEdition();
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        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.collection.upsertItem(m.get('id'), [
                { name: 'active', type: 'BIT', value: m.get('active') },
                { name: 'description', type: 'VARCHAR', value: m.get('description') },
                { name: 'name', type: 'VARCHAR', value: m.get('name') },
                { name: 'gradeGroupId', type: 'INT', value: m.get('groupId') },
                //{ name: 'recipeId', type: 'INT', value: Number(m.get('recipeId')) == 0 ? null : Number(m.get('recipeId')) },
                { name: 'recipeName', type: 'VARCHAR(MAX)', value: m.get('recipeName') ? m.get('recipeName') : null },
                ], function (ref, ids) {
                }, function (coll, msg) {
                    app.views.topMessages.showMessage(app.translate(app, msg), { stay: 10000, });
                    that._refresh();
                });
            }
        },
        collection_fetch: function (coll, resp) {
            try {
                this.model.set({
                    hasData: (this.model.get('items').length > 0),
                    isLoading: false,
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        //collectionAddRemove: function (m, b, c) {
        //    if (m.get('isNew'))
        //        this.model.set('hasData', (this.model.get('items').length > 0));
        //},
        item_fetch: function (model, resp) {
            try {
                this.model.set({
                    isLoadingItemData: false,
                    hasItemData: this.item.get('id'),
                });
            }
            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); }
        },
        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: this.viewParams.section,
                //                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); }
        },
        saveDetailsEditionBtn_click: function (e) {
            try {
                var that = this;

                this.saveDetails({
                    success: function (resp) {
                        try {
                            app.views.topMessages.showMessage(app.translate([that, app], 'SAVED_CHANGES_SUCCESSFUL'), { stay: 5 * 1000, });

                            that.closeItemEdition();

                            that.refreshItemsColl({ refresh: true, });
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    },
                    error: function (errorMsg) {
                        try {
                            app.views.topMessages.showMessage(app.translate([that, app], errorMsg), { stay: 5 * 1000, });
                        }
                        catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                    }
                });
            }
            catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
        },
        specsColl_fetch: function (coll, resp) {
            try {
                if (this.specsColl.length == 0) {                
                    //Add empty data for first version.
                    var idAux = 0;
                    this.specsColl.set([
                        { id: ++idAux, typeCode: 'MIN', },
                        { id: ++idAux, typeCode: 'MAX', },
                        { id: ++idAux, typeCode: 'AIM', },
                    ]);
                }

                this.model.set({
                    isLoadingItemSpecData: false,
                    hasItemSpecData: true,
                });
            }
            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: 'grades-subnavbar-controls',
        title: '',
        template: 'grades',

        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/grades/';

            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.$el.find('.clear-search').clearSearch();

                    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;

});
