//SCREEN-BOILERPLATE

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

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

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

  "modules/modal",

  "handlebars",
  'moment',

  "js/jquery.mask",
],

function (app, T, Modal, Handlebars, moment) {

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

    Screen.Models.Main = Backbone.Epoxy.Model.extend({
        defaults: {
            procedure: '',
            exportConfig: null,
            importConfig: null,
        },
    });    

    //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 "prod-excel-config";
        } catch (Error) { }
    }

    Screen.Models.ExportConfig = Backbone.Epoxy.Model.extend({
        defaults: {
            active: null,
            targetConnectionString: null,
            interval: null,
            //timeout: null,
            lastRunTimestamp: null,
            lastRunMessageCode: null,
            lastRunMessageText: null,
            lastRunStatus: null,
            lastModificationTimestamp: null,
            lastModificationUserName: null,
            userName: null,
            userPassword: null,

            editing: false,
        },
        computeds: {
            intervalFormated: {
                deps: ['interval'],
                get: function (interval) {
                    var h = Math.floor(interval / 3600);
                    var m = Math.floor(interval % 3600 / 60);
                    var s = interval % 60;

                    return ((h < 10) ? '0' + h : h)
                            + ':' + ((m < 10) ? '0' + m : m)
                            + ':' + ((s < 10) ? '0' + s : s);
                },
                set: function (value) {
                    var split = value.split(':');

                    _.each(split, function (item, i) {
                        split[i] = '00'.slice(item.length) + item;
                    });

                    value = split.join(":");

                    value = value + '00:00:00'.slice(value.length);

                    split = value.split(':');

                    return { interval: parseInt(split[0], 10) * 60 * 60 + parseInt(split[1], 10) * 60 + parseInt(split[2], 10), };
                }
            },
        },

        editAttrs: [
            'active',
            'interval',
            'targetConnectionString',
            //'timeout',
            'userName',
            'userPassword',
        ],
        i18n: { global: null, },
        lastFetch: null,

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

            qp.Add('@timeZoneCode', 'CHAR', app.models.user.get('timezoneCode'));

            Core.Json.CallProcedure(
                app.DatabaseNames.OEE + '.WebApp.GetProductionExcelExportConfig',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table) {
                                that.lastFetch = that.parse(resp.Table[0]);

                                var obj = _.extend({}, that.lastFetch);

                                if (that.get('editing') == true) {
                                    _.each(that.editAttrs, function (item) {
                                        delete obj[item];
                                    });
                                }

                                that.set(obj, { from: 'fetch', });
                                that.trigger('fetch', that, resp, opt);

                                if (opt.callback != null && _.isFunction(opt.callback))
                                    opt.callback.call(that, that, resp);
                            }
                            else {
                                console.error('Invalid server response.');
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (options && options.callback && _.isFunction(options.callback))
                                options.callback.call(that, that);

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

            return this;
        },
        parse: function (obj) {
            if (!obj)
                return null;

            var objp = {
                active: obj.Active,
                targetConnectionString: obj.TargetConnectionString,
                interval: obj.Interval,
                //timeout: obj.Timeout,
                lastRunTimestamp: obj.LastRunTimestampString,
                lastRunMessageCode: obj.LastRunMessage,
                lastRunMessageText: app.translate(this, obj.LastRunMessage),
                lastRunStatus: obj.LastRunStatus,
                lastModificationTimestamp: obj.LastModificationTimestampString,
                lastModificationUserName: obj.LastModificationUserName,
                lastRunStatus: (obj.LastRunStatus + '').toUpperCase(),
                userName: obj.Username,
                userPassword: obj.Password,
            };

            return objp;
        },
        cancelEdition: function () {
            this.set(_.extend({ editing: false, }, this.lastFetch));
        },
        confirmEdition: function (opt) {
            var that = this,
                //attrs = this.toJSON(),
                qp = new Core.Database.QueryParameters(),
                attrs = this.toJSON();

            if (!opt) opt = {};

            _.each(that.editAttrs, function (attr) {
                qp.Add('@' + attr, 'VARCHAR', attrs[attr]);
            });

            if (opt.params) {
                for (var pn in opt.params)
                    qp.Add('@' + pn, 'VARCHAR', opt.params[pn]);
            }


            Core.Json.CallProcedure(
                app.DatabaseNames.OEE + '.WebApp.SaveProductionExcelExportConfig',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp) {
                                if (!resp.Message) {
                                    if (resp.Table) {
                                        that.lastFetch = that.parse(resp.Table[0]);

                                        that.set(that.parse(resp.Table[0]), { from: 'fetch', });

                                        if (opt.success) opt.success(that, resp);
                                        that.trigger('fetch', that, resp, opt);
                                    }
                                    else {
                                        console.error('Invalid server response.');

                                        if (opt.error) opt.error(that, resp, 'Invalid server response.');
                                    }
                                }
                                else {
                                    console.error(resp.Message);

                                    if (opt.error) opt.error(this, resp, resp.Message);
                                }
                            }
                            else {
                                console.error('Invalid server response.');

                                if (opt.error) opt.error(this, resp, 'Invalid server response.');
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            console.error(errorMsg);
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    Async: true,
                    Secured: true,
                },
                app.ConnectionStrings.app
            );
            //}

            return this;
        },
    });

    Screen.Models.ImportConfig = Backbone.Epoxy.Model.extend({
        defaults: {
            active: null,
            targetConnectionString: null,
            interval: null,
            //timeout: null,
            lastRunTimestamp: null,
            lastRunMessageCode: null,
            lastRunMessageText: null,
            lastRunStatus: null,
            lastModificationTimestamp: null,
            lastModificationUserName: null,
            userName: null,
            userPassword: null,

            editing: false,
        },
        computeds: {
            intervalFormated: {
                deps: ['interval'],
                get: function (interval) {
                    var h = Math.floor(interval / 3600);
                    var m = Math.floor(interval % 3600 / 60);
                    var s = interval % 60;

                    return ((h < 10) ? '0' + h : h)
                            + ':' + ((m < 10) ? '0' + m : m)
                            + ':' + ((s < 10) ? '0' + s : s);
                },
                set: function (value) {
                    var split = value.split(':');

                    _.each(split, function (item, i) {
                        split[i] = '00'.slice(item.length) + item;
                    });

                    value = split.join(":");

                    value = value + '00:00:00'.slice(value.length);

                    split = value.split(':');

                    return { interval: parseInt(split[0], 10) * 60 * 60 + parseInt(split[1], 10) * 60 + parseInt(split[2], 10), };
                }
            },
        },

        editAttrs: [
            'active', 
            'interval', 
            'targetConnectionString',
            //'timeout',
            'userName',
            'userPassword',
        ],
        i18n: { global: null, },
        lastFetch: null,

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

            qp.Add('@timeZoneCode', 'CHAR', app.models.user.get('timezoneCode'));

            Core.Json.CallProcedure(
                app.DatabaseNames.OEE + '.WebApp.GetProductionExcelImportConfig',
                qp,
                {
                    onSuccess: function (resp) {
                        try {
                            if (resp && resp.Table) {
                                that.lastFetch = that.parse(resp.Table[0]);

                                var obj = _.extend({}, that.lastFetch);

                                if (that.get('editing') == true) {
                                    _.each(that.editAttrs, function (item) {
                                        delete obj[item];
                                    });
                                }

                                that.set(obj, { from: 'fetch', });
                                that.trigger('fetch', that, resp, opt);

                                if (opt.callback != null && _.isFunction(opt.callback))
                                    opt.callback.call(that, that, resp);
                            }
                            else {
                                console.error('Invalid server response.');
                            }
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    onError: function (errorMsg) {
                        try {
                            if (options && options.callback && _.isFunction(options.callback))
                                options.callback.call(that, that);

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

            return this;
        },
        parse: function (obj) {
            if (!obj)
                return null;

            var objp = {
                active: obj.Active,
                targetConnectionString: obj.TargetConnectionString,
                interval: obj.Interval,
                //timeout: obj.Timeout,
                lastRunTimestamp: obj.LastRunTimestampString,
                lastRunMessageCode: obj.LastRunMessage,
                lastRunMessageText: app.translate(this, obj.LastRunMessage),
                lastRunStatus: obj.LastRunStatus,
                lastModificationTimestamp: obj.LastModificationTimestampString,
                lastModificationUserName: obj.LastModificationUserName,
                lastRunStatus: (obj.LastRunStatus + '').toUpperCase(),
                userName: obj.Username,
                userPassword: obj.Password,
            };

            return objp;
        },
        cancelEdition: function () {
            this.set(_.extend({ editing: false, }, this.lastFetch));
        },
        confirmEdition: function (opt) {
            var that = this,
                //attrs = this.toJSON(),
                qp = new Core.Database.QueryParameters(),
                attrs = this.toJSON();

            if (!opt) opt = {};

            _.each(that.editAttrs, function (attr) {
                qp.Add('@' + attr, 'VARCHAR', attrs[attr]);
            });

            if (opt.params) {
                for (var pn in opt.params)
                    qp.Add('@' + pn, 'VARCHAR', opt.params[pn]);
            }
                

            //if (opt.params) {
            //    for (var pn in opt.params)
            //        qp.Add('@' + pn, 'VARCHAR', opt.params[pn]);

                //qp.Add('@active', 'BIT', attrs.active);
                //qp.Add('@targetConnectionString', 'VARCHAR', attrs.targetConnectionString);
                //qp.Add('@interval', 'INT', attrs.interval);
                //qp.Add('@timeout', 'INT', attrs.timeout);

                Core.Json.CallProcedure(
                    app.DatabaseNames.OEE + '.WebApp.SaveProductionExcelImportConfig',
                    qp,
                    {
                        onSuccess: function (resp) {
                            try {
                                if (resp) {
                                    if (!resp.Message) {
                                        if (resp.Table) {
                                            that.lastFetch = that.parse(resp.Table[0]);

                                            that.set(that.parse(resp.Table[0]), { from: 'fetch', });

                                            if (opt.success) opt.success(that, resp);
                                            that.trigger('fetch', that, resp, opt);
                                        }
                                        else {
                                            console.error('Invalid server response.');

                                            if (opt.error) opt.error(that, resp, 'Invalid server response.');
                                        }
                                    }
                                    else {
                                        console.error(resp.Message);

                                        if (opt.error) opt.error(this, resp, resp.Message);
                                    }
                                }
                                else {
                                    console.error('Invalid server response.');

                                    if (opt.error) opt.error(this, resp, 'Invalid server response.');
                                }
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        onError: function (errorMsg) {
                            try {
                                console.error(errorMsg);
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        },
                        Async: true,
                        Secured: true,
                    },
                    app.ConnectionStrings.app
                );
            //}

            return this;
        },
    });


    Screen.Views.Main = Backbone.Epoxy.View.extend({
        template: "prod-excel-config"
        , id: "prod-excel-config"
        , title: "Configuración de Importación de Excel de Producción"
        //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
        , askBeforeCloseOpt: {
            title: null,
            message: null,
        }
        , bindings: 'data-bind'
        , events: function () {
            return {
                'click #clearAdditionalImportedDataBtn': this.clearAdditionalImportedDataBtn_click,
            };
        }

        , beforeClose: function () {
            //if (!this.askBeforeCloseOpt.title || !this.askBeforeCloseOpt.message) {
            //    this.askBeforeCloseOpt.title = this.options.i18n[this.template].translate("unsaved_changes_modal_title").fetch();
            //    this.askBeforeCloseOpt.message = this.options.i18n[this.template].translate("unsaved_changes_modal_message").fetch();
            //}

            //return true; 
        }
        , bindEvents: function () {

        }
        , clearAdditionalImportedData: function (options) {
            var that = this,
                opt = _.extend({}, options);

            var modal = new Modal.Views.Main({
                focusOk: false,
                focusSelector: '#btn-cancel',
                title: app.translate([this, app], "clear_additional_imported_data_modal_confirm_title"),
                message: app.translate([this, app], "clear_additional_imported_data_modal_confirm_message"),
                buttons_type: "CONTINUE-CANCEL"
            });

            modal.on("continue", function () {
                try {
                    Core.Json.CallProcedure(
                        app.DatabaseNames.OEE + '.WebApp.ClearProductionAdditionalDataImported',
                        null,
                        {
                            onSuccess: function (resp) {
                                try {
                                    if (resp && !resp.Message) {
                                        if (opt.success != null && _.isFunction(opt.success))
                                            opt.success();
                                    } else {
                                        var errorMsg = (resp && resp.Message)
                                                            ? resp.Message
                                                            : "SERVER_RESPONSE_NOT_VALID"

                                        if (opt.error != null && _.isFunction(opt.error))
                                            opt.error(resp.Message);

                                        console.error(errorMsg);
                                    }
                                }
                                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                            },
                            onError: function (errorMsg) {
                                try {
                                    if (opt.error != null && _.isFunction(opt.error))
                                        opt.error(errorMsg);

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

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

            _.bindAll(this);

            if (this.options.viewParams) {
            }

            var model = new Screen.Models.Main({
                exportConfig: new Screen.Models.ExportConfig(),
                importConfig: new Screen.Models.ImportConfig(),
            });

            this.model = model;

            this.options.MYREFERENCES = {
                autoRefresh: {
                    enabled: false
                    , toid: null
                }
                , subviews: {

                }
                , isRefreshing: false

                //, requireLockColumns: ["enabled", "scanRate"]
            };
        }
        , render: function (container) {
            var that = this;
            var thatContainer = (container != null && container != undefined) ? container : this.options.container;

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

            T.render.call(this, this.template, function (tmp) {

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

                    that.model.get('exportConfig').i18n.global = i18nJED;
                    that.model.get('importConfig').i18n.global = i18nJED;

                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)                   


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

                    //if (ctx.editable == false) app.views.topMessages.showMessage("Solo lectura.", { stay: 5000 }); 

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

                    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.bindEvents();

                    
                    var exportCfgView = new Screen.Views.GeneralExportConfig({
                        model: that.model.get('exportConfig'),
                        el: that.$el.find('#generalExportCfgContainer'),
                        parent: that,
                    });
                    exportCfgView.render();

                    var importCfgView = new Screen.Views.GeneralImportConfig({
                        model: that.model.get('importConfig'),
                        el: that.$el.find('#generalImportCfgContainer'),
                        parent: that,
                    });
                    importCfgView.render();

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

                    that._startAutoRefresh();

                    //end
                }, true, customPath); 

            }, customPath);
        }
        , _startAutoRefresh: function (options) {
            try {
                var that = this;
                if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                    clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                    this.options.MYREFERENCES.autoRefresh.toid = null;
                }
                this.options.MYREFERENCES.autoRefresh.enabled = true;
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(function () { that._autoRefresh(options); }, 1);
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
        , _autoRefresh: function (options) {
            var that = this;
            options = options || {};

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

            //do not autorefresh if refreshing already
            if (!this.options.MYREFERENCES.isRefreshing) {
                this.refresh(options);
            }

            if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
                //refresh every one minute to avoid annoying freeze
                var autorefresh = function () { that._autoRefresh({ auto: true }); };
                //this.options.MYREFERENCES.autoRefresh.toid = setTimeout(autorefresh, (1000 * 60));
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(autorefresh, 5000);
            }
        }
        , _stopAutoRefresh: function () {
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }
            this.options.MYREFERENCES.autoRefresh.enabled = false;
        }
        , refresh: function (opt) {
            try {
                this.options.MYREFERENCES.isRefreshing = true;

                var that = this;

                //Fetch general exporation config
                this.model.get('exportConfig').fetch({
                    callback: function (model, data) {
                        try {
                            that.options.MYREFERENCES.isRefreshing = false
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                });

                //Fetch general imporation config
                this.model.get('importConfig').fetch({
                    callback: function (model, data) {
                        try {
                            that.options.MYREFERENCES.isRefreshing = false
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                });
            }
            catch (e) {
                that.options.MYREFERENCES.isRefreshing = false

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

        , 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;
            }
        }
        , bindViewScopedEvents: function () {

        }
        , unbindViewScopedEvents: function () {
            this._stopAutoRefresh(); 
        }
        , close: function () {
            this.options.state = app.view_states.closed;

            this._stopAutoRefresh();

            this.closeSubviews();
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }
        , closeSubviews: function () {
            _.each(this.options.MYREFERENCES.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.options.MYREFERENCES.subviews, function (sview) {
                sview.show();
            });
        }
        , hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews(); 
            this.$el.hide();
            this.unbind();
            this.stopListening();
        }
        , hideSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.hide(); 
            }); 
        }
        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
            app.models.subnavbar.set("notificationBar", false);
            app.models.subnavbar.set("dateTimeScopeControl", false); 
            app.models.subnavbar.set("subnavbar", false);
            //app.models.subnavbar.set("sections", "6-6"); 
        }
        , remove: function () {
            this.removeBindings();
            this.$el.remove();
            this.stopListening();
            return this;
        }
        , reRender: function () {
        }

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

                this.clearAdditionalImportedData({
                    success: function () {
                        try {
                            app.views.topMessages.showMessage(app.translate([that, app], 'DATA_CLEAR_SUCCESSFUL'), { stay: 5 * 1000, });
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    error: function (errorMsg) {
                        try {
                            app.views.topMessages.showMessage(app.translate([that, app], errorMsg), { stay: 5 * 1000, });
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                });
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        }
    });

    Screen.Views.GeneralExportConfig = Backbone.Epoxy.View.extend({
        id: "prod-excel-config-general-export-config",
        template: "prod-excel-config",
        bindings: 'data-bind',

        //exportModal: null,
        parent: null,

        events: function () {
            return {
                'blur #intervalTbx': this.intervalTbx_blur,
                //'blur #timeoutTbx': this.timeoutTbx_blur,
                'click #cancelGeneralCfgBtn': this.cancelGeneralCfgBtn_click,
                //'click #editGeneralCfgBtn': this.editGeneralCfgBtn_click,
                'click #saveGeneralCfgBtn': this.saveGeneralCfgBtn_click,
                //'click #testConnectionBtn': this.testConnectionBtn_click,
                //'click .toggleExportCfgBtn': this.toggleExportCfgBtn_click,
            };
        },

        initialize: function () {
            //this.listenTo(this.model, 'change', this.model_change);

            this.parent = this.options.parent;
        },

        render: function () {
            var that = this;

            var customPath = "/app/custom-screens/modules/OEE/OEEConfiguration/" + this.template + "/";

            T.render.call(this, this.template, function (tmp) {

                that.$el.html(tmp());

                that.applyBindings();

                that.$el.find('#intervalTbx').mask('00:00:00');
                //that.$el.find('#intervalTbx, #timeoutTbx').mask('00:00:00');

            }, customPath, "generalExportConfigTemplate");
        },

        cancelGeneralCfgBtn_click: function (e) {
            try {
                this.model.cancelEdition();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        //editGeneralCfgBtn_click: function (e) {
        //    try {
        //        this.parent.$el.find('.exportCfgCollapse').toggle(true);
        //        this.parent.$el.find('.exportCfgExpand').toggle(false);
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
        intervalTbx_blur: function (e) {
            try {
                this.model.set('intervalFormated', $(e.target).val());
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        saveGeneralCfgBtn_click: function (e) {
            try {
                var that = this;

                this.model.confirmEdition({
                    success: function (model, resp) {
                        try {
                            that.model.set('editing', false);
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    error: function (model, resp, msg) {
                        try {
                            app.views.topMessages.showMessage(app.translate(that.parent, msg), { stay: 10000, });
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                });
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        //TODO ? - Check if user credentials and remote file paths are valid.
        //testConnectionBtn_click: function (e) {
        //    try {
        //        var that = this;

        //        var btn = $(e.target).button('loading');

        //        var fn_modal_shown = function (e) {
        //            try {
        //                btn.button('reset');
        //            }
        //            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //        }

        //        $.ajax({
        //            url: '/wcf/tagsExport/' + 'TestConnection',
        //            //dataType: 'json',
        //            contentType: 'application/json',
        //            method: 'POST',
        //            data: JSON.stringify({
        //                ConnectionString: this.model.get('targetConnectionString'),
        //                TargetType: 0, //Oracle 11g
        //            }),
        //            success: function (resp) {
        //                try {
        //                    var msg;

        //                    if (resp && resp.Success == true) {
        //                        var msg = (resp.Data)
        //                                    ? resp.Data
        //                                    : 'test_connection_modal_success_message';
        //                    }
        //                    else {
        //                        msg = 'test_connection_modal_error_message';
        //                    }

        //                    var modal = new Modal.Views.Main({
        //                        title: app.translate(that.parent, 'test_connection_modal_title'),
        //                        message: app.translate(that.parent, msg),
        //                        buttons_type: 'OK',
        //                    });

        //                    that.listenTo(modal, 'shown', fn_modal_shown);

        //                    modal.show();
        //                }
        //                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //            },
        //            error: function (errorMsg) {
        //                try {
        //                    var modal = new Modal.Views.Main({
        //                        title: app.translate(that.parent, 'test_connection_modal_title'),
        //                        message: app.translate(that.parent, 'test_connection_modal_error_message'),
        //                        buttons_type: 'OK',
        //                    });

        //                    that.listenTo(modal, 'shown', fn_modal_shown);

        //                    modal.show();
        //                }
        //                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //            },
        //            async: true,
        //        });
        //    }
        //    catch (Error) {
        //        console.error(Error);

        //        btn.button('reset');
        //    }
        //},
        //timeoutTbx_blur: function (e) {
        //    try {
        //        this.model.set('timeoutFormated', $(e.target).val());
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
        //toggleExportCfgBtn_click: function (e) {
        //    try {
        //        this.parent.$el.find('.exportCfgCollapse, .exportCfgExpand').toggle();
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
    });

    Screen.Views.GeneralImportConfig = Backbone.Epoxy.View.extend({
        id: "prod-excel-config-general-import-config",
        template: "prod-excel-config",
        bindings: 'data-bind',

        //importModal: null,
        parent: null,

        events: function () {
            return {
                'blur #intervalTbx': this.intervalTbx_blur,
                //'blur #timeoutTbx': this.timeoutTbx_blur,
                'click #cancelGeneralCfgBtn': this.cancelGeneralCfgBtn_click,
                //'click #editGeneralCfgBtn': this.editGeneralCfgBtn_click,
                'click #saveGeneralCfgBtn': this.saveGeneralCfgBtn_click,
                //'click #testConnectionBtn': this.testConnectionBtn_click,
                //'click .toggleImportCfgBtn': this.toggleImportCfgBtn_click,
            };
        },

        initialize: function () {
            //this.listenTo(this.model, 'change', this.model_change);

            this.parent = this.options.parent;
        },

        render: function () {
            var that = this;

            var customPath = "/app/custom-screens/modules/OEE/OEEConfiguration/" + this.template + "/";

            T.render.call(this, this.template, function (tmp) {

                that.$el.html(tmp());

                that.applyBindings();

                that.$el.find('#intervalTbx').mask('00:00:00');
                //that.$el.find('#intervalTbx, #timeoutTbx').mask('00:00:00');

            }, customPath, "generalImportConfigTemplate");
        },

        cancelGeneralCfgBtn_click: function (e) {
            try {
                this.model.cancelEdition();
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        //editGeneralCfgBtn_click: function (e) {
        //    try {
        //        this.parent.$el.find('.importCfgCollapse').toggle(true);
        //        this.parent.$el.find('.importCfgExpand').toggle(false);
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
        intervalTbx_blur: function(e) {
            try {
                this.model.set('intervalFormated', $(e.target).val());
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        saveGeneralCfgBtn_click: function (e) {
            try {
                var that = this;

                this.model.confirmEdition({
                    success: function (model, resp) {
                        try {
                            that.model.set('editing', false);
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                    error: function (model, resp, msg) {
                        try {
                            app.views.topMessages.showMessage(app.translate(that.parent, msg), { stay: 10000, });
                        }
                        catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                    },
                });
            }
            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        },
        //TODO ? - Check if user credentials and remote file paths are valid.
        //testConnectionBtn_click: function (e) {
        //    try {
        //        var that = this;

        //        var btn = $(e.target).button('loading');

        //        var fn_modal_shown = function (e) {
        //            try {
        //                btn.button('reset');
        //            }
        //            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //        }

        //        $.ajax({
        //            url: '/wcf/tagsImport/' + 'TestConnection',
        //            //dataType: 'json',
        //            contentType: 'application/json',
        //            method: 'POST',
        //            data: JSON.stringify({
        //                ConnectionString: this.model.get('targetConnectionString'),
        //                TargetType: 0, //Oracle 11g
        //            }),
        //            success: function (resp) {
        //                try {
        //                    var msg;

        //                    if (resp && resp.Success == true) {
        //                        var msg = (resp.Data)
        //                                    ? resp.Data
        //                                    : 'test_connection_modal_success_message';
        //                    }
        //                    else {
        //                        msg = 'test_connection_modal_error_message';
        //                    }

        //                    var modal = new Modal.Views.Main({
        //                        title: app.translate(that.parent, 'test_connection_modal_title'),
        //                        message: app.translate(that.parent, msg),
        //                        buttons_type: 'OK',
        //                    });

        //                    that.listenTo(modal, 'shown', fn_modal_shown);

        //                    modal.show();
        //                }
        //                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //            },
        //            error: function (errorMsg) {
        //                try {
        //                    var modal = new Modal.Views.Main({
        //                        title: app.translate(that.parent, 'test_connection_modal_title'),
        //                        message: app.translate(that.parent, 'test_connection_modal_error_message'),
        //                        buttons_type: 'OK',
        //                    });

        //                    that.listenTo(modal, 'shown', fn_modal_shown);

        //                    modal.show();
        //                }
        //                catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //            },
        //            async: true,
        //        });
        //    }
        //    catch (Error) {
        //        console.error(Error);

        //        btn.button('reset');
        //    }
        //},
        //timeoutTbx_blur: function (e) {
        //    try {
        //        this.model.set('timeoutFormated', $(e.target).val());
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
        //toggleImportCfgBtn_click: function (e) {
        //    try {
        //        this.parent.$el.find('.importCfgCollapse, .importCfgExpand').toggle();
        //    }
        //    catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
        //},
    });

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

});
