/// <reference path="http://localhost:65492/IndustrialDashboard/Scripts/IndustrialDashboard-debug.js" />
//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",

  "backgrid",

  "handlebars", 

  "backgrid/select-all",

  "custom-assets/IndustrialGridEditableGeneric/Scripts/IndustrialGridEditableGeneric", 

  "js/jqBootstrapValidation/jqBootstrapValidation",
],

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

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

    DataSourcesConfiguration.Models.Main = Backbone.Model.extend({
        defaults: {
            procedure: '',
            dashes: null, 
        }
    });

    DataSourcesConfiguration.Models.Dash = Backbone.Model.extend({
        defaults: {
            id: null, 
            name: null,
            friendlyName: null,
            lastContactTime: null,
            hostName: null,
            ipAddress: null, 
            type: null,
            typeExtended: null,
            server: null,
            status: null,
            agentConnected: null, 
            systemType: null,
            systemTypeClass: null,
            systemCustomData: null,
            enabled: null,
            registered: null,
            address: null,
            local: null,
            hasDOTS: false,
            //removing: false, 
        }

        //@@overrides
        //overriding get and set method to allow custom getters/setters
        , get: function (attr) {
            // Call the getter if available
            if (_.isFunction(this.getters[attr])) {
                return this.getters[attr].call(this);
            }

            return Backbone.Model.prototype.get.call(this, attr);
        },
        set: function (key, value, options) {
            var attrs, attr;

            // Normalize the key-value into an object
            if (_.isObject(key) || key == null) {
                attrs = key;
                options = value;
            } else {
                attrs = {};
                attrs[key] = value;
            }

            // always pass an options hash around. This allows modifying
            // the options inside the setter
            options = options || {};

            // Go over all the set attributes and call the setter if available
            for (attr in attrs) {
                if (_.isFunction(this.setters[attr])) {
                    attrs[attr] = this.setters[attr].call(this, attrs[attr], options);
                }
            }

            return Backbone.Model.prototype.set.call(this, attrs, options);
        },
        getters: {
            local: function () {
                var name = this.attributes["name"];
                if (name.indexOf("AGENTLOCAL") != -1) {
                    return true; 
                }
                return false; 
            },
        },
        setters: {
        },
    }); 

    DataSourcesConfiguration.Collections.Dashes = Backbone.Collection.extend({
        model: DataSourcesConfiguration.Models.Dash,
        fetch: function (e) {
            var that = this;
            var QP = new Core.Database.QueryParameters();
            QP.Add('@TimeZone', 'CHAR', app.models.user.get("timezoneCode")); 

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.GetDataSourcesConfiguration", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        data = data.Table;

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

                            var dash = data[i];
                            var dashModel = new DataSourcesConfiguration.Models.Dash({
                                id: dash.Id,
                                name: dash.Name,
                                friendlyName: dash.FriendlyName,
                                lastContactTime: dash.LastContactTime,
                                hostName: dash.HostName,
                                ipAddress: dash.IPAddress, 
                                type: dash.Type,
                                typeExtended: dash.Name.substring(0, 3),
                                server: dash.Server,
                                status: dash.Status,
                                agentConnected: dash.AgentConnected, 
                                systemType: dash.SystemType,
                                systemTypeClass: dash.SystemTypeClass,
                                systemCustomData: dash.SystemCustomData, 
                                enabled: dash.Enabled,
                                registered: dash.Registered,
                                address: dash.DataSourceAddress,
                                hasDOTS: dash.HasDOTS, 
                            });

                            //CHECK, this should be deleted on future version and add a new custom type
                            //on the agent code itself.
                            if (dashModel.get('name').indexOf('OEEAGENTLOCAL') != -1) {
                                dashModel.set('type', 'CUSTOM');
                                dashModel.set('systemType', 'CUSTOM');
                            }

                            dashModels.push(dashModel);
                        }

                        that.set(dashModels, { from: "fetch" });
                    }
                }
            }, app.ConnectionStrings.app);

        }
    });

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

    DataSourcesConfiguration.Views.Main = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "data-sources-configuration"
        , title: "Fuentes de Datos"
        //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
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            if (this.options.viewParams) {
            }

            var model = new DataSourcesConfiguration.Models.Main({
                procedure: "dbo.procedureName",
                dashes: new DataSourcesConfiguration.Collections.Dashes(), 
            });

            this.options.MYREFERENCES = {
                autoRefresh: {
                    enabled: true
                    , toid: null
                }
                , editing: false                
            };

            this.model = model;

            this.bindEvents();
            _.bindAll(this);
        },

        events: {            
        }, 

        render: function (container) {
            var that = this;
            var thatContainer = (container != null && container != undefined) ? container : this.options.container;
            this.options.MYREFERENCES.subviews = {};
            //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/IHConfiguration/data-sources-configuration-v2/";

            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;
                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)

                    //end:

                    var ctx = {
                        editable: app.models.securityManager.getModuleActionValue("ihconfiguration_data_sources", "write"),
                    };

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

                    //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.options.MYREFERENCES.subviews.subnavbarControls = new DataSourcesConfiguration.Views.SubnavBarControls({
                        parent: that
                        , container: app.views.subnavbar.getSectionContainer(1, 12)
                    });

                    var ConfigureSourceCell = Backgrid.Cell.extend({
                        template: Handlebars.compile(that.$el.find("script#configure_cell_template").html()),
                        events: {
                            "click .btn-dropdown-config-option": "configure_dropdown_config_opt_click",
                            "click .btn-dropdown-action-option": "configure_dropdown_action_opt_click",
                        },
                        initialize: function () {
                            Backgrid.Cell.prototype.initialize.apply(this, arguments);

                            //creating new locked attr on column
                            this.model.set("locked", false); 

                            this.locksChanged();

                            _.bindAll(this);
                            this.bindEvents();
                        }, 
                        render: function () {
                            Backgrid.Cell.prototype.render.apply(this, arguments);

                            var id = this.model.get('id');
                            var type = this.model.get("systemType");
                            var typeExtended = this.model.get("typeExtended");
                            var typeClass = this.model.get("systemTypeClass");
                            var enabled = this.model.get("enabled");
                            var registered = this.model.get("registered"); 
                            var locked = this.model.get("locked");
                            var connected = this.model.get("agentConnected"); 
                            var local = this.model.get("local");
                            var status = this.model.get("status");
                            var hasDOTS = this.model.get("hasDOTS"); 

                            this.$el.html(this.template({
                                id: id,
                                enabled: enabled,
                                registered: registered, 
                                type: type,
                                typeExtended: typeExtended,
                                typeClass: typeClass, 
                                locked: locked,
                                connected: connected,
                                local: local,
                                status: status,
                                hasDOTS: hasDOTS, 
                            }));

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

                            if (!ctx.editable) {
                                this.$el.find(".configure-source-btn").attr("disabled", true);
                            }

                            this.checkAnyOptions(); 
                            this._customDataChanged();
                            this.delegateEvents();
                            return this;
                        },
                        checkAnyOptions: function () {
                            var actionSourceBtn = this.$el.find(".action-source-btn"); 
                            if (this.$el.find(".action-source-dropdown").find("li").length > 0) {
                                actionSourceBtn.attr("disabled", false);
                            } else {
                                actionSourceBtn.attr("disabled", true);
                            }
                        }, 
                        configure_dropdown_config_opt_click: function (e) {
                            e.preventDefault();
                            if (!$(e.target).hasClass("disabled-link")) {
                                that.configureSource(this.model, { option: $(e.target).data("option") });
                            }
                        },
                        configure_dropdown_action_opt_click: function (e) {
                            e.preventDefault();
                            if (!$(e.target).hasClass("disabled-link")) {
                                that.actionOnSource(this.model, { option: $(e.target).data("option") });
                            }
                        },

                        bindEvents: function () {
                            if (this.model.get("systemType") == "PLC") {
                                this.listenTo(this.model, "change:systemCustomData", this._customDataChanged);
                            }

                            this.listenTo(this.model, "change:enabled change:registered change:agentConnected", this.render);
                            this.listenTo(this.model, "change:locked", this.render);

                            //listening to all locks except for agent disconnected
                            app.models.locksManager.listenToCategory(
                                this,
                                ["add", "remove"],
                                ["TAGSCONFIGCHANGE", "SETPLCADDRESS", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                                this.locksChanged
                            );
                        },
                        locksChanged: function () {
                            var id = this.model.get("id"); 
                            if (id && !isNaN(id)) {
                                id = parseInt(id); 
                                var locks = app.models.locksManager.getCategoryLocks(
                                    ["TAGSCONFIGCHANGE", "SETPLCADDRESS", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                                    id, true
                                );

                                this.model.set("locked", (locks.length > 0));
                            }
                        }, 
                        _customDataChanged: function () {
                            if (this.model.get("systemType") == "PLC") {
                                switch (this.model.get("systemCustomData").toUpperCase()) {
                                    case "NO_DBS_SYNCED":
                                        this.$el.find(".plc-option-mnemonic-import").addClass("disabled-link");
                                        this.$el.find(".plc-option-mnemonic-import").popover({
                                            trigger: "hover",
                                            html: true,
                                            content: that.options.i18n[that.template].translate("import_mnemonics_select_dbs_first_popover_msg").fetch(),
                                            placement: "left",
                                            container: 'body',
                                        });
                                        break;
                                    case "DBS_SYNCED":
                                        this.$el.find(".plc-option-mnemonic-import").removeClass("disabled-link");
                                        this.$el.find(".plc-option-mnemonic-import").popover('destroy');
                                        break;
                                }
                            }
                        },
                    });

                    var SourceStatusCell = Backgrid.Cell.extend({
                        template: _.template("<div class='status-container'></div>"),
                        initialize: function () {
                            Backgrid.Cell.prototype.initialize.apply(this, arguments);
                            this.bindEvents(); 
                        }, 
                        render: function () {
                            var status = this.model.get("status");
                            var registered = this.model.get("registered");

                            this.$el.html(this.template());

                            var statusSpan = $("<span></span>"); 

                            if (registered) {
                                switch (status) {
                                    case "CHANGINGOPCSERVER":
                                        statusSpan.text(that.options.i18n[that.template].translate("changing_opc_server_status").fetch());
                                        break;
                                    case "CHANGINGPLCSERVER":
                                        statusSpan.text(that.options.i18n[that.template].translate("changing_plc_server_status").fetch());
                                        break;
                                    case "PENDINGREGISTRATION":
                                        statusSpan.text(that.options.i18n[that.template].translate("pending_registration_status").fetch());
                                        break;
                                    case "UNREGISTERED":
                                        statusSpan.text(that.options.i18n[that.template].translate("unregistered_status").fetch());
                                        break;
                                    case "CONNECTED":
                                        statusSpan.text(that.options.i18n[that.template].translate("connected_status").fetch());
                                        break;
                                    case "DISCONNECTED":
                                        statusSpan.text(that.options.i18n[that.template].translate("disconnected_status").fetch());
                                        break;
                                    case "MISSING":
                                        statusSpan.text(that.options.i18n[that.template].translate("missing_status").fetch());
                                        break;
                                }
                            } else {
                                statusSpan.text(that.options.i18n[that.template].translate("unregistered_status").fetch());
                            }

                            this.$el.find(".status-container").append(statusSpan); 
                            this.delegateEvents();
                            return this;
                        },
                        bindEvents: function () {
                            this.listenTo(this.model, "change:registered", this.render); 
                        }, 
                    }); 

                    var AgentStatusCell = Backgrid.Cell.extend({
                        template: _.template("..."),
                        initialize: function () {
                            Backgrid.Cell.prototype.initialize.apply(this, arguments);
                            this.bindEvents(); 
                        }, 
                        render: function () {
                            var status = this.model.get("agentConnected");
                            var registered = this.model.get("registered"); 

                            var connected_template = _.template('<div class="status-icon-container" ><i style="color: #00ff00;font-size:22px; cursor:default; " class="fa fa-check"></i></div>');
                            var disconnected_template = _.template('<div class="status-icon-container" ><i style="color: #ff0000;font-size:22px; cursor:default;" class="fa fa-close"></i></div>');
                            var unregistered_template = _.template('<div class="status-icon-container" ><i style="color: #000000;font-size:22px; cursor:default;" class="fa fa-circle-thin"></i></div>');

                            var status_message = "";
                            if (registered) {
                                switch (status) {
                                    case true:
                                        this.template = connected_template;
                                        status_message = that.options.i18n[that.template].translate("agent_connected_icon_message").fetch();
                                        break;
                                    case false:
                                        this.template = disconnected_template;
                                        status_message = that.options.i18n[that.template].translate("agent_disconnected_icon_message").fetch();
                                        break;
                                }
                            } else {
                                this.template = unregistered_template;
                                status_message = that.options.i18n[that.template].translate("agent_unregistered_icon_message").fetch();
                            }

                            this.$el.html(this.template());

                            this.$el.find(".status-icon-container").popover({
                                trigger: "hover",
                                html: true,
                                content: status_message,
                                placement: "top",
                            });

                            this.delegateEvents();
                            return this;
                        },
                        bindEvents: function () {
                            this.listenTo(this.model, "change:registered", this.render);
                        }, 
                    });

                    var columns = [
                    {
                        name: "name",
                        label: that.options.i18n[that.template].translate("name_col_label").fetch(),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            orderSeparator: '',
                            className: "string-cell align-center-cell",
                        })
                    }
                    , {
                        name: "agentConnected",
                        editable: false,
                        label: "",
                        cell: AgentStatusCell,
                    }
                    , {
                        name: "friendlyName",
                        editable: ctx.editable,
                        label: that.options.i18n[that.template].translate("friendlyName_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "lastContactTime",
                        editable: false,
                        label: that.options.i18n[that.template].translate("lastContactTime_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "hostName",
                        editable: false,
                        label: that.options.i18n[that.template].translate("hostName_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "ipAddress",
                        editable: false,
                        label: that.options.i18n[that.template].translate("ipAddress_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "type",
                        editable: false,
                        label: that.options.i18n[that.template].translate("type_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "server",
                        editable: false,
                        label: that.options.i18n[that.template].translate("server_col_label").fetch(),
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    }
                    , {
                        name: "status",
                        editable: false,
                        label: that.options.i18n[that.template].translate("status_col_label").fetch(),
                        //cell: Backgrid.StringCell.extend({
                        //    className: "string-cell align-center-cell"
                        //})
                        cell: SourceStatusCell
                    }
                    , {
                        name: "configure",
                        label: "",
                        sortable: false,
                        editable: false,
                        renderable: (_.isBoolean(ctx.editable)) ? ctx.editable : false, 
                        headerCell: Backgrid.HeaderCell.extend({
                            className: "configuretd", 
                        }), 
                        cell: ConfigureSourceCell, 
                    }
                    , {
                        name: "enabled",
                        editable: false,
                        renderable: false, 
                        cell: "boolean"
                    }
                    ];

                    var CustomRow = Backgrid.Row.extend({
                        initialize: function () {
                            Backgrid.Row.prototype.initialize.apply(this, arguments);

                            _.bindAll(this); 
                            this.bindEvents(); 
                        }, 
                        render: function () {
                            CustomRow.__super__.render.apply(this, arguments);

                            var agentsHaveDbConflcits = app.models.datablocksConflicts.get("hasConflicts"),
                                agentsDbConflicts = app.models.datablocksConflicts.get("conflicts"),
                                agentId = this.model.get("id");
                            var type = this.model.get("systemType");
                            var status = this.model.get("status"); 

                            if ((!agentsHaveDbConflcits) || (agentsDbConflicts.where({ agentId: agentId, }).length == 0))
                                this.$el.removeClass("error");
                            else
                                this.$el.addClass("error");

                            if (!this.model.get("enabled")) {
                                this.$el.addClass("disabled-ds-status");
                            } else {
                                this.$el.removeClass("disabled-ds-status");
                            }

                            if (type == "DASH") {
                                if (status == "UNREGISTERED") {
                                    this.$el.addClass("disconnected-dash-ds-status");
                                } else {
                                    this.$el.removeClass("disconnected-dash-ds-status");
                                }

                                if (status == "MISSING") {
                                    this.$el.addClass("missing-dash-ds-status");
                                }else{
                                    this.$el.removeClass("missing-dash-ds-status");
                                }
                            } else {
                                if (!this.model.get("registered")) {
                                    this.$el.addClass("unregistered-ds-status");
                                } else {
                                    this.$el.removeClass("unregistered-ds-status");
                                }
                            }

                            return this;
                        },
                        bindEvents: function () {
                            this.listenTo(this.model, "change:enabled change:registered change:status change:hasDOTS", this.render);
                        }, 
                    });

                    // Initialize a new Grid instance
                    that.options.MYREFERENCES.grid_instance = grid = new Backgrid.Grid({
                        row: CustomRow, 
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("dashes"),
                    });

                    grid.render();
                    //grid.sort("enabled", "descending"); 

                    // Render the grid and attach the root to your HTML document
                    that.$el.find(".data-sources-container").append(grid.el);

                    that.options.MYREFERENCES.subviews.subnavbarControls.render();

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

                    that._startAutoRefresh(); 

                }, true, customPath);
            }, customPath, "main_template");
        }

        , 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.options.MYREFERENCES.autoRefresh.toid != null) {
                    clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                    this.options.MYREFERENCES.autoRefresh.toid = null;
                }

                this.options.MYREFERENCES.autoRefresh.enabled = true;

                this._autoRefresh();
            } catch (Error) { }
        }

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

            this.refresh(); 

            if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(this._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;
        }

        , configureSource: function (model, data) {
            try {
                var row = model.attributes; 

                var type = row.systemType;
                var typeClass = row.systemTypeClass;
                var menu_option = (data && data.option) ? data.option : null;

                switch (type) {
                    case "DASH":
                        switch (typeClass) {
                            case "WIFI":
                                switch (menu_option.toUpperCase()) {
                                    case "DASH-WIFI-NETWORK":
                                        var modal = new DataSourcesConfiguration.Views.ConfigureDashWifiModal({
                                            parent: this
                                            , viewParams: {
                                                rowData: row
                                            }
                                        });
                                        modal.show();
                                        break;
                                }
                                break;
                            case "GPRS":
                                var modal = new Modal.Views.Main({
                                    id: "dash-gprs-configuration"
                                    , title: this.options.i18n[this.template].translate("no_configuration_available_modal_title").fetch()
                                    , message: this.options.i18n[this.template].translate("no_configuration_available_modal_body").fetch()
                                    , allowCancel: true
                                    , buttons_type: "OK"
                                });
                                modal.show();
                                break; 
                        }
                        break;
                    case "OPC":
                        if (menu_option.toUpperCase() != 'DMT-EDIT') {
                            var modal = new DataSourcesConfiguration.Views.ConfigureOPCModal({
                                parent: this
                                , viewParams: {
                                    agentID: row.id,
                                    rowData: row, 
                                }
                            });
                            modal.show();
                        }
                        break;
                    case "PLC":
                        switch (menu_option.toUpperCase()) {
                            case "PLC-CONNECTION":
                                var modal = new DataSourcesConfiguration.Views.ConfigurePLCModal({
                                    parent: this
                                    , viewParams: {
                                        rowData: row,
                                        rowModel: model, 
                                    }
                                });
                                modal.show();
                                break;
                            case "PLC-MNEMONIC-IMPORT":
                                var modal = new DataSourcesConfiguration.Views.PLCMnemonicsImport({
                                    parent: this
                                    , viewParams: {
                                        rowData: row
                                    }
                                });
                                modal.show();
                                break;
                            case "PLC-DATABLOCKS":
                                var modal = new DataSourcesConfiguration.Views.ConflictDataBlocks({
                                    parent: this
                                    , viewParams: {
                                        rowData: row
                                    }
                                });
                                modal.show();
                                break;
                            case "PLC-SELECT-DBS":
                                var modal = new DataSourcesConfiguration.Views.SelectDBS({
                                    parent: this
                                    , viewParams: {
                                        rowData: row
                                    }
                                });
                                modal.show();
                                break;
                        }
                        break;
                }
                
            }catch(Error){}
        }
        , actionOnSource: function (model, data) {
            var row = model.attributes;
            var type = (row && row.systemType) ? row.systemType.toUpperCase() : null;
            var typeClass = (row && row.systemTypeClass) ? row.systemTypeClass.toUpperCase() : null;
            var menu_option = (data && data.option) ? data.option : null;

            switch (type) {
                case "DASH":
                    this.actionOnDash(model, { option: menu_option }); 
                    break;
                case "DOT":
                    this.actionOnDot(model, { option: menu_option });
                    break; 
                case "OPC":
                case "PLC":
                case "CUSTOM":
                    if (menu_option != null) {
                        this.actionOnInstalledAgent(model, { option: menu_option }); 
                    }
                    break; 
            }
        }
        , actionOnInstalledAgent: function (model, data) {
            var that = this; 
            var row = model.attributes;
            var type = (row && row.systemType) ? row.systemType.toUpperCase() : null;
            var typeClass = (row && row.systemTypeClass) ? row.systemTypeClass.toUpperCase() : null;
            var menu_option = (data && data.option) ? data.option.toUpperCase() : null;
            
            switch (menu_option) {
                case "DS-MIGRATE":
                    var migrateModal = new DataSourcesConfiguration.Views.MigrateDataSourceModal({
                        model: model, 
                    });

                    migrateModal.show(); 
                    break;
                case "DS-DISABLE":
                case "DS-ENABLE":
                    this.dataSourceEnable(model, (menu_option == "DS-ENABLE") ? true : false); 
                    break;
                case "DS-REMOVE":
                    if (model.get("local")) {
                        if (model.get('registered')) {
                            model.set("locked", true);

                            if (model.get('name').toUpperCase().indexOf('OEEAGENTLOCAL') != -1) {
                                this.removeLocalOEEAgent(function (success, data) {
                                    var removeModal = new DataSourcesConfiguration.Views.RemoveDataSourceModal({
                                        model: model,
                                        parent: that,
                                    });
                                    removeModal.deactivateAndRemove_click();
                                    model.set('locked', false);
                                });
                            }
                            else {
                                this.removeLocalPLC(model.get("name"), function (success, data) {
                                    model.set("locked", false);
                                });
                            }
                        } else {
                            var removeModal = new DataSourcesConfiguration.Views.RemoveDataSourceModal({
                                model: model,
                                parent: this,
                            });

                            removeModal.show();
                        }
                    } else {
                        var removeModal = new DataSourcesConfiguration.Views.RemoveDataSourceModal({
                            model: model,
                            parent: this,
                        });

                        removeModal.show();
                    }
                    break;
                case "DS-CLEAR-DATA":
                    this.clearSourceData(model); 
                    break; 
            }
        }
        , actionOnDash: function (model, data) {
            var that = this; 
            var row = model.attributes;
            var type = (row && row.systemType) ? row.systemType.toUpperCase() : null;
            var typeClass = (row && row.systemTypeClass) ? row.systemTypeClass.toUpperCase() : null;
            var menu_option = (data && data.option) ? data.option.toUpperCase() : null;
            
            switch (menu_option) {
                case "DS-CLEAR-DATA":
                    var modal = new DataSourcesConfiguration.Views.RemoveClearDashModal({
                        parent: this,
                        model: model, 
                        viewParams: {
                            rowData: row,
                            mode: menu_option,
                        }, 
                    });

                    modal.show(); 
                    break;
                case "DS-REMOVE":
                    if (model.get("hasDOTS")) {
                        var modal = new DataSourcesConfiguration.Views.RemoveClearDashModal({
                            parent: this,
                            model: model,
                            viewParams: {
                                rowData: row,
                                mode: menu_option,
                            },
                        });

                        modal.show();
                    } else {
                        DataSourcesConfiguration.Views.DeleteSourceModal.DeleteDataSource(model.get("id"), true, function (data) {
                            if (data && data.Table && data.Table[0] && data.Table[0].Status == "SUCCESS") {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_unregistered_message").fetch(), { stay: 3000 });
                            } else {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_unregistered_error_message").fetch(), { stay: 3000 });
                            }
                            that.refresh(); 
                        }, function (data) {
                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_unregistered_error_message").fetch(), { stay: 3000 });
                            that.refresh();
                        });
                    }
                    break;
            }
        }
        , actionOnDot: function (model, data) {
            var row = model.attributes;
            var type = (row && row.systemType) ? row.systemType.toUpperCase() : null;
            var typeClass = (row && row.systemTypeClass) ? row.systemTypeClass.toUpperCase() : null;
            var menu_option = (data && data.option) ? data.option.toUpperCase() : null;

            switch (menu_option) {
                case "DS-CLEAR-DATA":
                    this.clearDotData(model);
                    break;
                case "DS-REMOVE":
                    this.removeDot(model); 
                    break; 
            }
        }
        , dataSourceEnable: function (model, enabled) {
            var that = this; 
            if (_.isBoolean(enabled)) {
                var row = model.attributes;
                var QP = new Core.Database.QueryParameters();
                QP.Add("DataSourceId", "INT", row.id);
                QP.Add("Enabled", "BIT", enabled)

                model.set("locked", true); 
                app.CallProcedure(app.DatabaseNames.IH + ".WEB.SetDataSourceEnabled", QP,
                    {
                        onSuccess: function (data) {
                            that._autoRefresh(); 
                        },
                        onFailure: function (data) {
                            that._autoRefresh();
                        }
                    },
                app.ConnectionStrings.app);
            }
        }
        , removeLocalPLC: function (name, callback) {
            name = name.replace("PLCAGENTLOCAL-", "");
            name = name.replace("PLCAGENTLOCAL", "");

            var that = this;
            $.ajax(app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/local-agents.aspx", {
                type: 'POST',
                data: { action: "REMOVE_LOCAL_PLC", AgentName: name },
                dataType: "json",
                success: function (data) {
                    callback(true, data); 
                },
                error: function (data) {
                    callback(false, data); 
                },
            });
        }
        , removeLocalOEEAgent: function (callback) {
            var that = this;
            $.ajax(app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/local-agents.aspx", {
                type: 'POST',
                data: { action: "REMOVE_OEE_DEMO" },
                dataType: "json",
                success: function (data) {
                    callback(true, data);
                },
                error: function (data) {
                    callback(false, data);
                },
            });
        }
        , clearDotData: function (model) {
            row = model.attributes;
            var that = this;

            var modal = new Modal.Views.Main({
                id: "delete-source-data-history"
                , title: this.options.i18n[this.template].translate("delete_source_data_history_modal_title").fetch(row.systemType, row.name)
                , message: this.options.i18n[this.template].translate("delete_source_data_history_modal_body").fetch(row.systemType, row.name)
                , allowCancel: true
                , buttons_type: "CONTINUE-CANCEL"
            });

            modal.on("continue", function () {

                var modal = new Modal.Views.Main({
                    id: "delete-source-data-history"
                    , title: that.options.i18n[that.template].translate("delete_source_data_history_confirm_modal_title").fetch(row.systemType, row.name)
                    , message: that.options.i18n[that.template].translate("delete_source_data_history_confirm_modal_body").fetch()
                    , allowCancel: true
                    , buttons_type: "CONTINUE-CANCEL"
                });

                modal.on("continue", function () {
                    var id = parseInt(row.id.replace("TG-", "")); 
                    if (!isNaN(id)) {
                        var QP = new QueryParameters();
                        QP.Add("@TagGroupId", "INT", id);

                        Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.ClearDotData", QP, {
                            onSuccess: function (data) {
                                if (data && data.Table && data.Table[0] && data.Table[0].Status == "OK") {
                                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_clear_data_message").fetch(), { stay: 3000 });
                                } else {
                                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_clear_data_error_message").fetch(), { stay: 3000 });
                                }

                                that.refresh(); 
                            }
                            , onFailure: function () {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_clear_data_error_message").fetch(), { stay: 3000 });
                            }
                        }, app.ConnectionStrings.app);
                    }
                });

                modal.show();

            });

            modal.show();
        }
        , removeDot: function (model) {
            row = model.attributes;
            var that = this;

            var modal = new Modal.Views.Main({
                id: "remove-dot-modal"
                , title: this.options.i18n[this.template].translate("delete_source_modal_title").fetch(row.systemType, row.name)
                , message: this.options.i18n[this.template].translate("delete_source_modal_body").fetch(row.systemType, row.name)
                , allowCancel: true
                , buttons_type: "CONTINUE-CANCEL"
            });

            modal.on("continue", function () {

                var modal = new Modal.Views.Main({
                    id: "delete-source-data-history"
                    , title: that.options.i18n[that.template].translate("delete_source_confirm_modal_title").fetch(row.systemType, row.name)
                    , message: that.options.i18n[that.template].translate("delete_source_confirm_modal_body").fetch()
                    , allowCancel: true
                    , buttons_type: "CONTINUE-CANCEL"
                });

                modal.on("continue", function () {
                    var id = parseInt(row.id.replace("TG-", ""));
                    if (!isNaN(id)) {
                        var QP = new QueryParameters();
                        QP.Add("@TagGroupId", "INT", id);

                        Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.DeleteDot", QP, {
                            onSuccess: function (data) {
                                if (data && data.Table && data.Table[0] && data.Table[0].Status == "OK") {
                                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_removed_message").fetch(), { stay: 3000 });
                                } else {
                                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_removed_error_message").fetch(), { stay: 3000 });
                                }
                                that.refresh(); 
                            }
                            , onFailure: function () {
                                app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dot_removed_error_message").fetch(), { stay: 3000 });
                                that.refresh(); 
                            }
                        }, app.ConnectionStrings.app);
                    }
                });

                modal.show();

            });

            modal.show();
        }
        , clearSourceData: function (model) {
            row = model.attributes;
            var that = this;

            var modal = new Modal.Views.Main({
                id: "delete-source-data-history"
                , title: this.options.i18n[this.template].translate("delete_source_data_history_modal_title").fetch(row.systemType, row.name)
                , message: this.options.i18n[this.template].translate("delete_source_data_history_modal_body").fetch(row.systemType, row.name)
                , allowCancel: true
                , buttons_type: "CONTINUE-CANCEL"
            });

            modal.on("continue", function () {

                var modal = new Modal.Views.Main({
                    id: "delete-source-data-history"
                    , title: that.options.i18n[that.template].translate("delete_source_data_history_confirm_modal_title").fetch(row.systemType, row.name)
                    , message: that.options.i18n[that.template].translate("delete_source_data_history_confirm_modal_body").fetch()
                    , allowCancel: true
                    , buttons_type: "CONTINUE-CANCEL"
                });

                modal.on("continue", function () {

                    var QP = new QueryParameters();
                    QP.Add("@DataSourceId", "INT", row.id);
                    Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.DeleteDataSourceHistory", QP, {
                        onSuccess: function (data) {
                            data;
                        }
                        , onFailure: function () {

                        }
                    }, app.ConnectionStrings.app);

                });

                modal.show(); 

            });

            modal.show();
        }        
        , refresh: function () {
            try {
                this.model.get("dashes").fetch(); 
            } catch (Error) { }
        }
        , collectionReset: function (collection) {
            var that = this;
            
            collection.each(function (model) {
                that.listenTo(model, "change", that.dashChanged); 
            }); 
        }
        , gridEdit: function () {
            this.options.MYREFERENCES.editing = true; 
            this._stopAutoRefresh(); 
        }
        , gridEditEnd: function () {
            var that = this; 
            this.options.MYREFERENCES.editing = false;
            setTimeout(function () {
                if (!that.options.MYREFERENCES.editing)
                    that._startAutoRefresh();
            }, 500); 
        }
        , dashChanged: function (model, val, opt) {
            var from = (opt && opt.from) ? opt.from : null;
            if (from != "fetch") this.saveData(model.toJSON(), ["friendlyName", "id"]); 
        }
        , datablocksConflictsChanged: function () {
            this.options.MYREFERENCES.grid_instance.render();
        }

        , _getXML: function (data, cols) {
            cols = (_.isArray(cols)) ? cols : []; 
            cols = _.invoke(cols, "toUpperCase"); 

            var xml = null;
            if (!data.length) data = [data];
            try {
                xml = '<XMLRoot>';
                for (var r = 0; r < data.length; r++) {
                    rowObj = data[r];
                    var row = '<Row ';
                    for (var c in rowObj) {
                        if ((cols.length == 0) || (cols.length > 0 && _.indexOf(cols, c.toString().toUpperCase()) != -1)) {
                            row += ((Trim(c).replace(' ', '')).replace('[', '')).replace(']', '') + '="' + rowObj[c] + '" ';
                        }
                    }
                    row += '/>';
                    row = row.replace(/#/g, '');
                    xml += row;
                }
                xml += '</XMLRoot>';
            } catch (Error) {
            }
            return xml;
        }

        , saveData: function (data, cols) {
            var xml = this._getXML(data, cols);

            var QP = new Core.Database.QueryParameters();
            QP.Add("XML", "XML", xml);

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.[SaveDataSourcesConfiguration]", QP, {
                onSuccess: function (data) {
                    data;
                }
            }, app.ConnectionStrings.app);
        }

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

            this.listenTo(this.model.get("dashes"), "backgrid:edit", this.gridEdit);
            this.listenTo(this.model.get("dashes"), "backgrid:edited", this.gridEditEnd);
            this.listenTo(this.model.get("dashes"), "backgrid:error", this.gridEditEnd);
            this.listenTo(this.model.get("dashes"), "change:friendlyName", this.dashChanged); 

            //this.listenTo(this.model.get("dashes"), "reset", this.collectionReset);
            this.listenTo(app.models.datablocksConflicts, "change:hasConflicts", this.datablocksConflictsChanged);

            app.models.locksManager.listenToCategory(
                this,
                ["add", "remove"],
                ["ENABLE", "DISABLE", "UNREGISTER", ],
                this._autoRefresh
            );
        }

        , bindViewScopedEvents: function () {
        }

        , unbindViewScopedEvents: function () {
        }

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

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

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

            var subnavbar = app.models.securityManager.getModuleActionValue("ihconfiguration_data_sources", "write"); 
            app.models.subnavbar.set("subnavbar", subnavbar);
            app.models.subnavbar.set("sections", "12");
        }

        , reRender: function () {
            this._startAutoRefresh(); 
        }
    });

    DataSourcesConfiguration.Models.ConfigureOPCModal = Backbone.Model.extend({
        defaults: {
            rows: [], 
            locked: false, 
        }
        , initialize: function(){
            _.bindAll(this); 
        }
        , getOPCAgentData: function (opcid) {
            return _.find(this.get("rows"), function (item) {
                return item.OPCServerDetectedID == opcid; 
            });
        }
    }); 

    DataSourcesConfiguration.Views.ConfigureOPCModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "opc-configuration-modal"
        , title: "OPC Configuration Modal"
        , className: "modal hide fade"
        //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: true
        , initialize: function () {
            if (this.options.viewParams) {
            }

            this.model = new DataSourcesConfiguration.Models.ConfigureOPCModal(); 

            this.options.MYREFERENCES = {
                rowData: null, 
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.options._isRendered = false; 

            this.locksChanged(); 

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            "click .clickeable-row": "_opcAgentRowClick"
        },
        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                var QP = new Core.Database.QueryParameters();
                QP.Add("AgentID", "INT", that.options.viewParams.agentID); 
                Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].[GetOPCServersDetected]", QP, {
                    onSuccess: function (data) {
                        try {
                            //always mock-up the object in case no data is returned.
                            var tmplData = {
                                rows: []
                            };

                            if (Core.Object.Eval(data, "Table")) {
                                var data = data.Table;

                                for (var i = 0, len = data.length; i < len; i++) {
                                    data[i]["OPCServerDetectedID"] = i+1; 
                                }

                                that.model.set("rows", data); 
                                tmplData.rows = data; 
                            }

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

                            that.lockedChanged(); 

                            that.options._isRendered = true;

                        } catch (Error) { }
                    },
                    onFailure: function () {
                        try{
                        } catch (Error) { }
                    }
                }, app.ConnectionStrings.app); 

            }, customPath, "opc_configuration_modal");
        }
        , locksChanged: function () {
            var locks = app.models.locksManager.getCategoryLocks(
                ["AGENTDISCONNECTED", "SETOPCADDRESS", "TAGSCONFIGCHANGE", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.options.MYREFERENCES.rowData.id, true
            );

            this.model.set("locked", (locks.length > 0));
        }
        , lockedChanged: function () {
            var locked = this.model.get("locked");

            var locks = app.models.locksManager.getCategoryLocks(
                ["AGENTDISCONNECTED", "SETOPCADDRESS", "TAGSCONFIGCHANGE", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.options.MYREFERENCES.rowData.id, true
            );
            var firstLock = (locks.length > 0) ? locks.at(0) : null;

            var opcServersTable = this.$(".select-opc-server-table");
            if (locked) {
                opcServersTable.find(".clickeable-row").addClass("locked-row"); 
            } else {
                opcServersTable.find(".clickeable-row").removeClass("locked-row");
            }

            var disconnected_msg = this.$el.find(".agent-disconnected-msg");
            var applying_msg = this.$el.find(".applying-config-msg");
            var locked_msg = this.$el.find(".locked-agent-msg");
            disconnected_msg.addClass("hide");
            applying_msg.addClass("hide");
            locked_msg.addClass("hide");

            if (firstLock) {
                var msg_elem = null;
                switch (firstLock.get("name")) {
                    case "AGENTDISCONNECTED":
                        msg_elem = disconnected_msg;
                        break;
                    case "SETOPCADDRESS":
                        msg_elem = applying_msg;
                        break;
                    default:
                        msg_elem = locked_msg;
                        break;
                }
                if (msg_elem != null) msg_elem.removeClass("hide");
            }
        }

        , _opcAgentRowClick: function (e) {
            var locked = this.model.get("locked");

            if (!locked) {
                var el = $(e.target).closest("tr");
                var agentData = this.model.getOPCAgentData(el.data("opcagentid"));

                var QP = new Core.Database.QueryParameters();
                QP.Add("AgentID", "INT", agentData.AgentID);
                QP.Add("ProgID", "VARCHAR", agentData.ProgID);

                var that = this;
                Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].[SetOPCAgentAddress]", QP, {
                    onSuccess: function (data) {
                        //everything went well
                        that.options.parent.refresh();
                        that.hide();
                    }
                    , onFailure: function (data) {
                        data;
                    }
                }, app.ConnectionStrings.app);
            }
        }

        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal();

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });
            
            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            try {

            } catch (Error) { }
        }

        , 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
            app.models.locksManager.listenToCategory(
                this,
                ["add", "remove"],
                ["AGENTDISCONNECTED", "SETOPCADDRESS", "TAGSCONFIGCHANGE", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.locksChanged
            );

            this.listenTo(this.model, "change:locked", this.lockedChanged);
        }

        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.DeleteSourceModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "delete-source-modal"
        , title: "Delete Source Modal"
        , className: "modal hide fade"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                rowData: null
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData; 
            }

            this.options._isRendered = false;

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            //, "click #unregister_delete_data": function () {
            //    this._unregisterDataSource("DELETEDATA"); 
            //}
            , "click #unregister_continue": function () {
                this._callUnregisterDataSource(true);
            }
            //, "click #unregister_keep_data": function () {
            //    this._unregisterDataSource("KEEPDATA"); 
            //}
            , "click #unregister_cancel": "_cancelAction"
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                //loading the view and appeding it to the views's $el.
                that.$el.html(tmp({
                    modal_title: that.options.parent.options.i18n[that.template].translate("delete_source_modal_title").fetch()
                    , modal_body: that.options.parent.options.i18n[that.template].translate("delete_source_modal_body").fetch(that.options.MYREFERENCES.rowData.systemType, that.options.MYREFERENCES.rowData.name)
                }));
                that.options._isRendered = true;

            }, customPath, "delete_source_modal");

        }        

        , _unregisterDataSource: function (action) {
            if (action == "DELETEDATA") {
                this._confirmDeleteData(); 
            } else if (action == "KEEPDATA") {
                action = false;
                this._callUnregisterDataSource(action); 
            }

            this.hide();
        }

        , _callUnregisterDataSource: function (action) {
            try {
                var data = this.options.MYREFERENCES.rowData;
                var QP = new QueryParameters();
                var that = this;

                QP.Add("DataSourceId", "INT", data.id);
                QP.Add("DeleteAllData", "BIT", action);

                Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].DeleteDataSource", QP, {
                    onSuccess: function (data) {
                        that.options.parent.refresh();
                        that.hide();
                    }
                }, app.ConnectionStrings.app);
            } catch (Error) { }
        }

        , _confirmDeleteData: function () {
            var modal = new Modal.Views.Main({
                id: "confirm-delete"
                , title: this.options.parent.options.i18n[this.template].translate("delete_source_confirm_modal_title").fetch(this.options.MYREFERENCES.rowData.systemType, this.options.MYREFERENCES.rowData.name)
                , message: this.options.parent.options.i18n[this.template].translate("delete_source_confirm_modal_body").fetch()
                , allowCancel: true
                , buttons_type: "CONTINUE-CANCEL"
            });

            var that = this; 
            modal.on("continue", function () {
                that._callUnregisterDataSource(true); 
            });

            modal.show();
        }

        , _cancelAction: function () {
            this.hide(); 
        }

        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal();

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            try {

            } catch (Error) { }
        }

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

        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
            app.models.subnavbar.set("dateControl", false);
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.DeleteSourceModal.DeleteDataSource = function (datasourceId, deleteAllData, success, failure) {
        try {
            success = _.isFunction(success) ? success : function () { };
            failure = _.isFunction(failure) ? failure : function () { };
            var QP = new QueryParameters();
            var that = this;

            QP.Add("DataSourceId", "INT", datasourceId);
            QP.Add("DeleteAllData", "BIT", deleteAllData);

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].DeleteDataSource", QP, {
                onSuccess: function (data) {
                    success.call(this, data);
                },
                onFailure: function (data) {
                    failure.call(this, data);
                }
            }, app.ConnectionStrings.app);
        } catch (Error) { }
    }; 

    //subview for the subnavbar controls
    DataSourcesConfiguration.Views.SubnavBarControls = Backbone.View.extend({
        id: "dataSourcesConfiguration-subnavbar-controls"
        , title: ""
        , template: "data-sources-configuration"
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            if (this.options.viewParams) {
            }

            this.options.MYREFERENCES = {};

            this.bindEvents();
            _.bindAll(this);
        },

        events: {
            "submit #addSource_form": "addSource", 
            "keydown #sourceNumber_input": function () {
                this.$("#cg_addSource").removeClass("error"); 
            }, 
            //"click .add-source-pre-btn": "addSourcePreBtn_click",
            "click .btn-add-source-cancel": "addSourceCancelBtn_click",
            "click .btn-add-local-plc-cancel": "addLocalPLCCancelBtn_click",
            "click .add-local-plc-pre-btn": "addLocalPLCPreBtn_click",
            "click #addLocalPLC_btn": "addLocalPLC",
            "click .install-agent-btn": "installAgentBtn_click", 
        },

        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/IHConfiguration/data-sources-configuration-v2/";

            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: app.models.securityManager.getModuleActionValue("ihconfiguration_data_sources", "write"),
                    };

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

                    that.append(thatContainer, that.$el);
                }, true, customPath); 
            }, customPath, "subnavbar_controls"); 

        }

        , 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;
            }
        }
        , addSourcePreBtn_click: function () {
            this.$el.find(".datasources-subnavbar-toolbar").addClass("hide");
            this.$el.find("#addSource_form").removeClass("hide"); 
        }
        , addLocalPLCPreBtn_click: function () {
            this.$el.find(".datasources-subnavbar-toolbar").addClass("hide");
            this.$el.find("#addLocalPLC_form").removeClass("hide"); 
        }
        , addSourceCancelBtn_click: function () {
            var frm = this.$el.find("#addSource_form"); 
            frm.addClass("hide");
            frm.find("#cg_addSource").removeClass("error");
            frm.find("#sourceNumber_input").val("");

            this.$el.find(".datasources-subnavbar-toolbar").removeClass("hide");
        }
        , addLocalPLCCancelBtn_click: function () {
            var frm = this.$el.find("#addLocalPLC_form");
            frm.addClass("hide");
            frm.find("#cg_addLocalPLC").removeClass("error");
            frm.find("#addLocalPLC_input").val("");
            this.$el.find(".datasources-subnavbar-toolbar").removeClass("hide");
        }
        , installAgentBtn_click: function () {
            var modal = new DataSourcesConfiguration.Views.InstallAgentModal(); 
            modal.show(); 
        }
        , addLocalPLC: function (e) {
            var that = this;
            e.preventDefault();
            var frm = $(e.target).closest("form");
            var frmInput = frm.find("#addLocalPLC_input");
            var localPLCName = frmInput.val();
            var plcLoading = this.$el.find("#addLocalPLC_loading"); 
            var toolbar = this.$el.find(".datasources-subnavbar-toolbar"); 

            if (this.validateLocalPLCName(localPLCName)) {
                frm.addClass("hide"); 
                plcLoading.removeClass("hide"); 

                $.ajax(app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/local-agents.aspx", {
                    type: 'POST',
                    data: { action: "ADD_LOCAL_PLC", AgentName: localPLCName },
                    dataType: "json",
                    success: function (data) {
                        plcLoading.addClass("hide");
                        if (data && data.Success == true) {
                            frmInput.val("");
                            frm.find("#cg_addLocalPLC").removeClass("error");
                            toolbar.removeClass("hide");
                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("add_local_plc_success_message").fetch(), { stay: 2000 });
                        } else {
                            frm.removeClass("hide"); 
                            frm.find("#cg_addLocalPLC").addClass("error");

                            var errorKey = "add_local_plc_generic_error_message";
                            if (data && data.Message) {   
                                switch (data.Message.toUpperCase()) {
                                    case "DIRECTORYALREADYEXISTS":
                                        errorKey = "add_local_plc_same_name_error_message"; 
                                        break;
                                    case "MAXLOCALAGENTSREACHED":
                                        errorKey = "add_local_plc_max_local_agents_reached";
                                        break; 
                                }
                            }

                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate(errorKey).fetch(), { stay: 3500 });
                        }
                    },
                    error: function () {
                    },
                });
            } else {
                frm.find("#cg_addLocalPLC").addClass("error");
                frmInput.select();
            }
        }
        , validateLocalPLCName: function (name) {
            try {
                if (Core.String.ValidateEmpty(name)) {
                    var reg = new RegExp("^[a-zA-Z0-9]{1,20}$");
                    if (name.match(reg)) {
                        return true;
                    }
                }
                return false;
            } catch (Error) {
                return false;
            }
        }
        , addSource: function (e) {
            try {
                e.preventDefault();
                var frm = $(e.target).closest("form");
                var frmInput = frm.find("#sourceNumber_input"); 
                var sourceNumber = frmInput.val();

                if (this._validateSourceNumber(sourceNumber)) {
                    var QP = new Core.Database.QueryParameters();
                    QP.Add("SourceName", "VARCHAR", sourceNumber);

                    var that = this;
                    Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].[RegisterNewSource]", QP, {
                        onSuccess: function (data) {

                            var status = 0;
                            for (var t in data) {
                                try {
                                    var table = data[t];
                                    if (Core.Object.Eval(table, '0.Status') == true) {
                                        if (table[0].Status == 'SUCCESS') {
                                            status = "SUCCESS";
                                        } else if (table[0].Status == 'FAILURE') {
                                            status = "FAILURE";
                                        } else if (table[0].Status == 'MAXAGENTSREACHED') {
                                            status = "MAXAGENTSREACHED";
                                        }
                                    }
                                } catch (Error) { }
                            }

                            if (status == "SUCCESS") {
                                //added successfully.
                                that.$("#sourceNumber_input").val("");
                                that.options.parent.refresh();

                                var frm = that.$el.find("#addSource_form");
                                frm.addClass("hide");
                                frm.find("#cg_addSource").removeClass("error");
                                frm.find("#sourceNumber_input").val("");

                                that.$el.find(".datasources-subnavbar-toolbar").removeClass("hide");

                            } else if (status == "FAILURE") {
                                //something happened!
                            } else if (status == "MAXAGENTSREACHED") {

                            }

                        }
                        , onFailure: function () {

                        }
                    }, app.ConnectionStrings.app);

                } else {
                    frm.find("#cg_addSource").addClass("error");
                    frmInput.select(); 
                }

            } catch (Error) { }
        }
        , _validateSourceNumber: function (sn) {
            try {
                if (Core.String.ValidateEmpty(sn)) {
                    var reg = new RegExp("[WwGgUu]{1}[A-Fa-f0-9]{16}");
                    if (sn.match(reg)) {
                        return true; 
                    }
                }
                return false; 
            } catch (Error) {
                return false; 
            }
        }

        , refresh: function () {
            try {

            } catch (Error) { }
        }

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

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

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.InstallAgentModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "install-agent-modal"
        , title: "Install Agent Modal"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
            };

            if (this.options.viewParams) {
            }

            this.options._isRendered = false;

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            'click .btn-close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            "change .downloads-table-radio": "downloadSelected",
            "click .btn-download": "download_click",
            "click .btn-try-again": "backToDownloadCenter", 
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                //loading the view and appeding it to the views's $el.
                that.$el.html(tmp({
                    downloads: [
                        { name: "Industrial Historian Agent for OPC", id: "IHOPCAGENT" },
                        { name: "Industrial Historian Siemens S7 Agent", id: "IHSIEMENSS7AGENT" },
                    ]
                }));

                that.options._isRendered = true;

            }, customPath, "install_agent_modal");
        }
        , downloadSelected: function () {
            this.$el.find(".btn-download").prop("disabled", false);
        }
        , download_click: function () {
            var that = this; 
            var selected_download_rb = this.$el.find("input[type='radio'][name='downloads_table_radio']:checked");
            if (selected_download_rb.length > 0) {
                var selected_tr = selected_download_rb.parents("tr");
                var downloadid = selected_tr.data("downloadid");
                if (downloadid != null && downloadid != undefined) {
                    this.generateDownload(downloadid); 
                }
            }
        }
        , backToDownloadCenter: function () {
            this.$el.find(".btn-download").removeClass("hide");
            this.$el.find(".btn-close").removeClass("hide");
            this.$el.find(".close").removeClass("hide");
            this.$el.find(".generate-and-download").addClass("hide");
            this.$el.find(".main-download-center").removeClass("hide");
        }
        , generateDownload: function (downloadid) {
            var that = this;
            this.$el.find(".btn-download").addClass("hide");
            this.$el.find(".btn-close").addClass("hide");
            this.$el.find(".close").addClass("hide");

            this.$el.find(".generating-download-text").removeClass("hide");
            this.$el.find(".starting-download").addClass("hide");
            this.$el.find(".download-failed").addClass("hide");
            
            var downloadIcon = this.$el.find(".fa-download-big-icon");
            downloadIcon.removeClass("animated infinite pulse shake bounce"); 
            downloadIcon.addClass("animated pulse infinite"); 

            //hide main, showing generating download screen
            this.$el.find(".main-download-center").fadeOut("slow", function () {
                that.$el.find(".main-download-center").addClass("hide"); 
                that.$el.find(".main-download-center").css("opacity", "");
                that.$el.find(".main-download-center").css("display", "");
                that.$el.find(".generate-and-download").fadeIn("slow", function () {
                    that.$el.find(".generate-and-download").removeClass("hide"); 
                    that.$el.find(".generate-and-download").css("display", "");
                    that.$el.find(".generate-and-download").css("opacity", "");
                });
            });

            var frm = this.$el.find("#form-generate-download");
            var action = frm.prop("action");
            var sourceName = "OPC"; 

            switch (downloadid) {
                case "IHOPCAGENT":
                    sourceName = "OPC"; 
                    break;
                case "IHSIEMENSS7AGENT":
                    sourceName = "PLCSiemensS7";
                    break; 
            }

            $.ajax({
                url: action, 
                type: 'POST',
                data: {
                    accountnumber: app.models.user.get("accountNumber"),
                    sourceName: sourceName,
                },
                dataType: "json"
            })
            .done(function (e) { that.generateDownloadComplete(e); })
            .fail(function (e) { that.generateDownloadFailed(e); });
        }
        , generateDownloadComplete: function (e, opt) {
            this.$el.find(".btn-close").removeClass("hide");
            this.$el.find(".close").removeClass("hide");
            this.$el.find(".generating-download-text").addClass("hide");

            var downloadIcon = this.$el.find(".fa-download-big-icon");
            downloadIcon.removeClass("animated pulse infinite");

            if (e && e.status && e.status == "OK") {
                downloadIcon.addClass("animated bounce"); 

                this.$el.find(".starting-download").removeClass("hide");
                this.$el.find(".download-direct-link").attr("href", e.path);

                //trigger automatic download
                location.href = e.path;
            } else {
                downloadIcon.addClass("animated shake");
                this.$el.find(".download-failed").removeClass("hide");
            }
        }
        , generateDownloadFailed: function (e, opt) {
            var downloadIcon = this.$el.find(".fa-download-big-icon");
            downloadIcon.removeClass("animated pulse infinite");
            downloadIcon.addClass("animated shake");

            this.$el.find(".btn-close").removeClass("hide");
            this.$el.find(".close").removeClass("hide");
            this.$el.find(".generating-download-text").addClass("hide");
            this.$el.find(".download-failed").removeClass("hide");
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false,
                backdrop: 'static', 
            });

            $backdrop = $('.modal-backdrop');

            //$backdrop.one('click', function () {
            //    if (self.options.content && self.options.content.trigger) {
            //        self.options.content.trigger('cancel', self);
            //    }

            //    self.trigger('cancel');
            //});

            //$(document).one('keyup.dismiss.modal', function (e) {
            //    e.which == 27 && self.trigger('cancel');

            //    if (self.options.content && self.options.content.trigger) {
            //        e.which == 27 && self.options.content.trigger('shown', self);
            //    }
            //});

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            try {
            } catch (Error) { }
        }

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

        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.ConfigureDashWifiModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "configure-dash-wifi-modal"
        , title: "Configure Dash Wifi Modal"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                rowData: null
            };
            
            this.options.dashConfigurationCommandMonitorTOUT = null; 
            this.options.configurationCommandId = null;
            this.options.sentConfigString = null;

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.options._isRendered = false;
            this.options._isRendering = false; 

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
        },
        render: function (container, status) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

            var locks = app.models.locksManager.getCategoryLocks(
                ["CONFIGUREDASH", "GETDASHCONFIGURATION"],
                this.options.MYREFERENCES.rowData.id, true
            );

            status = (status != undefined && status != null) ? status : "GETDASHCONFIGURATION"; 
            if (locks.length == 0 && (status != "CONFIGURATIONREAD" && status != "CONFIGURATIONSAVED" && status != "SENDINGCONFIGURATION")) {
                var QP = new Core.Database.QueryParameters();
                QP.Add("AgentId", "INT", this.options.MYREFERENCES.rowData.id);

                app.CallProcedure(app.DatabaseNames.IH + ".WEB.SendGetDashConfigurationCommand", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table[0]) {
                            that.options.configurationCommandId = data.Table[0].CommandId;
                            //that.readConfigurationCommand();
                        }
                    },
                }, app.ConnectionStrings.app);
            } else if (locks.length > 0) {
                var l = locks.at(0); 
                status = l.get("name");
                if (status == "GETDASHCONFIGURATION") {
                    that.options.configurationCommandId = parseInt(l.get("data"));
                    //that.readConfigurationCommand();
                }
            }

            if (status == "GETDASHCONFIGURATION") {
                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.options._isRendered = true;
                    }, true, customPath); 
                }, customPath, "dash_wifi_configuration_modal_loading");
            }else if (status == "CONFIGURATIONREAD"){
                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.$el.find("#widget-frame").on("load", that.formFrameLoaded);
                        that.options._isRendered = true;
                    }, true, customPath); 
                }, customPath, "dash_wifi_configuration_modal");
            } else if (status == "CONFIGUREDASH" || status == "SENDINGCONFIGURATION") {
                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.options._isRendered = true;
                    }, true, customPath);
                }, customPath, "dash_wifi_configuration_modal_sending_configuration");
            } else if (status == "CONFIGURATIONSAVED") {
                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.$el.find("#widget-frame").on("load", that.displayFormLoaded);
                        that.options._isRendered = true;
                    }, true, customPath);
                }, customPath, "dash_wifi_configuration_modal_configuration_saved");
            }
        }
        , readConfigurationCommand: function () {
            var that = this; 
            //if (this.options.dashConfigurationCommandMonitorTOUT) {
            //    clearTimeout(this.options.dashConfigurationCommandMonitorTOUT);
            //    this.options.dashConfigurationCommandMonitorTOUT = null; 
            //}

            if (this.options.configurationCommandId != null) {
                var QP = new Core.Database.QueryParameters();
                QP.Add("CommandId", "INT", this.options.configurationCommandId);

                app.CallProcedure(app.DatabaseNames.IH + ".WEB.GetDashConfiguration", QP, {
                    onSuccess: function (data) {
                        if (data && data.Table && data.Table[0]) {
                            data = data.Table[0];

                            var commandStatus = data.CommandStatus;
                            if (commandStatus == "OK") {
                                var configString = data.ConfigString;
                                that.options.dashConfigString = configString;
                                that.render(null, "CONFIGURATIONREAD");
                            } else {
                                //that.options.dashConfigurationCommandMonitorTOUT = setTimeout(_.bind(that.readConfigurationCommand, that), 1000);
                            }
                        }
                    },
                }, app.ConnectionStrings.app);

                return true; 
            } else {
                //that.options.dashConfigurationCommandMonitorTOUT = setTimeout(_.bind(that.readConfigurationCommand, that), 1000);
            }

            return false; 
        }
        , stopMonitoringConfigurationCommand: function () {
            var that = this;
            if (this.options.dashConfigurationCommandMonitorTOUT) {
                clearTimeout(this.options.dashConfigurationCommandMonitorTOUT);
                this.options.dashConfigurationCommandMonitorTOUT = null;
            }
        }
        , deparam: function (params, coerce) {
            var obj = {},
                coerce_types = { 'true': !0, 'false': !1, 'null': null };

            //Remove initial chars '.?' to then parse parameters
            //To do this, look for the index of the first char '?' and get all the text after
            //that index. Do this to prevent issues if there is another char '?' on the rest of the text.
            params = params.substring(params.indexOf('?') + 1, params.length);

            //TEMPORAL FIX ******************
            //Add a char '=' after the text '&secKey' to fix format of password attribute.
            //Remove this change after fix the format of the data on the dash app.
            params = params.substring(0, params.indexOf('&secKey') + 1 + "secKey".length)
                    + "="
                    + params.substring(params.indexOf('&secKey') + 1 + "secKey".length, params.length);


            // Iterate over all name=value pairs.
            $.each(params.replace(/\+/g, ' ').split('&'), function (j, v) {
                var param = v.split('='),
                    key = decodeURIComponent(param[0]),
                    val,
                    cur = obj,
                    i = 0,

                    // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it
                    // into its component parts.
                    keys = key.split(']['),
                    keys_last = keys.length - 1;

                // If the first keys part contains [ and the last ends with ], then []
                // are correctly balanced.
                if (/\[/.test(keys[0]) && /\]$/.test(keys[keys_last])) {
                    // Remove the trailing ] from the last keys part.
                    keys[keys_last] = keys[keys_last].replace(/\]$/, '');

                    // Split first keys part into two parts on the [ and add them back onto
                    // the beginning of the keys array.
                    keys = keys.shift().split('[').concat(keys);

                    keys_last = keys.length - 1;
                } else {
                    // Basic 'foo' style key.
                    keys_last = 0;
                }

                // Are we dealing with a name=value pair, or just a name?
                if (param.length === 2) {
                    val = decodeURIComponent(param[1]);

                    // Coerce values.
                    if (coerce) {
                        val = val && !isNaN(val) ? +val              // number
                            : val === 'undefined' ? undefined         // undefined
                            : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null
                            : val;                                                // string
                    }

                    if (keys_last) {
                        // Complex key, build deep object structure based on a few rules:
                        // * The 'cur' pointer starts at the object top-level.
                        // * [] = array push (n is set to array length), [n] = array if n is 
                        //   numeric, otherwise object.
                        // * If at the last keys part, set the value.
                        // * For each keys part, if the current level is undefined create an
                        //   object or array based on the type of the next keys part.
                        // * Move the 'cur' pointer to the next level.
                        // * Rinse & repeat.
                        for (; i <= keys_last; i++) {
                            key = keys[i] === '' ? cur.length : keys[i];
                            cur = cur[key] = i < keys_last
                              ? cur[key] || (keys[i + 1] && isNaN(keys[i + 1]) ? {} : [])
                              : val;
                        }

                    } else {
                        // Simple key, even simpler rules, since only scalars and shallow
                        // arrays are allowed.

                        if ($.isArray(obj[key])) {
                            // val is already an array, so push on the next value.
                            obj[key].push(val);

                        } else if (obj[key] !== undefined) {
                            // val isn't an array, but since a second value has been specified,
                            // convert val into an array.
                            obj[key] = [obj[key], val];

                        } else {
                            // val is a scalar.
                            obj[key] = val;
                        }
                    }

                } else if (key) {
                    // No value was defined, so set something meaningful.
                    obj[key] = coerce
                      ? undefined
                      : '';
                }
            });

            return obj;
        }
        , formFrameLoaded: function (e) {
            var that = this;

            var dashConfig = _.extend({
                dns: '',
                gateway: '',
                hostname: '',
                ihType: 1,
                ipAddress: '',
                ipAddrMode: 1,
                networkMask: '',
                password: '',
                secType: '',
                ssid: '', 
            }, this.deparam(that.options.dashConfigString)); 

            var dashConfigP = {
                dashId: this.options.MYREFERENCES.rowData.name,
                version: '',
                ssid: dashConfig.ssid,
                sectypeopenselected: parseInt(dashConfig.secType) == 0 ? 'selected' : '',
                sectypewpaselected: parseInt(dashConfig.secType) == 1 ? 'selected' : '',
                sectypewpa2selected: parseInt(dashConfig.secType) == 2 ? 'selected' : '',
                sectypewepselected: parseInt(dashConfig.secType) == 3 ? 'selected' : '',
                password: dashConfig.secKey,
                ipaddressingdhcpchecked: parseInt(dashConfig.ipAddrMode) == 1 ? 'checked' : '',
                ipaddressingstaticchecked: parseInt(dashConfig.ipAddrMode) == 2 ? 'checked' : '',
                staticIpAddress: dashConfig.ipAddress,
                networkMask: dashConfig.networkMask,
                gateway: dashConfig.gateway,
                dns: dashConfig.dns,
                ihtypeihboxchecked: parseInt(dashConfig.ihType) == 1 ? 'checked' : '',
                ihtypecloudchecked: parseInt(dashConfig.ihType) == 2 ? 'checked' : '',
                account: dashConfig.account,
                hostname: dashConfig.hostname,
            };
            
            //var key, keys = Object.keys(dashConfigP);
            //var n = keys.length;
            //var dashConfigHB = {}
            //while (n--) {
            //    key = keys[n];
            //    dashConfigHB[key.toLowerCase()] = dashConfigP[key];
            //}

            var filledForm = Handlebars.compile($(e.target).contents().find('body').html().split('}}=""').join('}}'))(dashConfigP);

            $(e.target).contents().find('body').html(filledForm);
            $(e.target)[0].contentWindow.init(); 

            $(e.target).contents().find("form").on("submit", function (e) {
                e.preventDefault();
                
                var dashconfig = $(e.target).serialize(); 
                var QP = new Core.Database.QueryParameters();
                QP.Add("AgentId", "INT", that.options.MYREFERENCES.rowData.id);
                QP.Add("DashConfigString", "VARCHAR", dashconfig); 

                app.CallProcedure(app.DatabaseNames.IH + ".WEB.SetDashConfiguration", QP, {
                    onSuccess: function (data) {
                        that.render(null, "SENDINGCONFIGURATION");
                    },
                }, app.ConnectionStrings.app);
            }); 
        }
        , displayFormLoaded: function (e) {
            var that = this;

            var dashConfig = _.extend({
                dns: '',
                gateway: '',
                hostname: '',
                ihType: 1,
                ipAddress: '',
                ipAddrMode: 1,
                networkMask: '',
                password: '',
                secType: '',
                ssid: '',
            }, this.deparam(that.options.sentConfigString));

            var secType;
            switch (parseInt(dashConfig.secType, 10)) {
                case 0:
                    secType = "Open"; 
                    break;
                case 1:
                    secType = "WPA";
                    break;
                case 2:
                    secType = "WPA2";
                    break;
                case 3:
                    secType = "WEP";
                    break;
            }

            var ipAddressing;
            switch (parseInt(dashConfig.ipAddrMode, 10)) {
                case 1:
                    ipAddressing = "DHCP";
                    break;
                case 2:
                    ipAddressing = "Static"; 
                    break; 
            }

            var ihType;
            switch (parseInt(dashConfig.ihType, 10)) {
                case 1:
                    ihType = "IHBox";
                    break;
                case 2:
                    ihType = "Cloud";
                    break;
            }

            var dashConfigP = {
                dashId: this.options.MYREFERENCES.rowData.name,
                version: '',
                ssid: dashConfig.ssid,
                secType: secType,
                password: '******',
                ipAddressing: ipAddressing,
                staticSettingsVis: (parseInt(dashConfig.ipAddrMode, 10) == 1) ? 'none' : 'block',
                staticIpAddress: dashConfig.staticIpAddress,
                networkMask: dashConfig.networkMask,
                gateway: dashConfig.gateway,
                dns: dashConfig.dns,
                ihType: ihType,
                accountVis: (parseInt(dashConfig.ihType, 10) == 1) ? 'none' : 'block',
                account: dashConfig.account,
                hostnameVis: (parseInt(dashConfig.ihType, 10) == 2) ? 'none' : 'block',
                hostname: dashConfig.hostname,
                result: 'Saved', 
            };            

            var filledForm = Handlebars.compile($(e.target).contents().find('body').html().split('}}=""').join('}}'))(dashConfigP);
            $(e.target).contents().find('body').html(filledForm);

            $(e.target).contents().find('body').find("#ip-static-settings").css("display", dashConfigP.staticSettingsVis);
            $(e.target).contents().find('body').find("#accn").css("display", dashConfigP.accountVis);
            $(e.target).contents().find('body').find("#hn").css("display", dashConfigP.hostnameVis);
        }
        , show: function () {

            if (!this.options._isRendered) {
                if (!this.options._isRendering) { this.options._isRendering = true; this.render(); }
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            //$backdrop = $('.modal-backdrop');

            //$backdrop.one('click', function () {
            //    if (self.options.content && self.options.content.trigger) {
            //        self.options.content.trigger('cancel', self);
            //    }

            //    self.trigger('cancel');
            //});

            //$(document).one('keyup.dismiss.modal', function (e) {
            //    e.which == 27 && self.trigger('cancel');

            //    if (self.options.content && self.options.content.trigger) {
            //        e.which == 27 && self.options.content.trigger('shown', self);
            //    }
            //});

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }
        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }
        , locksAdded: function (e) {
            e; 
        }
        , locksRemoved: function (lock) {
            if (lock && lock.get("name") == "GETDASHCONFIGURATION") {
                this.options.configurationCommandId = parseInt(lock.get("data"), 10); 
                if (!this.readConfigurationCommand()) {
                    this.render(null, null); 
                }
            }
            if (lock && lock.get("name") == "CONFIGUREDASH") {
                this.options.sentConfigString = lock.get("data"); 
                this.render(null, "CONFIGURATIONSAVED");
            }
        }
        , refresh: function () {
            try {

            } catch (Error) { }
        }
        , bindEvents: function () {
            app.models.locksManager.listenToCategory(
                this,
                ["add", "remove"],
                ["CONFIGUREDASH", "GETDASHCONFIGURATION"],
                this.locksAdded
            );
            app.models.locksManager.listenToCategory(
                this,
                ["remove"],
                ["CONFIGUREDASH", "GETDASHCONFIGURATION"],
                this.locksRemoved
            );
        }
        , close: function () {
            //stopping configuration command loop
            this.stopMonitoringConfigurationCommand();

            this.remove();
            this.unbind();
        }
        , preRender: function () {
            app.models.subnavbar.setAll(false); 
        }
        , reRender: function () {
        }
    });

    //DataSourcesConfiguration.Views.ConfigureDashWifiModal = Backbone.View.extend({
    //    template: "data-sources-configuration"
    //    , id: "configure-dash-wifi-modal"
    //    , title: "Configure Dash Wifi Modal"
    //    , className: "modal hide fade modal-wider"
    //    //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: true
    //    , initialize: function () {
    //        this.options.MYREFERENCES = {
    //            rowData: null
    //        };

    //        if (this.options.viewParams) {
    //            this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
    //        }

    //        this.options._isRendered = false;

    //        this.bindEvents();
    //        _.bindAll(this);
    //    },
    //    events: {
    //        'click .close': function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //        , "click #dash_wifi_configuration_btn_cancel": function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //        , "click #dash_wifi_configuration_btn_save": "_saveConfiguration"
    //        , "change #checkbox_securityKey_showChars": "_checkbox_showChars_onchange"
    //        , "change #encryptionType": "_encryptionType_onchange"
    //        , "focus #securityKey": function () {
    //            this.$("#cg_SECURITYKEY").removeClass("error"); 
    //        }
    //        , "focus #wifiSSID": function () {
    //            this.$("#cg_SSID").removeClass("error");
    //        }
    //    },

    //    render: function (container) {
    //        var that = this;
    //        var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

    //        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());

    //                //var frmConfig = that.$("#dash_wifi_configuration_form");
    //                //frmConfig.find("input,select").jqBootstrapValidation({
    //                //});
    //                this.$("#securityKey_icon_popover").popover({
    //                });
    //                that._updateSecurityKeyPopOverText(); 

    //                that.options._isRendered = true;
    //            }, true, customPath); 

    //        }, customPath, "dash_wifi_configuration_modal");

    //    }
    //    , _updateSecurityKeyPopOverText: function () {
    //        var securityOption = this.$("#encryptionType").val(); 
    //        var text = this.options.i18n[this.template].translate("encryption_helptext_" + securityOption).fetch(); 
            
    //        this.$("#securityKey_icon_popover").popover("destroy");
    //        this.$("#securityKey_icon_popover").popover({
    //            html: true
    //            , content: text
    //        }); 
    //    }
    //    , _saveConfiguration: function () {
    //        try {
    //            var frmConfig = this.$("#dash_wifi_configuration_form");
    //            var data = frmConfig.serializeArray();
    //            var valuesDict = {}; 
    //            for (var i in data) {
    //                valuesDict[data[i].name.toUpperCase()] = data[i].value;
    //            }

    //            valuesDict["SECURITYKEY"] = (Core.Object.Exist(valuesDict, 'SECURITYKEY')) ? valuesDict["SECURITYKEY"] : ""; 
    //            valuesDict["ACCOUNTNUMBER"] = app.models.user.get("accountNumber");
    //            valuesDict["AGENTID"] = this.options.MYREFERENCES.rowData.id;
    //            valuesDict["SERVERHOSTNAME"] = app.models.user.get("ihServerHost");

    //            var validated = this._validateConfiguration(valuesDict); 

    //            if (!validated.allValid) {
    //                this._showValidationErrors(validated); 
    //            } else {
    //                var valuesEnconded = Core.Json.Encode({ Values: valuesDict });
    //                var form = this.$("#data_hidden_form");
    //                var dataInput = form.find("#data_input_hidden_form");
    //                dataInput.val(valuesEnconded);
    //                form.submit();
    //                this.hide();
    //            }

    //        } catch (Error) { }
    //    }
    //    , _showValidationErrors: function (validated) {
    //        try {
    //            for (var i in validated) {
    //                if (!validated[i]) {
    //                    switch (i.toUpperCase()) {
    //                        case "SSID":
    //                            this.$("#cg_SSID").addClass("error"); 
    //                            break;
    //                        case "SECURITYKEY":
    //                            this.$("#cg_SECURITYKEY").addClass("error");
    //                            this.$("#securityKey_icon_popover").popover("show"); 
    //                            break; 
    //                    }
    //                }
    //            }
    //        } catch (Error) { }
    //    }
    //    , _validateConfiguration: function (values) {
    //        try {
    //            var validated = {
    //                allValid: true
    //            };
    //            var val; 
    //            for (var i in values) {
    //                validated[i] = false; 
    //                val = values[i];
    //                switch (i.toUpperCase()) {
    //                    case "SSID":
    //                        validated[i] = Core.String.ValidateEmpty(val); 
    //                        break;
    //                    case "SECURITYKEY":
    //                        switch (values["ENCRYPTIONTYPE"]) {
    //                            case "0":
    //                                validated[i] = (!Core.String.ValidateEmpty(val)); 
    //                                break;
    //                            case "1":
    //                            case "2":
    //                                var isHex = Core.Type.IsHexadecimal(val);
    //                                if (isHex && val.length == 64) {
    //                                    validated[i] = true; 
    //                                } else {
    //                                    if (val.length > 7 & val.length < 64)
    //                                        validated[i] = true; 
    //                                }
    //                                break; 
    //                            case "3":
    //                                var isHex = Core.Type.IsHexadecimal(val);
    //                                if (isHex && (val.length == 10 || val.length == 26)) {
    //                                    validated[i] = true;
    //                                } else {
    //                                    if (val.length == 5 || val.length == 13) {
    //                                        validated[i] = true; 
    //                                    }
    //                                }
    //                                break; 
    //                        }
    //                        break; 
    //                    default:
    //                        validated[i] = true; 
    //                        break;
    //                }
    //                if (!validated[i]) validated["allValid"] = false; 
    //            }
    //            return validated; 
    //        } catch (Error) { }
    //    }
    //    , _checkbox_showChars_onchange: function () {
    //        var chkboxShowChars = this.$("#checkbox_securityKey_showChars");
    //        var inputSecurityKey = this.$("#securityKey"); 
    //        if (chkboxShowChars.is(':checked')) {
    //            inputSecurityKey.attr("type", "text");
    //        } else {
    //            inputSecurityKey.attr("type", "password");
    //        }
    //    }
    //    , _encryptionType_onchange: function () {
    //        var encryptionType = this.$("#encryptionType");
    //        var passwordInput = this.$("#securityKey"); 
    //        switch (encryptionType.val()) {
    //            case "0":
    //                passwordInput.val("");
    //                passwordInput.prop("disabled", true);
    //                passwordInput.attr("maxlength", "0"); 
    //                break;
    //            case "1":
    //            case "2":
    //                passwordInput.prop("disabled", false);
    //                passwordInput.val("");
    //                passwordInput.attr("maxlength","64");
    //                break;
    //            case "3":
    //                passwordInput.prop("disabled", false);
    //                passwordInput.val("");
    //                passwordInput.attr("maxlength", "26");
    //                break; 
    //        }
    //        this.$("#cg_SECURITYKEY").removeClass("error");
    //        this._updateSecurityKeyPopOverText(); 
    //    }
    //    , show: function () {

    //        if (!this.options._isRendered) {
    //            this.render();
    //            setTimeout(this.show, 100);
    //            return;
    //        }

    //        var self = this,
    //        $el = this.$el;

    //        //creating modal
    //        $el.modal({
    //            keyboard: false
    //            , backdrop: "static"
    //        });

    //        //$backdrop = $('.modal-backdrop');

    //        //$backdrop.one('click', function () {
    //        //    if (self.options.content && self.options.content.trigger) {
    //        //        self.options.content.trigger('cancel', self);
    //        //    }

    //        //    self.trigger('cancel');
    //        //});

    //        //$(document).one('keyup.dismiss.modal', function (e) {
    //        //    e.which == 27 && self.trigger('cancel');

    //        //    if (self.options.content && self.options.content.trigger) {
    //        //        e.which == 27 && self.options.content.trigger('shown', self);
    //        //    }
    //        //});

    //        this.on('cancel', function () {
    //            self.hide();
    //        });

    //        return this;

    //    }

    //    , hide: function () {
    //        var self = this,
    //        $el = this.$el;

    //        $el.one('hidden', function onHidden(e) {
    //            // Ignore events propagated from interior objects, like bootstrap tooltips
    //            if (e.target !== e.currentTarget) {
    //                return $el.one('hidden', onHidden);
    //            }
    //            self.close();

    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('hidden', self);
    //            }

    //            self.trigger('hidden');
    //        });

    //        $el.modal('hide');
    //    }

    //    , refresh: function () {
    //        try {

    //        } catch (Error) { }
    //    }

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

    //    , close: function () {
    //        this.remove();
    //        this.unbind();
    //    }

    //    , preRender: function () {
    //        app.models.subnavbar.set("dateControl", false);
    //    }

    //    , reRender: function () {
    //    }
    //});

    DataSourcesConfiguration.Models.ConfigurePLCModal = Backbone.Model.extend({
        defaults: {
            connectionType: null,
            entryPoint: null,
            cpuRack: null,
            cpuSlot: null,
            cpuMpi: null,
            cpuIP: null,
            port: null,
            busSpeed: null,
            timeoutIPConnect: null,
            timeout: null,
            lokalMpi: null,
            comPort: null,
            comPortSpeed: null,
            comPortParity: null,
            netLinkReset: null,
            editMode: false,
            locked: false, 
        },
        initialize: function () {
        },
        fetch: function (agentId) {
            var that = this; 
            var QP = new Core.Database.QueryParameters();
            QP.Add("AgentId", "INT", agentId);
            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.GetPLCConfiguration", QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table.length > 0) {
                        data = data.Table[0];
                        var dataSourceAddress = (data && data["DataSourceAddress"]) ? data["DataSourceAddress"] : null; 

                        if (dataSourceAddress != null) {
                            $.ajax(app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/PLCConfiguration.aspx", {
                                type: 'POST',
                                data: { action: "DESERIALIZECONFIGURATION", configurationXML: encodeURIComponent(dataSourceAddress) },
                                dataType: "json",
                                success: function (data) {
                                    if (data.status == "OK") {
                                        var plcConfiguration = data.value; 
                                        var values = _.extend({}, that.attributes, {
                                            connectionType: plcConfiguration.ConnectionType,
                                            entryPoint: plcConfiguration.EntryPoint,
                                            cpuRack: plcConfiguration.CpuRack,
                                            cpuSlot: plcConfiguration.CpuSlot,
                                            cpuMpi: plcConfiguration.CpuMpi,
                                            cpuIP: plcConfiguration.CpuIP,
                                            port: plcConfiguration.Port,
                                            busSpeed: plcConfiguration.BusSpeed,
                                            timeoutIPConnect: plcConfiguration.TimeoutIPConnect,
                                            timeout: plcConfiguration.Timeout,
                                            lokalMpi: plcConfiguration.LokalMpi,
                                            comPort: plcConfiguration.ComPort,
                                            comPortSpeed: plcConfiguration.ComPortSpeed,
                                            comPortParity: plcConfiguration.ComPortParity,
                                            netLinkReset: plcConfiguration.NetLinkReset,
                                        });

                                        that.set(values);
                                    }
                                },
                                error: function (e) {
                                }
                            });
                        }
                    }
                },
            }, app.ConnectionStrings.app);
        },
    });

    DataSourcesConfiguration.Views.ConfigurePLCModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "configure-plc-modal"
        , title: "Configure PLC Modal"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                autoRefresh: {
                    enabled: true
                    , toid: null
                },
                rowData: null,
                rowModel: null, 
                plc_inner_form_template: null,
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
                this.options.MYREFERENCES.rowModel = this.options.viewParams.rowModel; 
            }

            this.options._isRendered = false;

            this.model = new DataSourcesConfiguration.Models.ConfigurePLCModal();

            this.locksChanged();

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_configuration_btn_close": function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_configuration_btn_save": "_saveConfiguration"
            , "click #plc_configuration_btn_edit": "_editConfiguration"
            , "click #plc_configuration_btn_cancel": "_cancelEditConfiguration"
            , "change .connection-type-select": "_connectionTypeChanged"
            //, "click .btn-entry-point": "_fillEntryPoints"
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                T.render.call(that, that.template, function (inner_form) {

                    that.options.MYREFERENCES.plc_inner_form_template = inner_form; 

                    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({
                            plc_name: that.options.MYREFERENCES.rowData.name, 
                        }));

                        var container = that.$el.find(".plc_inner_form_container");
                        container.html(that.options.MYREFERENCES.plc_inner_form_template({}));

                        that.lockedChanged();
                        that.agentConnectionStatusChanged(); 
                        that._startAutoRefresh(); 

                        that.options._isRendered = true;
                    }, true, customPath);

                }, customPath, "plc_inner_configuration_modal");

            }, customPath, "plc_configuration_modal");

        }

        , plcConfigurationChanged: function (m) {
            if (!this.model.get("editMode")) {
                var container = this.$el.find(".plc_inner_form_container");
                var connectionTypeSelect = this.$el.find(".connection-type-select");
                connectionTypeSelect.val(this.model.get("connectionType"));
                container.html(this.options.MYREFERENCES.plc_inner_form_template(this.model.toJSON()));
            }
        }

        , editModeChanged: function (m) {
            this._stopAutoRefresh(); 
            var editMode = this.model.get("editMode"); 
            var connectionTypeSelect = this.$el.find(".connection-type-select");
            connectionTypeSelect.prop("disabled", !editMode);

            var btnEdit = this.$el.find("#plc_configuration_btn_edit");
            var btnSave = this.$el.find("#plc_configuration_btn_save");
            var btnClose = this.$el.find("#plc_configuration_btn_close");
            var btnCancel = this.$el.find("#plc_configuration_btn_cancel");

            if (editMode) {
                btnEdit.addClass("hide");
                btnClose.addClass("hide");
                btnSave.removeClass("hide");
                btnCancel.removeClass("hide"); 
                this._connectionTypeChanged();
            } else {
                btnEdit.removeClass("hide");
                btnClose.removeClass("hide");
                btnSave.addClass("hide");
                btnCancel.addClass("hide");
                this._startAutoRefresh();
            }
        }

        , refresh: function () {
            try {
                this.model.fetch(this.options.MYREFERENCES.rowData.id);
            } catch (Error) { }
        }

        , _startAutoRefresh: function () {
            try {
                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._autoRefresh();
            } catch (Error) { }
        }

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

            this.refresh();

            if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(this._autoRefresh, 3000);
            }
        }

        , _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;
        }
        , locksChanged: function () {
            var locks = app.models.locksManager.getCategoryLocks(
                ["AGENTDISCONNECTED", "SETPLCADDRESS", "TAGSCONFIGCHANGE", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.options.MYREFERENCES.rowData.id, true
            );
            
            this.model.set("locked", (locks.length > 0));
        }
        , lockedChanged: function () {
            var that = this;
            var locked = this.model.get("locked");
            this.$el.find("#plc_configuration_btn_edit").prop("disabled", locked);
            this.$el.find("#plc_configuration_btn_save").prop("disabled", locked);

            var locks = app.models.locksManager.getCategoryLocks(
                ["AGENTDISCONNECTED", "SETPLCADDRESS", "TAGSCONFIGCHANGE", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.options.MYREFERENCES.rowData.id, true
            );
            var firstLock = (locks.length > 0) ? locks.at(0) : null; 

            var frmConfig = this.$("#plc_configuration_form");
            if (locked) {
                frmConfig.find(":input").each(function (inx, input) {
                    $(input).data("wasDisabled", $(input).prop("disabled"));
                    $(input).prop("disabled", true); 
                }); 
            } else {
                frmConfig.find(":input").each(function (inx, input) {
                    var wasDisabled = $(input).data("wasDisabled");
                    $(input).data("wasDisabled", null);
                    $(input).prop("disabled", wasDisabled);
                }); 
            }

            var agent_status_msj = this.$el.find(".agent-status-msj");
            var disconnected_msg = this.$el.find(".agent-disconnected-msg");
            var applying_msg = this.$el.find(".applying-config-msg");
            var locked_msg = this.$el.find(".locked-agent-msg");
            disconnected_msg.addClass("hide");
            applying_msg.addClass("hide");
            locked_msg.addClass("hide");
            agent_status_msj.addClass("hide"); 

            if (firstLock) {
                var msg_elem = null;
                switch (firstLock.get("name")) {
                    case "AGENTDISCONNECTED":
                        msg_elem = disconnected_msg;
                        break;
                    case "SETPLCADDRESS":
                        msg_elem = applying_msg;
                        break;
                    default:
                        msg_elem = locked_msg;
                        break;
                }
                if (msg_elem != null) msg_elem.removeClass("hide");
            } else {
                agent_status_msj.removeClass("hide"); 
            }
        }
        , agentConnectionStatusChanged: function () {
            var agent_status_msj = this.$el.find(".agent-status-msj");
            var status = this.options.MYREFERENCES.rowModel.get("status");

            var connected_template = _.template('<span style="font-size:14px;font-weight:bold;margin-top:5px;"><%= message %></span><span style="margin-left:5px;" class="fa-stack fa-lg"><i style="color: #00ff00;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #00ff00;" class="fa fa-check fa-stack-1x"></i></span>');
            var disconnected_template = _.template('<span style="font-size:14px;font-weight:bold;margin-top:5px;"><%= message %></span><span style="margin-left:5px;" class="fa-stack fa-lg"><i style="color: #ff0000;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #ff0000;" class="fa fa-exclamation fa-stack-1x"></i></span>');
            var loading_template = _.template('<span style="float:left;font-size:14px;font-weight:bold;margin-top:8px;"><%= message %></span><div style="margin-left:5px;height:31px;cursor:default;float:left;"><img style="width:30px;height:30px;" src="' + app.foldersRoot + '/assets/img/spinner22.gif" /></div>');

            var template, message; 
            switch (status) {
                case "CONNECTED":
                    template = connected_template;
                    message = this.options.i18n[this.template].translate("plc_configuration_modal_agent_status_connected").fetch();
                    break;
                case "CHANGINGPLCSERVER":
                    template = loading_template;
                    message = this.options.i18n[this.template].translate("plc_configuration_modal_agent_status_changingplcserver").fetch();
                    break;
                case "DISCONNECTED":
                    template = disconnected_template;
                    message = this.options.i18n[this.template].translate("plc_configuration_modal_agent_status_disconnected").fetch();
                    break;
                default:
                    template = loading_template; 
                    break; 
            }

            agent_status_msj.html(template({ message: message }));
        }
        , _editConfiguration: function () {
            this.model.set("editMode", true); 
        }

        , _cancelEditConfiguration: function () {
            this.model.set("editMode", false);
        }

        , _saveConfiguration: function () {
            try {
                var frmConfig = this.$("#plc_configuration_form");
                var data = frmConfig.serializeArray();

                frmConfig.find(':disabled[name]', this).each(function () {
                    data.push({ name: this.name, value: $(this).val() });
                });

                var names = (function () {
                    var n = [],
                        l = data.length - 1;
                    for (; l >= 0; l--) {
                        n.push(data[l].name);
                    }

                    return n;
                })(); 

                frmConfig.find('input[type="checkbox"]:not(:checked)').each(function () {
                    if ($.inArray(this.name, names) === -1) {
                        data.push({ name: this.name, value: 'off' });
                    }
                });

                var valuesDict = {};
                for (var i in data) {
                    valuesDict[data[i].name.toUpperCase()] = data[i].value;
                }

                //var validated = this._validateConfiguration(valuesDict);

                //if (!validated.allValid) {
                //    this._showValidationErrors(validated);
                //} else {
                var valuesEnconded = Core.Json.Encode({ Values: valuesDict });
                var form = this.$("#plc_data_hidden_form");
                var dataInput = form.find("#plc_data_input_hidden_form");

                //disabling edit button as soon as trying to apply changes.
                this.$el.find("#plc_configuration_btn_edit").prop("disabled", true); 

                //this.model.set("locked", true); 
                var that = this;
                $.ajax(form.attr("action"), {
                    type: 'POST',
                    data: { data: valuesEnconded, action: "SERIALIZECONFIGURATION" },
                    dataType: "json",
                    success: function (data) {
                        if (data.status == "OK") {
                            var QP = new Core.Database.QueryParameters();
                            QP.Add("AgentId", "INT", that.options.MYREFERENCES.rowData.id);
                            QP.Add("Value", "VARCHAR", data.value); 
                            
                            Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].[SetPLCAgentAddress]", QP, {
                                onSuccess: function (data) {
                                    that.model.set("editMode", false); 
                                }
                                , onFailure: function (data) {
                                    data;
                                }
                            }, app.ConnectionStrings.app);
                        } else {
                            //something went wrong.
                        }
                    },
                    error: function (e) {
                    }
                });

                //this.hide();
                //}

            } catch (Error) { }
        }
        , _connectionTypeChanged: function (e) {
            var select_target = (e && e.target) ? $(e.target) : this.$el.find(".connection-type-select");

            var default_values = {
                entryPoint: {
                    0: { val: "", disabled: true },
                    1: { val: "", disabled: true },
                    2: { val: "", disabled: true },
                    3: { val: "", disabled: true },
                    4: { val: "", disabled: true },
                    10: { val: "", disabled: true },
                    20: { val: "", disabled: true },
                    50: { val: "S7ONLINE", disabled: false },
                    122: { val: "", disabled: true },
                    123: { val: "", disabled: true },
                    223: { val: "", disabled: true },
                    224: { val: "", disabled: true },
                    230: { val: "", disabled: true },
                },
                cpuRack: {
                    0: { val: "", disabled: true },
                    1: { val: 0, disabled: false },
                    2: { val: 0, disabled: false },
                    3: { val: 0, disabled: false },
                    4: { val: 0, disabled: false },
                    10: { val: 0, disabled: false },
                    20: { val: "", disabled: true },
                    50: { val: 0, disabled: false },
                    122: { val: 0, disabled: false },
                    123: { val: 0, disabled: false },
                    223: { val: 0, disabled: false },
                    224: { val: 0, disabled: false },
                    230: { val: 0, disabled: false },
                },
                cpuSlot: {
                    0: { val: "", disabled: true },
                    1: { val: 2, disabled: false },
                    2: { val: 2, disabled: false },
                    3: { val: 2, disabled: false },
                    4: { val: 2, disabled: false },
                    10: { val: 2, disabled: false },
                    20: { val: "", disabled: true },
                    50: { val: 2, disabled: false },
                    122: { val: 2, disabled: false },
                    123: { val: 2, disabled: false },
                    223: { val: 2, disabled: false },
                    224: { val: 2, disabled: false },
                    230: { val: 2, disabled: false },
                },
                cpuMpi: {
                    0: { val: "", disabled: true },
                    1: { val: 2, disabled: false },
                    2: { val: 2, disabled: false },
                    3: { val: 2, disabled: false },
                    4: { val: 2, disabled: false },
                    10: { val: 2, disabled: false },
                    20: { val: "", disabled: true },
                    50: { val: 2, disabled: false },
                    122: { val: "", disabled: true },
                    123: { val: "", disabled: true },
                    223: { val: 2, disabled: false },
                    224: { val: 2, disabled: false },
                    230: { val: 2, disabled: false },
                },
                cpuIP: {
                    0: { val: "", disabled: true },
                    1: { val: "", disabled: true },
                    2: { val: "", disabled: true },
                    3: { val: "", disabled: true },
                    4: { val: "", disabled: true },
                    10: { val: "", disabled: true },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: "", disabled: false },
                    123: { val: "", disabled: false },
                    223: { val: "", disabled: false },
                    224: { val: "", disabled: false },
                    230: { val: "", disabled: false },
                },
                port: {
                    0: { val: "", disabled: true },
                    1: { val: "", disabled: true },
                    2: { val: "", disabled: true },
                    3: { val: "", disabled: true },
                    4: { val: "", disabled: true },
                    10: { val: "", disabled: true },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: 102, disabled: false },
                    123: { val: 102, disabled: false },
                    223: { val: 1099, disabled: false },
                    224: { val: 1099, disabled: false },
                    230: { val: 7777, disabled: false },
                },
                busSpeed: {
                    0: { val: "", disabled: true },
                    1: { val: 2, disabled: false },
                    2: { val: 2, disabled: false },
                    3: { val: 2, disabled: false },
                    4: { val: 2, disabled: false },
                    10: { val: 2, disabled: false },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: "", disabled: true },
                    123: { val: "", disabled: true },
                    223: { val: "", disabled: true },
                    224: { val: "", disabled: true },
                    230: { val: "", disabled: true },
                },
                timeoutIPConnect: {
                    0: { val: "", disabled: true },
                    1: { val: "", disabled: true },
                    2: { val: "", disabled: true },
                    3: { val: "", disabled: true },
                    4: { val: "", disabled: true },
                    10: { val: "", disabled: true },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: 5000, disabled: false },
                    123: { val: 5000, disabled: false },
                    223: { val: 5000, disabled: false },
                    224: { val: 5000, disabled: false },
                    230: { val: 5000, disabled: false },
                },
                timeout: {
                    0: { val: "", disabled: true },
                    1: { val: "", disabled: true },
                    2: { val: "", disabled: true },
                    3: { val: "", disabled: true },
                    4: { val: "", disabled: true },
                    10: { val: "", disabled: true },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: 5000000, disabled: false },
                    123: { val: 5000000, disabled: false },
                    223: { val: 5000000, disabled: false },
                    224: { val: 5000000, disabled: false },
                    230: { val: 5000000, disabled: false },
                },
                lokalMpi: {
                    0: { val: "", disabled: true },
                    1: { val: 0, disabled: false },
                    2: { val: 0, disabled: false },
                    3: { val: 0, disabled: false },
                    4: { val: 0, disabled: false },
                    10: { val: 0, disabled: false },
                    20: { val: "", disabled: true },
                    50: { val: "", disabled: true },
                    122: { val: "", disabled: true },
                    123: { val: "", disabled: true },
                    223: { val: 0, disabled: false },
                    224: { val: 0, disabled: false },
                    230: { val: 0, disabled: false },
                },
                comPort: {
                    0: { val: "", disabled: true },
                    1: { val: "1", disabled: false },
                    2: { val: "1", disabled: false },
                    3: { val: "1", disabled: false },
                    4: { val: "1", disabled: false },
                    10: { val: "1", disabled: false },
                    20: { val: "1", disabled: false },
                    50: { val: "1", disabled: false },
                    122: { val: "1", disabled: true },
                    123: { val: "1", disabled: false },
                    223: { val: "1", disabled: false },
                    224: { val: "1", disabled: false },
                    230: { val: "1", disabled: false },
                },
                comPortSpeed: {
                    0: { val: "", disabled: true },
                    1: { val: "38400", disabled: false },
                    2: { val: "38400", disabled: false },
                    3: { val: "38400", disabled: false },
                    4: { val: "38400", disabled: false },
                    10: { val: "38400", disabled: false },
                    20: { val: "38400", disabled: false },
                    50: { val: "", disabled: true },
                    122: { val: "", disabled: true },
                    123: { val: "", disabled: true },
                    223: { val: "", disabled: true },
                    224: { val: "", disabled: true },
                    230: { val: "", disabled: true },
                },
                comPortParity: {
                    0: { val: "", disabled: true },
                    1: { val: "n", disabled: false },
                    2: { val: "n", disabled: false },
                    3: { val: "n", disabled: false },
                    4: { val: "n", disabled: false },
                    10: { val: "n", disabled: false },
                    20: { val: "n", disabled: false },
                    50: { val: "n", disabled: true },
                    122: { val: "n", disabled: true },
                    123: { val: "n", disabled: true },
                    223: { val: "n", disabled: true },
                    224: { val: "n", disabled: true },
                    230: { val: "n", disabled: true },
                },
                netlinkReset: {
                    0: { val: "", disabled: true },
                    1: { val: "off", disabled: true },
                    2: { val: "off", disabled: true },
                    3: { val: "off", disabled: true },
                    4: { val: "off", disabled: true },
                    10: { val: "off", disabled: true },
                    20: { val: "off", disabled: true },
                    50: { val: "off", disabled: true },
                    122: { val: "off", disabled: true },
                    123: { val: "off", disabled: true },
                    223: { val: "off", disabled: false },
                    224: { val: "off", disabled: false },
                    230: { val: "off", disabled: true },
                }
            };

            var data_obj = {};
            var model_data = this.model.toJSON(); 
            var id = select_target.val(); 
            for (var v in default_values) {
                if (default_values[v][id] != null && default_values[v][id] != undefined) {
                    if (default_values[v][id].disabled != null && default_values[v][id].disabled != undefined && default_values[v][id].disabled == true) {
                        data_obj[v] = (default_values[v][id].val != null && default_values[v][id].val != undefined) ? default_values[v][id].val : default_values[v][id];
                        data_obj[v + "_disabled"] = true;
                    } else {
                        data_obj[v] = (model_data[v] != null && model_data[v] != undefined) ? model_data[v] : (default_values[v][id].val != null && default_values[v][id].val != undefined) ? default_values[v][id].val : default_values[v][id];
                    }
                } else {
                    data_obj[v] = ""; 
                }
            }

            var container = this.$el.find(".plc_inner_form_container");
            data_obj = _.extend(data_obj, { editMode: this.model.get("editMode") }); 
            container.html(this.options.MYREFERENCES.plc_inner_form_template(data_obj));
        }

        , _showValidationErrors: function (validated) {
            try {
                for (var i in validated) {
                    if (!validated[i]) {
                        switch (i.toUpperCase()) {
                            //case "SSID":
                            //    this.$("#cg_SSID").addClass("error");
                            //    break;
                            //case "SECURITYKEY":
                            //    this.$("#cg_SECURITYKEY").addClass("error");
                            //    this.$("#securityKey_icon_popover").popover("show");
                            //    break;
                        }
                    }
                }
            } catch (Error) { }
        }
        , _validateConfiguration: function (values) {
            try {
                var validated = {
                    allValid: true
                };
                var val;
                for (var i in values) {
                    validated[i] = false;
                    val = values[i];
                    switch (i.toUpperCase()) {
                        case "SSID":
                            validated[i] = Core.String.ValidateEmpty(val);
                            break;
                        case "SECURITYKEY":
                            switch (values["ENCRYPTIONTYPE"]) {
                                case "0":
                                    validated[i] = (!Core.String.ValidateEmpty(val));
                                    break;
                                case "1":
                                case "2":
                                    var isHex = Core.Type.IsHexadecimal(val);
                                    if (isHex && val.length == 64) {
                                        validated[i] = true;
                                    } else {
                                        if (val.length > 7 & val.length < 64)
                                            validated[i] = true;
                                    }
                                    break;
                                case "3":
                                    var isHex = Core.Type.IsHexadecimal(val);
                                    if (isHex && (val.length == 10 || val.length == 26)) {
                                        validated[i] = true;
                                    } else {
                                        if (val.length == 5 || val.length == 13) {
                                            validated[i] = true;
                                        }
                                    }
                                    break;
                            }
                            break;
                        default:
                            validated[i] = true;
                            break;
                    }
                    if (!validated[i]) validated["allValid"] = false;
                }
                return validated;
            } catch (Error) { }
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , 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
            app.models.locksManager.listenToCategory(
                this,
                ["add", "remove"],
                ["AGENTDISCONNECTED", "SETPLCADDRESS", "TAGSCONFIGCHANGE", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.locksChanged
            );

            this.listenTo(this.model, "change", this.plcConfigurationChanged);
            this.listenTo(this.model, "change:editMode", this.editModeChanged);
            this.listenTo(this.model, "change:locked", this.lockedChanged);
            this.listenTo(this.options.MYREFERENCES.rowModel, "change:status", this.agentConnectionStatusChanged); 
        }

        , close: function () {
            this._stopAutoRefresh(); 
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    //DataSourcesConfiguration.Views.ConfigurePLCModal = Backbone.View.extend({
    //    template: "data-sources-configuration"
    //    , id: "configure-plc-modal"
    //    , title: "Configure PLC Modal"
    //    , className: "modal hide fade modal-wider"
    //    //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: true
    //    , initialize: function () {
    //        this.options.MYREFERENCES = {
    //            autoRefresh: {
    //                enabled: true
    //                , toid: null
    //            },
    //            rowData: null,
    //            plc_inner_form_template: null,
    //        };

    //        if (this.options.viewParams) {
    //            this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
    //        }

    //        this.options._isRendered = false;

    //        this.model = new DataSourcesConfiguration.Models.ConfigurePLCModal();

    //        this.locksChanged();

    //        this.bindEvents();
    //        _.bindAll(this);
    //    },
    //    events: {
    //        'click .close': function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //    },
    //    render: function (container) {
    //        var that = this;
    //        var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

    //        T.render.call(this, this.template, function (tmp) {
    //            T.render.call(that, that.template, function (inner_form) {
    //                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());

    //                    var container = that.$el.find(".plc_inner_form_container");
    //                    container.html(that.options.MYREFERENCES.plc_inner_form_template({}));

    //                    that.options._isRendered = true;
    //                }, true, customPath);

    //            }, customPath, "plc_inner_configuration_modal");

    //        }, customPath, "plc_configuration_modal");

    //    }
    //    , refresh: function () {
    //        try {
    //        } catch (Error) { }
    //    }
    //    , show: function () {

    //        if (!this.options._isRendered) {
    //            this.render();
    //            setTimeout(this.show, 100);
    //            return;
    //        }

    //        var self = this,
    //        $el = this.$el;

    //        //creating modal
    //        $el.modal({
    //            keyboard: false
    //            , backdrop: "static"
    //        });

    //        $backdrop = $('.modal-backdrop');

    //        $backdrop.one('click', function () {
    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('cancel', self);
    //            }

    //            self.trigger('cancel');
    //        });

    //        $(document).one('keyup.dismiss.modal', function (e) {
    //            e.which == 27 && self.trigger('cancel');

    //            if (self.options.content && self.options.content.trigger) {
    //                e.which == 27 && self.options.content.trigger('shown', self);
    //            }
    //        });

    //        this.on('cancel', function () {
    //            self.hide();
    //        });

    //        return this;

    //    }

    //    , hide: function () {
    //        var self = this,
    //        $el = this.$el;

    //        $el.one('hidden', function onHidden(e) {
    //            // Ignore events propagated from interior objects, like bootstrap tooltips
    //            if (e.target !== e.currentTarget) {
    //                return $el.one('hidden', onHidden);
    //            }
    //            self.close();

    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('hidden', self);
    //            }

    //            self.trigger('hidden');
    //        });

    //        $el.modal('hide');
    //    }

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

    //    , close: function () {
    //        this._stopAutoRefresh();
    //        this.remove();
    //        this.unbind();
    //    }

    //    , preRender: function () {
    //    }

    //    , reRender: function () {
    //    }
    //});

    DataSourcesConfiguration.Models.DataBlock = Backbone.Model.extend({
        defaults: {
            name: null, 
            tagsCount: null,
            overrideAlias: false,
            status: "not-checked",
            conflicts: [],
            importDB: false,
            importedTags: [], 
        },
    });

    DataSourcesConfiguration.Collections.DataBlocks = Backbone.Collection.extend({
        model: DataSourcesConfiguration.Models.DataBlock,
        //fetch: function (e) {
        //}, 
    });

    DataSourcesConfiguration.Models.PLCMnemonicsImport = Backbone.Model.extend({
        defaults: {
            datablocks: null,
            filename: null,
            isMultiproject: false, 
            folderName: null,
            folders: null, 
        },
        initialize: function () {
            this.set("datablocks", new DataSourcesConfiguration.Collections.DataBlocks()); 
        }, 
    });

    DataSourcesConfiguration.Views.PLCMnemonicsImport = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "plc-mnemonics-import"
        , title: "PLC Mnemonics Import"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                rowData: null,
                dbs_grid: null, 
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.model = new DataSourcesConfiguration.Models.PLCMnemonicsImport({}); 

            this.options._isRendered = false;

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_mnemonics_import_btn_cancel": function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_mnemonics_import_btn_analyze_project": "_analizePLCProject"
            , "click #plc_mnemonics_import_btn_import": "_importPLCProject"
            , "click .fileinput-button": "_browseProjectFile"
            , "click .btn-select-project-folder": "selectProjectFromMultiproject"
            , "click .btn-change-multiproject-project": "changeProjectFromMultiproject"
            , "change #project_fileinput": "projectFileChanged",
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                    var ImportStatusCell = Backgrid.Cell.extend({
                        template: _.template("..."),
                        events: {
                        },
                        render: function () {
                            var not_checked = _.template('<div class="not-checked-icon-popover" style="height:31px;cursor:pointer;"><i style="color: #333;font-size:30px;" class="fa fa-circle-o"></i></div>');
                            var warning_template = _.template('<div class="warning-icon-popover" style="height:31px;cursor:pointer;"><span class="fa-stack fa-lg"><i style="color: #ff0000;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #ff0000;" class="fa fa-exclamation fa-stack-1x"></i></span></div>');
                            var success_template = _.template('<div style="height:31px;cursor:default;"><span class="fa-stack fa-lg"><i style="color: #00ff00;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #00ff00;" class="fa fa-check fa-stack-1x"></i></span></div>');
                            var loading_template = _.template('<div style="height:31px;cursor:default;"><img style="width:30px;height:30px;" src="' + app.foldersRoot + '/assets/img/spinner22.gif" /></div>');

                            switch (this.model.get("status").toUpperCase()) {
                                case "NOT-CHECKED":
                                    this.template = not_checked; 
                                    break; 
                                case "ERROR":
                                    this.template = warning_template; 
                                    break;
                                case "SUCCESS":
                                    this.template = success_template;
                                    break;
                                case "LOADING":
                                    this.template = loading_template;
                                    break;
                            }

                            this.$el.html(this.template());

                            if (this.model.get("status").toUpperCase() == "ERROR") {
                                var popover_error_message = that.options.i18n[that.template].translate("popover_message_errors_title").fetch() + "<br />";
                                var conflicts = this.model.get("conflicts");
                                
                                for (var i = 0, len = conflicts.length; i < len; i++) {
                                    var code = conflicts[i];
                                    var code_message = ""; 
                                    switch (code.toUpperCase()) {
                                        case "DB_NOT_FOUND":
                                            code_message = that.options.i18n[that.template].translate("code_message_DB_NOT_FOUND").fetch();
                                            break;
                                        case "TAG_NOT_FOUND":
                                            code_message = that.options.i18n[that.template].translate("code_message_TAG_NOT_FOUND").fetch();
                                            break;
                                        case "PLC_PROJECT_TAGS_COUNT_MISMATCH":
                                            code_message = that.options.i18n[that.template].translate("code_message_PLC_PROJECT_TAGS_COUNT_MISMATCH").fetch();
                                            break; 
                                    }

                                    popover_error_message += "- " + code_message + "<br/>"; 
                                }

                                this.$el.find(".warning-icon-popover").popover({
                                    trigger: "hover",
                                    html: true, 
                                    content: popover_error_message,
                                    placement: "top", 
                                }); 
                            }

                            if (this.model.get("status").toUpperCase() == "NOT-CHECKED") {
                                var popover_not_checked_message = that.options.i18n[that.template].translate("popover_message_not_checked").fetch() + "<br />";
                                this.$el.find(".not-checked-icon-popover").popover({
                                    trigger: "hover",
                                    html: true,
                                    content: popover_not_checked_message,
                                    placement: "top",
                                });
                            }

                            this.delegateEvents();
                            return this;
                        }, 
                        className: "align-center-cell", 
                    });

                    var columns = [
                    {
                        name: "",
                        cell: Backgrid.Extension.SelectRowCell.extend({
                            className: "select-row-cell renderable align-center-cell"
                        }),
                        headerCell: Backgrid.Extension.SelectAllHeaderCell.extend({
                            render: function () {
                                this.$el.empty().append('<span style="position: relative; top: 2px; margin-right: 2px;">' + that.options.i18n[that.template].translate("import_mnemonics_table_column_title_label").fetch() + '</span><input tabindex="-1" type="checkbox" /><i style="margin-left:2px;cursor:pointer;" class="fa fa-question-circle"></i>');

                                this.$el.find(".fa-question-circle").popover({
                                    trigger: "hover",
                                    html: true,
                                    content: that.options.i18n[that.template].translate("help_icon_message_import_mnemonics").fetch(),
                                    placement: "top",
                                });

                                this.delegateEvents();
                                return this;
                            },
                            className: "import-mnemonics-header-cell select-all-header-cell renderable"
                        }),
                    },
                    {
                        name: "override-alias",
                        label: that.options.i18n[that.template].translate("import_mnemonics_override_alias_table_column_title_label").fetch(),
                        editable: false,
                        sortable: false,
                        headerCell: Backgrid.HeaderCell.extend({
                            render: function () {
                                Backgrid.HeaderCell.prototype.render.apply(this, arguments);
                                this.$el.append($('<i style="margin-left:4px;cursor:pointer;" class="fa fa-question-circle"></i>'));
                                this.$el.find(".fa-question-circle").popover({
                                    trigger: "hover",
                                    html: true,
                                    content: that.options.i18n[that.template].translate("help_icon_message_override_alias").fetch(),
                                    placement: "top",
                                });
                                return this; 
                            }
                        }), 
                        cell: Backgrid.Cell.extend({
                            template: _.template("<input class='override-status-checkbox' tabindex='-1' type='checkbox' />"),
                            events: {
                                "change .override-status-checkbox": "chkboxChanged", 
                            },
                            chkboxChanged: function (e) {
                                this.model.set("overrideAlias", $(e.target).is(":checked"));
                            }, 
                            render: function () {
                                this.$el.html(this.template());
                                if (this.model.get("overrideAlias")) this.$el.find(".override-status-checkbox").attr("checked", "checked"); 
                                this.delegateEvents();
                                return this;
                            },
                            className: "align-center-cell", 
                        }), 
                    }, 
                    {
                        name: "name",
                        label: that.options.i18n[that.template].translate("import_mnemonics_name_table_column_title_label").fetch(),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            orderSeparator: '',
                            className: "string-cell align-center-cell",
                        })
                    }
                    //, {
                    //    name: "tagsCount",
                    //    editable: false,
                    //    label: "Tags Count", 
                    //    cell: Backgrid.StringCell.extend({
                    //        className: "string-cell align-center-cell"
                    //    })
                    //    }
                    , {
                        name: "status",
                        editable: false,
                        label: that.options.i18n[that.template].translate("import_mnemonics_status_table_column_title_label").fetch(),
                        editable: false,
                        sortable: false,
                        headerCell: Backgrid.HeaderCell.extend({
                            render: function () {
                                Backgrid.HeaderCell.prototype.render.apply(this, arguments);
                                this.$el.append($('<i style="margin-left:4px;cursor:pointer;" class="fa fa-question-circle"></i>'));
                                this.$el.find(".fa-question-circle").popover({
                                    trigger: "hover",
                                    html: true,
                                    content: that.options.i18n[that.template].translate("help_icon_message_status").fetch(),
                                    placement: "top",
                                });
                                return this;
                            }
                        }),
                        cell: ImportStatusCell, 
                    },
                    ];

                    // Initialize a new Grid instance
                    var grid; 
                    that.options.MYREFERENCES.dbs_grid = grid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("datablocks"),
                    });

                    // Render the grid and attach the root to your HTML document
                    that.$el.find(".datablocks-table").append(grid.render().el);

                    that.options._isRendered = true;
                }, true, customPath);

            }, customPath, "plc_mnemonics_import_modal");

        }
        , _analizePLCProject: function (e) {
            var analyze_btn = this.$("#plc_mnemonics_import_btn_analyze_project");
            var download_error_report_btn = this.$("#plc_mnemonics_import_btn_download_error_report");

            try {
                analyze_btn.attr("disabled", "disabled");
                download_error_report_btn.addClass("hide"); 

                var form = this.$("#plc_mnemonics_import_hidden_form");

                this.model.get("datablocks").forEach(function (model, index) {
                    model.set("status", "not-checked"); 
                }); 

                var selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels();
                this.options.MYREFERENCES.dbs_grid.$el.find(":input").prop("disabled", true); 

                var jsonData = {
                    dbs: [],
                    accountNumber: app.models.user.get("accountNumber"),
                    filename: this.model.get("filename"),
                    folderName: this.model.get("folderName"), 
                    agentId: this.options.MYREFERENCES.rowData.id,  
                };

                for (var i in selected) {
                    var s = selected[i];
                    s.set("status", "loading");

                    var db = { name: s.get("name"), overrideAlias: s.get("overrideAlias") };

                    jsonData.dbs.push(db);
                }

                var that = this;
                $.ajax(form.attr("action"), {
                    type: 'POST',
                    data: JSON.stringify(jsonData),
                    dataType: "json",
                    success: function (data) {
                        if (data && data["importedDBs"])
                            that._processImportedData(data);

                        that.options.MYREFERENCES.dbs_grid.$el.find(":input").prop("disabled", false);
                    },
                    error: function (e) {
                        analyze_btn.removeAttr("disabled");
                        that.options.MYREFERENCES.dbs_grid.$el.find(":input").prop("disabled", false);

                        for (var i in selected) {
                            var s = selected[i];
                            s.set("status", "not-checked");
                        }
                    }
                });
            } catch (Error) {
                analyze_btn.removeAttr("disabled");
                this.options.MYREFERENCES.dbs_grid.$el.find(":input").prop("disabled", false);

                for (var i in selected) {
                    var s = selected[i];
                    s.set("status", "not-checked");
                }
            }
        }
        , _importPLCProject: function (e) {
            var that = this;
            var analyze_btn = this.$("#plc_mnemonics_import_btn_analyze_project");
            var import_btn = this.$("#plc_mnemonics_import_btn_import");

            this.options.MYREFERENCES.dbs_grid.$el.find(":input").prop("disabled", true);
            analyze_btn.attr("disabled", "disabled");
            import_btn.attr("disabled", "disabled");

            var selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels();

            var tagsArr = []; 
            for (var i in selected) {
                if (selected[i].get("importDB")){
                    tagsArr = tagsArr.concat(selected[i].get("importedTags")); 
                }

                selected[i].set("status", "loading"); 
            }

            var tagsChunks = [];
            if (tagsArr.length > 500) {
                while (tagsArr.length > 500) {
                    tagsChunks.push(tagsArr.splice(0, 500));
                }
            } else {
                tagsChunks = [tagsArr]; 
            }

            var chunksImported = 0; 
            for (var i = 0; i < tagsChunks.length; i++) {
                var xml = this._getXML(tagsChunks[i], ["Id", "Name", "Alias", "HasConflicts"]);

                var QP = new Core.Database.QueryParameters();
                QP.Add("AgentID", "INT", this.options.MYREFERENCES.rowData.id);
                QP.Add("XML", "XML", xml);

                app.CallProcedure(app.DatabaseNames.IH + ".WEB.ImportPLCMnemonics", QP,
                {
                    onSuccess: function (data) {
                        chunksImported++;
                        if (chunksImported == tagsChunks.length) {
                            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("import_mnemonics_mnemonics_import_successful_message").fetch());
                            that.hide();
                        }
                    },
                    onFailure: function (data) {
                        data;
                    }
                },
                app.ConnectionStrings.app);
            }

        }
        , _getXML: function (data, cols) {
            cols = (_.isArray(cols)) ? cols : [];
            cols = _.invoke(cols, "toUpperCase");

            var xml = null;
            if (!data.length) data = [data];
            try {
                xml = '<XMLRoot>';
                for (var r = 0; r < data.length; r++) {
                    rowObj = data[r];
                    var row = '<Row ';
                    for (var c in rowObj) {
                        if ((cols.length == 0) || (cols.length > 0 && _.indexOf(cols, c.toString().toUpperCase()) != -1)) {
                            row += ((Trim(c).replace(' ', '')).replace('[', '')).replace(']', '') + '="' + rowObj[c] + '" ';
                        }
                    }
                    row += '/>';
                    row = row.replace(/#/g, '');
                    xml += row;
                }
                xml += '</XMLRoot>';
            } catch (Error) {
            }
            return xml;
        }
        , _processImportedData: function (data) {
            var analyze_btn = this.$("#plc_mnemonics_import_btn_analyze_project");
            var import_btn = this.$("#plc_mnemonics_import_btn_import");
            var download_error_report_btn = this.$("#plc_mnemonics_import_btn_download_error_report");

            try{
                var collection = this.model.get("datablocks");
                var importedDBs = (data && data["importedDBs"]) ? data["importedDBs"] : []; 

                var anyConflicts = false; 
                for (var i in importedDBs) {
                    var d = importedDBs[i];
                    var model = collection.findWhere({ name: d.Name });

                    if (model != null) {
                        if (d.HasConflicts == true) {
                            anyConflicts = true; 
                            model.set({
                                status: "error",
                                conflicts: d.Conflicts, 
                            }); 
                        } else model.set("status", "success");

                        model.set("importedTags", d.Tags); 
                    }
                }

                if (anyConflicts) {
                    var error_report_path = (data && data["errorReportPath"]) ? data["errorReportPath"] : "";
                    download_error_report_btn.prop("href", error_report_path);
                    download_error_report_btn.removeClass("hide");
                } else {
                    download_error_report_btn.addClass("hide");
                }

                import_btn.removeAttr("disabled");

            } catch (Error) {
                import_btn.attr("disabled", "disabled");
                analyze_btn.removeAttr("disabled");
                download_error_report_btn.addClass("hide");
            }
        }
        , _browseProjectFile: _.debounce(function () {
            this.$el.find("#project_fileinput").get(0).click();
        }, 500, true)
        , projectFileChanged: function () {
            var fileinput = this.$el.find("#project_fileinput").get(0);
            var files = fileinput.files;

            if (files.length > 0) {
                var file = files[0];
                var filename = file.name;

                this.$el.find(".input-project-filename").val(filename);
                this.uploadProjectFile(); 
            }
        }
        , uploadProjectFile: function () {
            try {

                this.$el.find(".fileinput-button").prop("disabled", true); 

                this.$el.find("#plc_mnemonics_import_btn_import").attr("disabled", "disabled");
                var download_error_report_btn = this.$("#plc_mnemonics_import_btn_download_error_report");
                download_error_report_btn.addClass("hide"); 

                var datablocksSection = this.$el.find(".datablocks-section");
                datablocksSection.addClass("hide");

                this.model.get("datablocks").each(function (model, i) {
                    model.trigger("backgrid:select", model, false);
                });

                this.model.get("datablocks").reset(); 

                var project_upload_progress = this.$el.find(".project-upload-progress");

                var that = this;

                var fileinput = $("#project_fileinput").get(0);
                var files = fileinput.files;
                var formData = new FormData();

                for (var i = 0; i < files.length; i++) {
                    var file = files[i];

                    // Add the file to the request.
                    formData.append('files[]', file, file.name);
                }

                formData.append("accountNumber", app.models.user.get("accountNumber"));
                formData.append("agentId", this.options.MYREFERENCES.rowData.id);
                formData.append("action", "UPLOAD"); 

                if (formData) {
                    project_upload_progress.removeClass("hide");

                    $.ajax({
                        url: app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/upload-project.aspx",
                        type: 'POST',
                        // handle the progress report
                        xhr: function () {  // Custom XMLHttpRequest
                            var myXhr = $.ajaxSettings.xhr();
                            if (myXhr.upload) { // Check if upload property exists
                                myXhr.upload.addEventListener('progress', that.uploadProjectProgressHandler, false); // For handling the progress of the upload
                            }
                            return myXhr;
                        },

                        // Form data
                        data: formData,

                        //Options to tell jQuery not to process data or worry about content-type.
                        cache: false,
                        contentType: false,
                        processData: false
                    })
                    .done(that.uploadProjectComplete)
                    .fail(that.uploadProjectFailed);
                }
            } catch (Error) { this.$el.find(".fileinput-button").prop("disabled", false); }
        }
        , uploadProjectProgressHandler: function (e) {
            var upload_progress_bar = this.$el.find(".project-upload-progress-bar");
            var loaded = e.loaded;
            var total = e.total;

            var percent = (loaded * 100) / total;
            upload_progress_bar.css("width", percent + "%");
        }
        , uploadProjectComplete: function (data) {
            this.$el.find(".fileinput-button").prop("disabled", false);
            this.$el.find(".project-upload-progress").addClass("hide");
            this.$el.find(".project-upload-progress-bar").css("width", "0%"); 

            if (data && data["status"] && data.status == "OK") {
                this.model.set("filename", (data && data["filename"]) ? data["filename"] : "");
                this.model.set("folders", data.folders);
                if (data.folders.length > 0) {
                    if (data.folders.length > 1) {
                        this.showMultiprojectSelection(data.folders);
                    } else {
                        this.model.set("folderName", data.folders[0]);
                        this.showProjectDBS(this.model.get("folderName")); 
                    }
                } else {
                    this.showUploadProjectFailedModal(); 
                }
            } else {
                this.showUploadProjectFailedModal();
            }
        }
        , showMultiprojectSelection: function (folders) {
            var project_folders_selector = this.$el.find(".project-folder-selector");
            var project_folders_select = this.$el.find(".mnemonics-project-folder-select");

            project_folders_select.find('option').remove().end();
            for (var finx in folders) {
                var folder_name = folders[finx];
                var opt_template = _.template("<option value='<%= name %>'><%= name %></option>")({
                    name: folder_name,
                });
                var project_folder_opt = $(opt_template);
                project_folders_select.append(project_folder_opt);
            }

            project_folders_selector.removeClass("hide");
        }
        , hideMultiprojectSelection: function () {
            var project_folders_selector = this.$el.find(".project-folder-selector");
            project_folders_selector.addClass("hide"); 
        }
        , selectProjectFromMultiproject: function () {
            var project_folders_select = this.$el.find(".mnemonics-project-folder-select");
            var selected_val = project_folders_select.val();
            this.model.set("folderName", selected_val); 

            this.hideMultiprojectSelection(); 
            this.showProjectDBS(this.model.get("folderName")); 
        }
        , changeProjectFromMultiproject: function () {
            this.$el.find(".datablocks-section").addClass("hide");
            var analyze_btn = this.$("#plc_mnemonics_import_btn_analyze_project");
            var import_btn = this.$("#plc_mnemonics_import_btn_import");
            var download_error_report_btn = this.$("#plc_mnemonics_import_btn_download_error_report");
            analyze_btn.attr("disabled", "disabled");
            import_btn.attr("disabled", "disabled");
            download_error_report_btn.addClass("hide");

            this.model.get("datablocks").each(function (model, i) {
                model.trigger("backgrid:select", model, false);
            });

            this.model.get("datablocks").reset();

            this.showMultiprojectSelection(this.model.get("folders")); 
        }
        , showProjectDBS: function (folderName) {
            var loading_bar = this.$el.find(".getting-dbs-from-project-file-loading-bar-section");
            loading_bar.removeClass("hide");

            var data = {
                action: "GETDBS", 
                accountNumber: app.models.user.get("accountNumber"),
                agentId: this.options.MYREFERENCES.rowData.id,
                filename: this.model.get("filename"),
                folderName: folderName, 
            };

            var that = this; 
            $.ajax(app.foldersRoot + "/app/custom-screens/IHConfiguration/data-sources-configuration-v2/api/upload-project.aspx", {
                type: 'POST',
                data: data,
                dataType: "json",
                success: function (data) {
                    loading_bar.addClass("hide");

                    if (data && data["status"] && data.status == "OK") {
                        that.$el.find(".datablocks-section-project-name").text(that.options.i18n[that.template].translate("datablocks_section_project_name").fetch(folderName));

                        that.$el.find(".datablocks-section").removeClass("hide");
                        var collection = that.model.get("datablocks");

                        collection.reset();
                        if (data && data["datablocks"]) {
                            for (var i in data["datablocks"]) {
                                var d = data["datablocks"][i];
                                var datablock = new DataSourcesConfiguration.Models.DataBlock({ name: d.Name, tagsCount: d.TagsCount });
                                collection.add(datablock);
                            }
                        }

                        //select-all by default
                        collection.each(function (model, i) {
                            model.trigger("backgrid:select", model, true);
                        });
                    }
                },
                error: function (e) {
                }
            });
        }
        , showUploadProjectFailedModal: function () {
            var i18n = this.options.i18n[this.template]

            var modal = new Modal.Views.Main({
                id: "upload-project-failed-modal"
                , title: i18n.translate("upload_project_failed_modal_title").fetch()
                , message: i18n.translate("upload_project_failed_modal_body").fetch()
                , allowCancel: false
                , buttons_type: "OK"
            });

            var that = this;
            modal.on("continue", function () {
            });
            modal.show(); 
        }
        , uploadProjectFailed: function () {
            this.$el.find(".fileinput-button").prop("disabled", false);
            this.showUploadProjectFailedModal(); 
        }
        , dbSelected: function (model, isSelected) {
            var selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels();

            model.set("importDB", isSelected); 
            if (isSelected) selected.push(model);
            else selected = _.filter(selected, function (t) {
                if (t.get("name") == model.get("name")) return false;
                return true; 
            }); 

            this.checkSelectedModels(selected); 
        }
        , checkSelectedModels: function (selected) {
            var analize_btn = this.$el.find("#plc_mnemonics_import_btn_analyze_project");
            var import_btn = this.$el.find("#plc_mnemonics_import_btn_import");

            var analized_count = _.countBy(selected, function (t) {
                if (t.get("status").toUpperCase() == "NOT-CHECKED") {
                    return "notChecked";
                }

                return "checked";
            });

            if (analized_count && analized_count["notChecked"] != null
                && analized_count["notChecked"] != undefined && analized_count["notChecked"] > 0) {
                analize_btn.removeAttr("disabled");
                import_btn.attr("disabled", "disabled");
            } else {
                if (analized_count && analized_count["checked"] && analized_count["checked"] > 0) {
                    import_btn.removeAttr("disabled");
                } else {
                    import_btn.attr("disabled", "disabled");
                }
                analize_btn.attr("disabled", "disabled");
            }
        }
        , overrideAliasChanged: function () {
            var selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels();
            this.checkSelectedModels(selected); 
        }
        , datablocksCollectionChanged: function (model) {
            if (model.hasChanged("overrideAlias")) {
                model.set("status", "not-checked"); 
                this.overrideAliasChanged(); 
            }

            if (model.hasChanged("status")) {
                if (model.get("status") == "not-checked") {
                    model.set("importedTags", []);
                }
            }
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            try {

            } catch (Error) { }
        }

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

        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });


    DataSourcesConfiguration.Models.ConflictDataBlockItem = Backbone.Model.extend({
        defaults: {
            id: null,
            name: '',
            statusDescription: '',
        },
    });

    DataSourcesConfiguration.Collections.ConflictDataBlocks = Backbone.Collection.extend({
        model: DataSourcesConfiguration.Models.ConflictDataBlockItem,
        fetch: function (agentId) {
            var that = this;
            var QP = new Core.Database.QueryParameters();
            QP.Add('@AgentId', 'INT', agentId);
            QP.Add('@Type', 'VARCHAR', 'DB_SYNC'); 

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".dbo.GetAgentItems", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        data = data.Table;

                        var models = [];
                        for (var i = 0, len = data.length; i < len; i++) {
                            var dataBlockStatus = data[i];

                            if ((true) && (dataBlockStatus.Status.toUpperCase() != "CONFLICT"))
                                continue;

                            var model = new DataSourcesConfiguration.Models.ConflictDataBlockItem({
                                id: dataBlockStatus.Id,
                                name: dataBlockStatus.Name,
                                statusDescription: dataBlockStatus.StatusDescription,
                            });

                            models.push(model);
                        }

                        that.reset(models);
                    }
                },
                Language: app.language,
            }, app.ConnectionStrings.app);
        }
    });

    DataSourcesConfiguration.Models.ConflictDataBlocks = Backbone.Model.extend({
        defaults: {
            datablocks: null,
            agentId: null,
            dbSelectedCount: 0,
        },
        initialize: function () {
            this.set("datablocks", new DataSourcesConfiguration.Collections.ConflictDataBlocks());
        },
    });

    DataSourcesConfiguration.Views.ConflictDataBlocks = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "conflicted-datablocks"
        , title: "Datablocs Conflicts"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                rowData: null,
                dbs_grid: null,
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.model = new DataSourcesConfiguration.Models.ConflictDataBlocks({
                agentId: this.options.MYREFERENCES.rowData.id,
            });

            this.listenTo(this.model, "change:dbSelectedCount", this.model_dbSelectedCount_change)

            this.options._isRendered = false;

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #conflicted_datablocks_btn_cancel": function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #conflicted_datablocks_btn_delete": function (event) {
                var i18n = this.options.i18n[this.template]

                var modal = new Modal.Views.Main({
                    id: "confirm-delete"
                    , title: i18n.translate("conflicted_datablocks_confirm_modal_title").fetch()
                    , message: i18n.translate("conflicted_datablocks_confirm_modal_body").fetch()
                    , allowCancel: true
                    , buttons_type: "CONTINUE-CANCEL"
                });

                var that = this;
                modal.on("continue", function () {
                    that.deleteDatablockConflictSelected();
                });

                modal.show();
            }
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                    var columns = [
                    {
                        name: "",
                        cell: Backgrid.Extension.SelectRowCell.extend({
                            className: "select-row-cell renderable align-center-cell"
                        }),
                        headerCell: Backgrid.Extension.SelectAllHeaderCell,
                    },
                    {
                        name: "name",
                        label: that.options.i18n[that.template].translate("conflicted_datablocks_modal_name_col_label").fetch(),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell",
                        })
                    }, {
                        name: "statusDescription",
                        label: that.options.i18n[that.template].translate("conflicted_datablocks_modal_description_col_label").fetch(),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            className: "string-cell align-center-cell"
                        })
                    },
                    ];

                    // Initialize a new Grid instance
                    var grid;
                    that.options.MYREFERENCES.dbs_grid = grid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("datablocks"),
                    });

                    // Render the grid and attach the root to your HTML document
                    that.$el.find(".datablocks-table").append(grid.render().el);


                    //var collection = this.model.get("datablocks");
                    //collection.reset();
                    //if (data && data["datablocks"]) {
                    //    for (var i in data["datablocks"]) {
                    //        var d = data["datablocks"][i];
                    //        var datablock = new DataSourcesConfiguration.Models.DataBlock({ name: d.Name, tagsCount: d.TagsCount });
                    //        collection.add(datablock);
                    //    }
                    //}


                    that.options._isRendered = true;


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

            }, customPath, "conflicted_datablocks_modal");

        }

        , deleteDatablockConflictSelected: function () {
            try {
                var that = this,
                    selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels(),
                    datablocksNames = [],
                    agentId = this.model.get("agentId");


                for (var i in selected)
                    datablocksNames.push(selected[i].get("name"));

                var QP = new Core.Database.QueryParameters();
                QP.Add('@AgentId', 'INT', agentId);
                QP.Add('@DataBlocksNames', 'VARCHAR', datablocksNames.toString());

                Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.DeleteDataBlocksConflict", QP, {
                    onSuccess: function (data) {
                        if ((data) && (!data.Message)) {
                            that.refresh();

                            app.views.topMessages.showMessage(
                                that.options.i18n[that.template].translate(
                                    "conflicted_datablocs_delete_success_msg"
                                ).fetch()
                            );                            
                        }
                        else
                        {
                            if (data.Message)
                                console.error(data.Message);

                            app.views.topMessages.showMessage(
                                that.options.i18n[that.template].translate(
                                    "conflicted_datablocs_delete_error_msg"
                                ).fetch()
                            );
                        }
                    },
                    onFailure: function (a, b, c) {
                        console.error(a);
                        console.error(b);
                        console.error(c);

                        app.views.topMessages.showMessage(
                            that.options.i18n[that.template].translate(
                                "conflicted_datablocs_delete_error_msg"
                            ).fetch()
                        );
                    }               
                }, app.ConnectionStrings.app);


            } catch (Error) { }
        }

        , dbSelected: function (model, isSelected) {
            var selected = this.options.MYREFERENCES.dbs_grid.getSelectedModels();
            var selected_count = selected.length;
            selected_count = (isSelected) ? selected_count + 1 : selected_count - 1;

            this.model.set("dbSelectedCount", selected_count);
        }

        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            this.model.get("datablocks").fetch(this.model.get("agentId"));
        }

        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            this.listenTo(this.model.get("datablocks"), "backgrid:selected", this.dbSelected);
            this.listenTo(this.model.get("datablocks"), "reset", this.collectionReset);
            this.listenTo(app.models.datablocksConflicts, "change:hasConflicts", this.datablocksConflictsChanged);
        }

        , collectionReset: function (collection) {
            var nodata = this.$el.find(".no-data-poster");

            if (collection.length > 0 && !nodata.hasClass("hide"))
                nodata.addClass("hide");
            else if (collection.length == 0)
                nodata.removeClass("hide").removeClass("fadeIn").outerWidth(nodata.outerWidth).addClass("fadeIn");

            this.model.set("dbSelectedCount", 0);
        }

        , model_dbSelectedCount_change: function (e) {
            var deleteBtn = this.$el.find("#conflicted_datablocks_btn_delete"),
                dbSelCount = this.model.get("dbSelectedCount");

            if (dbSelCount > 0)
                deleteBtn.removeAttr("disabled");
            else
                deleteBtn.attr("disabled", "disabled");
        }

        , datablocksConflictsChanged: function () {
            this.refresh();
        }

        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    //DataSourcesConfiguration.Views.AddLocalPLCModal = Backbone.View.extend({
    //    template: "data-sources-configuration"
    //    , id: "add-local-plc-modal"
    //    , title: "Add Local PLC"
    //    , className: "modal hide fade"
    //    //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: true
    //    , initialize: function () {
    //        if (this.options.viewParams) {
    //        }

    //        this.model = null; 

    //        this.options._isRendered = false;

    //        this.bindEvents();
    //        _.bindAll(this);
    //    },
    //    events: {
    //        'click .close': function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //        , "click .cancel": function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //    },

    //    render: function (container) {
    //        var that = this;
    //        var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

    //        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.options._isRendered = true;

    //            }, true, customPath);

    //        }, customPath, "conflicted_datablocks_modal");

    //    }

    //    , show: function () {

    //        if (!this.options._isRendered) {
    //            this.render();
    //            setTimeout(this.show, 100);
    //            return;
    //        }

    //        var self = this,
    //        $el = this.$el;

    //        //creating modal
    //        $el.modal({
    //            keyboard: false
    //            , backdrop: "static"
    //        });

    //        $backdrop = $('.modal-backdrop');

    //        $backdrop.one('click', function () {
    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('cancel', self);
    //            }

    //            self.trigger('cancel');
    //        });

    //        $(document).one('keyup.dismiss.modal', function (e) {
    //            e.which == 27 && self.trigger('cancel');

    //            if (self.options.content && self.options.content.trigger) {
    //                e.which == 27 && self.options.content.trigger('shown', self);
    //            }
    //        });

    //        this.on('cancel', function () {
    //            self.hide();
    //        });

    //        return this;

    //    }

    //    , hide: function () {
    //        var self = this,
    //        $el = this.$el;

    //        $el.one('hidden', function onHidden(e) {
    //            // Ignore events propagated from interior objects, like bootstrap tooltips
    //            if (e.target !== e.currentTarget) {
    //                return $el.one('hidden', onHidden);
    //            }
    //            self.close();

    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('hidden', self);
    //            }

    //            self.trigger('hidden');
    //        });

    //        $el.modal('hide');
    //    }

    //    , refresh: function () {
    //    }

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

    //    , close: function () {
    //        this.remove();
    //        this.unbind();
    //    }

    //    , preRender: function () {
    //    }

    //    , reRender: function () {
    //    }
    //});

    //models to use with the SelectDBS view.
    DataSourcesConfiguration.Models.SelectDBS = {}; 

    DataSourcesConfiguration.Models.SelectDBS.DataBlock = Backbone.Model.extend({
        defaults: {
            name: null,
            status: null,
            action: null,
            selected: false,
            new_action: null, 
        },
    });

    DataSourcesConfiguration.Collections.SelectDBS = {}; 

    var monitor_dbs_statuses = {
        no_monitoring: "NO_MON",
        //monitoring: "MON",
        stop_monitoring: "STOP_MON",
        start_monitoring: "START_MON",
        syncing: "SYNCING",
        unsyncing: "UNSYNCING",
        ok: "OK",
        conflict: "CONFLICT",
        command: "COMMAND", 
        fix_conflicts: "FIX_CONFLICTS",
        fixing_conflicts: "FIXING_CONFLICTS",
    };

    DataSourcesConfiguration.Collections.SelectDBS.DataBlocks = Backbone.Collection.extend({
        initialize: function () {
        }, 
        model: DataSourcesConfiguration.Models.SelectDBS.DataBlock,
        fill: function (data, parentModel) {
            isLocked = parentModel.get("isLocked");
            var syncing_dbs = parentModel.get("syncing_dbs"); 
            var unsyncing_dbs = parentModel.get("unsyncing_dbs"); 
            var fixing_dbs = parentModel.get("fixing_dbs"); 

            isLocked = (_.isBoolean(isLocked)) ? isLocked : false; 

            var new_actions = [];
            if (!isLocked) {
                new_actions = this.filter(function (i) {
                    if (i.get("new_action") != null) return true;
                    return false;
                });
            }

            if (new_actions.length > 0) {
                new_actions; 
            }

            var models = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var datablockData = data[i];

                var new_action = null;
                var selected = (datablockData.Status == monitor_dbs_statuses.conflict ||
                    datablockData.Status == monitor_dbs_statuses.ok ||
                    datablockData.Status == monitor_dbs_statuses.syncing ||
                    _.indexOf(syncing_dbs, datablockData.Name) != -1 ||
                    _.indexOf(fixing_dbs, datablockData.Name) != -1 ) ? true : false;

                if (new_actions.length > 0) {
                    var found = _.find(new_actions, function (i) { return i.get("id") == datablockData.Id && i.get("name") == datablockData.Name });
                    new_actions = _.without(new_actions, found);

                    if (found) {
                        new_action = found.get("new_action");
                        selected = found.get("selected"); 
                    }
                }

                var model = new DataSourcesConfiguration.Models.SelectDBS.DataBlock({
                    id: datablockData.Id,
                    name: datablockData.Name,
                    status: datablockData.Status,
                    selected: selected, 
                    new_action: new_action,
                });

                models.push(model);
            }

            this.set(models);
        }, 
        fetch: function (agentId) {
        }, 
    });

    DataSourcesConfiguration.Models.SelectDBS.Main = Backbone.Model.extend({
        defaults: {
            datablocks: null,
            isLocked: false,
            syncing_dbs: [],
            unsyncing_dbs: [],
            fixing_dbs: [],
            changes: 0,  
        },
        initialize: function () {
            this.set("datablocks", new DataSourcesConfiguration.Collections.SelectDBS.DataBlocks());
        },
        fetch: function (agentId) {
            var that = this;
            var QP = new Core.Database.QueryParameters();
            QP.Add('@AgentId', 'INT', agentId);

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.GetMonitorDBStatus", QP, {
                onSuccess: function (data) {
                    var datablocksData = data.Table;

                    that.get("datablocks").fill(datablocksData, that);
                },
                //Language: app.language,
            }, app.ConnectionStrings.app);
        }, 
    });

    DataSourcesConfiguration.Views.SelectDBS = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "plc-select-dbs"
        , title: "PLC Select DBS"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                autoRefresh: {
                    enabled: true
                    , toid: null
                }, 
                rowData: null,
                dbs_grid: null,
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.model = new DataSourcesConfiguration.Models.SelectDBS.Main({});

            this.dbsConfigLockCheck(); 

            this.options._isRendered = false;

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_monitor_dbs_close_btn": function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click #plc_monitor_dbs_apply_btn": "applyChanges"
        },

        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

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

                    var DBSelectedStatusCell = Backgrid.Cell.extend({
                        template: _.template("..."),
                        initialize: function () {
                            Backgrid.Cell.prototype.initialize.apply(this, arguments);
                            this.bindEvents();
                        },
                        events: {
                            "click .fix-conflicts-btn": "_fixConflicts"
                        },
                        _fixConflicts: function (e) {
                            e.preventDefault();
                            that.fixConflicts(this.model);
                        }, 
                        render: function () {
                            var no_status_template = _.template('<div class="status-icon-container" style="height:31px;cursor:pointer;"><span style="float:left;padding-left:3px;padding-right:3px;"><i style="color: #333;font-size:30px;" class="fa fa-circle-o"></i></span><div class="status-message-text"><span><%= status_message %></span></div></div>');
                            var warning_template = _.template('<div class="status-icon-container" style="height:31px;cursor:pointer;"><span style="float:left; " class="fa-stack fa-lg"><i style="color: #ff0000;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #ff0000;" class="fa fa-exclamation fa-stack-1x"></i></span><div class="status-message-text"><span><%= status_message %></span></div><button style="position:absolute; margin-top:4px; display:inline-block;" class="fix-conflicts-btn btn btn-danger btn-mini"><i class="icon-white icon-remove"></i> <%= fix_conflicts_btn_label %></button></div>');
                            var success_template = _.template('<div class="status-icon-container" style="height:31px;cursor:pointer;"><span style="float:left; " class="fa-stack fa-lg"><i style="color: #00ff00;" class="fa fa-circle-o fa-stack-2x"></i><i style="color: #00ff00;" class="fa fa-check fa-stack-1x"></i></span><div class="status-message-text"><span><%= status_message %></span></div></div>');
                            var loading_template = _.template('<div class="status-icon-container" style="height:31px;cursor:pointer;"><img style="width:30px;height:30px;float:left;" src="' + app.foldersRoot + '/assets/img/spinner30.gif" /><div class="status-message-text"><span><%= status_message %></span></div></div>');

                            var status = this.model.get("status").toUpperCase();

                            if (_.indexOf([monitor_dbs_statuses.no_monitoring, monitor_dbs_statuses.ok, monitor_dbs_statuses.conflict], status) != -1
                                && _.indexOf(_.union(that.model.get("syncing_dbs"), that.model.get("unsyncing_dbs"), that.model.get("fixing_dbs")), this.model.get("name")) != -1
                                ) {
                                status = monitor_dbs_statuses.command; 
                            }

                            switch (status) {
                                case monitor_dbs_statuses.no_monitoring:
                                    this.template = no_status_template;
                                    break;
                                case monitor_dbs_statuses.conflict:
                                    this.template = warning_template;
                                    break;
                                case monitor_dbs_statuses.command:
                                case monitor_dbs_statuses.syncing:
                                case monitor_dbs_statuses.unsyncing:
                                case monitor_dbs_statuses.fixing_conflicts:
                                case monitor_dbs_statuses.fix_conflicts:
                                    this.template = loading_template;
                                    break;
                                case monitor_dbs_statuses.ok:
                                    this.template = success_template;
                                    break; 
                            }

                            var status_message = "";
                            switch (status) {
                                case monitor_dbs_statuses.no_monitoring:
                                    status_message = that.options.i18n[that.template].translate("status_message_no_monitoring").fetch();
                                    break;
                                case monitor_dbs_statuses.conflict:
                                    status_message = that.options.i18n[that.template].translate("status_message_conflict").fetch();
                                    break;
                                case monitor_dbs_statuses.command:
                                    status_message = that.options.i18n[that.template].translate("status_message_sending_command").fetch();
                                    break;
                                case monitor_dbs_statuses.syncing:
                                    status_message = that.options.i18n[that.template].translate("status_message_syncing").fetch();
                                    break;
                                case monitor_dbs_statuses.unsyncing:
                                    status_message = that.options.i18n[that.template].translate("status_message_unsyncing").fetch();
                                    break; 
                                case monitor_dbs_statuses.fix_conflicts:
                                    status_message = that.options.i18n[that.template].translate("status_message_fix_conflicts").fetch();
                                    break;
                                case monitor_dbs_statuses.fixing_conflicts:
                                    status_message = that.options.i18n[that.template].translate("status_message_fixing_conflicts").fetch();
                                    break;
                                case monitor_dbs_statuses.ok:
                                    status_message = that.options.i18n[that.template].translate("status_message_ok").fetch();
                                    break;
                            }

                            this.$el.html(this.template({
                                status_message: status_message,
                                fix_conflicts_btn_label: that.options.i18n[that.template].translate("fix_conflicts_btn_label").fetch(), 
                            }));

                            if (status_message) {
                                //this.$el.find(".status-icon-container").popover({
                                //    trigger: "hover",
                                //    html: true,
                                //    content: status_message,
                                //    placement: "top",
                                //});
                            }

                            this.delegateEvents();
                            return this;
                        },
                        className: "",
                        bindEvents: function () {
                            this.listenTo(that.model, "change:isLocked", this.render);
                        },
                    });

                    var columns = [
                    //{
                    //    name: "",
                    //    cell: Backgrid.Extension.SelectRowCell.extend({
                    //        render: function () {
                    //            Backgrid.Extension.SelectRowCell.prototype.render.apply(this, arguments);
                    //            this.$el.find("input:checkbox").prop("checked", this.model.get("selected"));
                    //            this.$el.find("input:checkbox").prop("disabled", that.model.get("isLocked")); 
                    //            return this; 
                    //        }
                    //        , className: "select-row-cell renderable align-center-cell"
                    //    }),
                    //    headerCell: Backgrid.Extension.SelectAllHeaderCell, 
                    //},
                    {
                        name: "selected",
                        headerCell: Backgrid.HeaderCell.extend({
                            events: {
                                "change .monitor-db-select-all-checkbox": "_selectAll"
                            }, 
                            initialize: function () {
                                Backgrid.HeaderCell.prototype.initialize.apply(this, arguments);
                                this.bindEvents(); 
                            }
                            , _selectAll: function (e) {
                                var val = $(e.target).is(":checked"); 
                                this.collection.forEach(function (model, index) {
                                    model.set("selected", val, { from: "ui" });
                                }); 
                            }
                            , render: function () {
                                this.template = _.template("<input class='monitor-db-select-all-checkbox' tabindex='-1' type='checkbox' />");
                                this.$el.html(this.template());

                                this.$el.find(".monitor-db-select-all-checkbox").prop("disabled", that.model.get("isLocked"));

                                this.delegateEvents();
                                return this;
                            }, 
                            bindEvents: function () {
                                this.listenTo(that.model, "change:isLocked", this.render);
                            }, 
                        }),
                        cell: Backgrid.Cell.extend({
                            template: _.template("<input class='monitor-db-checkbox' tabindex='-1' type='checkbox' />"),
                            initialize: function () {
                                Backgrid.Cell.prototype.initialize.apply(this, arguments);
                                this.bindEvents(); 
                            }, 
                            events: {
                                "change .monitor-db-checkbox": "chkboxChanged",
                            },
                            chkboxChanged: function (e) {
                                this.model.set("selected", $(e.target).is(":checked"), { from: "ui" });
                            },
                            render: function () {
                                this.$el.html(this.template());
                                
                                this.$el.find(".monitor-db-checkbox").prop("disabled", that.model.get("isLocked"));
                                this.$el.find(".monitor-db-checkbox").prop("checked", this.model.get("selected"));
                                this.delegateEvents();
                                return this;
                            },
                            className: "align-center-cell",
                            bindEvents: function () {
                                this.listenTo(that.model, "change:isLocked", this.render);
                            }, 
                        }),
                    }, 
                    {
                        name: "name",
                        label: that.options.i18n[that.template].translate("select_dbs_name_table_column_title_label").fetch(),
                        editable: false,
                        cell: Backgrid.StringCell.extend({
                            orderSeparator: '',
                            className: "string-cell align-center-cell",
                        })
                    }
                    , {
                        name: "status",
                        editable: false,
                        label: that.options.i18n[that.template].translate("select_dbs_status_table_column_title_label").fetch(),
                        editable: false,
                        sortable: false,
                        headerCell: Backgrid.HeaderCell.extend({
                            render: function () {
                                Backgrid.HeaderCell.prototype.render.apply(this, arguments);
                                this.$el.append($('<i style="margin-left:4px;cursor:pointer;" class="fa fa-question-circle"></i>'));
                                this.$el.find(".fa-question-circle").popover({
                                    trigger: "hover",
                                    html: true,
                                    content: that.options.i18n[that.template].translate("select_dbs_status_help_icon_message_status").fetch(),
                                    placement: "top",
                                });
                                return this;
                            }
                        }),
                        cell: DBSelectedStatusCell,
                    },
                    ];

                    // Initialize a new Grid instance
                    var grid;
                    that.options.MYREFERENCES.dbs_grid = grid = new Backgrid.Grid({
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("datablocks"),
                    });

                    // Render the grid and attach the root to your HTML document
                    that.$el.find(".datablocks-table").append(grid.render().el);

                    that.options._isRendered = true;

                    that.checkApplyButton(); 

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

            }, customPath, "plc_select_dbs_modal");

        }
        , fixConflicts: function (m) {
            var that = this,
            selected = m,
            datablocksNames = [],
            agentId = this.options.MYREFERENCES.rowData.id;

            //stopping autorefresh, resuming after calling procedure
            this._stopAutoRefresh();

            datablocksNames.push(m.get("name"));

            var QP = new Core.Database.QueryParameters();
            QP.Add('@AgentId', 'INT', agentId);
            //QP.Add('@DataBlocksNames', 'VARCHAR', datablocksNames.toString());
            QP.Add('@Name', 'VARCHAR', m.get("name"));

            m.set("status", monitor_dbs_statuses.command); 
            this.model.set({ isLocked: true });
            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.[FixDataBlockConflicts]", QP, {
                onSuccess: function (data) {
                    if ((data) && (!data.Message)) {

                        app.models.locksManager.fetch({
                            async: false
                            , callback: function () {
                                if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();
                            }
                        });

                        //app.views.topMessages.showMessage(
                        //    that.options.i18n[that.template].translate(
                        //        "conflicted_datablocs_delete_success_msg"
                        //    ).fetch()
                        //);
                    }
                    else {
                        if (data.Message)
                            console.error(data.Message);

                        if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();

                        app.views.topMessages.showMessage(
                            that.options.i18n[that.template].translate(
                                "conflicted_datablocs_delete_error_msg"
                            ).fetch()
                        );
                    }
                },
                onFailure: function (a, b, c) {
                    console.error(a);
                    console.error(b);
                    console.error(c);

                    if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();

                    app.views.topMessages.showMessage(
                        that.options.i18n[that.template].translate(
                            "conflicted_datablocs_delete_error_msg"
                        ).fetch()
                    );
                }
            }, app.ConnectionStrings.app);
        }
        , dbSelected: function (model, a, ctx) {
            if (ctx.from == "ui") {
                var new_action = model.get("selected") ? monitor_dbs_statuses.start_monitoring : monitor_dbs_statuses.stop_monitoring; 
                var currentStatus = model.get("status"); 
                var validChange = false;
                
                switch(new_action){
                    case monitor_dbs_statuses.start_monitoring:
                        validChange = (currentStatus != monitor_dbs_statuses.ok); 
                        break; 
                    case monitor_dbs_statuses.stop_monitoring:
                        validChange = (currentStatus != monitor_dbs_statuses.no_monitoring); 
                        break; 
                }
                
                this.model.set("changes", this.model.get("changes") + ((validChange) ? 1 : -1)); 
                model.set("new_action", (validChange) ? new_action : null);
            }
        }
        , applyChanges: function () {
            var that = this; 
            this._stopAutoRefresh(); 
            var filtered = _.filter(this.model.get("datablocks").models, function (t) {
                return (t.get("new_action") != null); 
            });

            var no_monitoring = _.filter(filtered, function (t) {
                return (t.get("new_action") == monitor_dbs_statuses.stop_monitoring); 
            });

            if (no_monitoring.length > 0) {
                var no_monitoring_dbs_names = (_.pluck(_.pluck(no_monitoring, "attributes"), "name")).join(", "); 
                var modal = new Modal.Views.Main({
                    id: "check-unsync-dbs-options"
                    , title: this.options.i18n[this.template].translate("unsync_dbs_options_modal_title").fetch()
                    , message: this.options.i18n[this.template].translate("unsync_dbs_options_modal_message").fetch(no_monitoring_dbs_names)
                    , allowCancel: false
                    , buttons_type: "CUSTOM-BUTTONS"
                    , custom_buttons: [
                        { id: "keepdata", classNames: "", btn_lbl: this.options.i18n[this.template].translate("unsync_dbs_options_modal_btn_keep_data").fetch() },
                        { id: "wipedata", classNames: "", btn_lbl: this.options.i18n[this.template].translate("unsync_dbs_options_modal_btn_wipe_data").fetch() },
                        { id: "cancel", classNames: "", btn_lbl: this.options.i18n[this.template].translate("unsync_dbs_options_modal_btn_cancel").fetch() },
                    ]
                });

                modal.on("customButtonClicked", function (e) {
                    e.modal.hide();
                    if (e.buttonid != "cancel") {
                        var options = { unsyncOption: e.buttonid.toString().toUpperCase() };
                        _applyChanges_continue(options);
                    } else {
                        _applyChanges_cancel(); 
                    }
                });

                modal.show();
            } else {
                _applyChanges_continue({});
            }

            var that = this; 
            function _applyChanges_continue(options) {
                var changes = []; 
                _.each(filtered, function (i) {
                    changes.push(i.toJSON());
                    i.set({ new_action: null }, { silent: true });
                    i.set({ status: monitor_dbs_statuses.command });
                });

                var dbsChunks = [];
                if (changes.length > 500) {
                    while (changes.length > 500) {
                        dbsChunks.push(changes.splice(0, 500));
                    }
                } else {
                    dbsChunks = [changes]; 
                }
            
                that.model.set({ isLocked: true, changes: 0 });
                var chunksSent = 0;
                if (dbsChunks.length > 0) {
                    for (var i = 0; i < dbsChunks.length; i++) {
                        var xml = that._getXML(dbsChunks[i], ["id", "name", "new_action"]);

                        var QP = new Core.Database.QueryParameters();
                        QP.Add("AgentID", "INT", that.options.MYREFERENCES.rowData.id);
                        QP.Add("XML", "XML", xml);
                        QP.Add("StopMonitoringDataOption", "VARCHAR", (options && options.unsyncOption) ? options.unsyncOption : null); 

                        app.CallProcedure(app.DatabaseNames.IH + ".WEB.SetMonitorDBStatus", QP,
                        {
                            onSuccess: function (data) {
                                chunksSent++;
                                if (chunksSent == dbsChunks.length) {
                                    app.models.locksManager.fetch({
                                        async: false
                                        , callback: function () {
                                            if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();
                                        }
                                    });

                                    //app.views.topMessages.showMessage(that.options.i18n[that.template].translate("import_mnemonics_mnemonics_import_successful_message").fetch());
                                    //that.hide();
                                }
                            },
                            onFailure: function (data) {
                                if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();
                            }
                        },
                        app.ConnectionStrings.app);
                    }
                } else {
                    if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();
                }
            }

            function _applyChanges_cancel() {
                if (!that.options.MYREFERENCES.autoRefresh.enabled) that._startAutoRefresh();
            }
            
        }
        , _getXML: function (data, cols) {
            cols = (_.isArray(cols)) ? cols : [];
            cols = _.invoke(cols, "toUpperCase");

            var xml = null;
            if (!data.length) data = [data];
            try {
                xml = '<XMLRoot>';
                for (var r = 0; r < data.length; r++) {
                    rowObj = data[r];
                    var row = '<Row ';
                    for (var c in rowObj) {
                        if ((cols.length == 0) || (cols.length > 0 && _.indexOf(cols, c.toString().toUpperCase()) != -1)) {
                            row += ((Trim(c).replace(' ', '')).replace('[', '')).replace(']', '') + '="' + rowObj[c] + '" ';
                        }
                    }
                    row += '/>';
                    row = row.replace(/#/g, '');
                    xml += row;
                }
                xml += '</XMLRoot>';
            } catch (Error) {
            }
            return xml;
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }

        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }

        , refresh: function () {
            try {
                this.model.fetch(this.options.MYREFERENCES.rowData.id);
            } catch (Error) { }
        }

        , _startAutoRefresh: function () {
            try {
                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._autoRefresh();
            } catch (Error) { }
        }

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

            this.refresh();

            if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
                this.options.MYREFERENCES.autoRefresh.toid = setTimeout(this._autoRefresh, 3000);
            }
        }

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

        , checkCurrentTransaction: function (m) {
            var isLocked = this.model.get("isLocked");
            this.enableApplyButton(!isLocked); 
        }

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

            app.models.locksManager.listenToCategory(
                this,
                ["add", "remove"],
                ["TAGSCONFIGCHANGE", "SETPLCADDRESS", "AGENTDISCONNECTED", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                this.dbsConfigLockCheck
            );

            this.listenTo(this.model, "change:isLocked", this.checkApplyButton);
            this.listenTo(this.model, "change:changes", this.checkApplyButton);
        }

        , checkApplyButton: function () {
            var changesCount = this.model.get("changes");
            var isLocked = this.model.get("isLocked"); 

            this.enableApplyButton((isLocked) ? false : (changesCount < 1) ? false : true); 
        }

        , dbsConfigLockCheck: function (e) {
            var agentId = this.options.MYREFERENCES.rowData.id; 
            var startMonLock = app.models.locksManager.getCategoryLocks("DBSTARTMON", agentId);
            var stopMonLock = app.models.locksManager.getCategoryLocks("DBSTOPMON", agentId);
            var fixConflictsLock = app.models.locksManager.getCategoryLocks("DBFIXCONFLICTS", agentId);
            var allLocks = app.models.locksManager.getCategoryLocks(
                ["TAGSCONFIGCHANGE", "AGENTDISCONNECTED", "SETPLCADDRESS", "DBSTARTMON", "DBSTOPMON", "DBFIXCONFLICTS", "ENABLE", "DISABLE", "UNREGISTER", ],
                agentId, true
            );

            var startMonDBSarr = []; 
            if (startMonLock != null) {
                var startMonDBS = startMonLock.get("data");
                startMonDBSarr = startMonDBS.split(','); 
                
            }

            this.model.set("syncing_dbs", startMonDBSarr);

            var stopMonDBSarr = [];
            if (stopMonLock != null) {
                var stopMonDBS = stopMonLock.get("data");
                stopMonDBSarr = stopMonDBS.split(','); 
            }

            this.model.set("unsyncing_dbs", stopMonDBSarr);

            var fixConflictsDBSarr = []; 
            if (fixConflictsLock != null) {
                var fixConflictsDBS = fixConflictsLock.get("data");
                fixConflictsDBSarr = fixConflictsDBS.split(','); 
            }

            this.model.set("fixing_dbs", fixConflictsDBSarr);

            this.model.set("isLocked", (allLocks.length > 0));
        }

        , enableApplyButton: function (val) {
            var apply_btn = this.$el.find("#plc_monitor_dbs_apply_btn");
            apply_btn.prop("disabled", !val); 
        }

        , close: function () {
            this._stopAutoRefresh(); 
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.MigrateDataSourceModal = Backbone.View.extend({
        template: "data-sources-configuration"
        , id: "migrate-datasource-modal"
        , title: "Migrate Datasource Modal"
        , className: "modal hide fade modal-wider"
        //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: true
        , initialize: function () {
            this.options.MYREFERENCES = {
                nextStep: null,

                migration_info: {
                    id: null,
                    name: null,
                    address: null, 
                }, 
            };

            if (this.options.viewParams) {
            }

            this.options._isRendered = false;

            this.bindEvents();
            this.bindStepEvents(); 
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            'click .btn-close, .btn-cancel': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            'click .btn-next': "nextStep",
            'click .btn-generate-download': "generateCustomDownload",
            'click .btn-try-again': "generateCustomDownload", 
        },
        render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

            T.render.call(this, this.template, function (tmp) {
                //loading the view and appeding it to the views's $el.
                that.$el.html(tmp({}));
                that.options._isRendered = true;

                that.checkWizardStep(); 
            }, customPath, "migrate_datasource_modal");
        }
        , checkWizardStep: function () {
            var status = {
                enabled: this.model.get("enabled"), 
                registered: this.model.get("registered"), 
            };

            this.setStep(0);
        }
        , setStep: function (step) {
            var stepShown = this.$el.find(".step-shown");
            var currentStep = stepShown.data("step");
            stepShown.removeClass("step-shown").addClass("hide");

            if (currentStep) {
                this.trigger("step" + currentStep + "hidden", { status: "hidden" });
            }

            var stepToShow = this.$el.find("[data-step='" + step + "']");
            stepToShow.removeClass("hide").addClass("step-shown");
            this.trigger("step" + step + "shown", { status: "shown" });
        }
        , nextStep: function () {
            if (this.options.MYREFERENCES.nextStep) {
                var ns = this.options.MYREFERENCES.nextStep; 
                //resetting next step back to null, 
                this.options.MYREFERENCES.nextStep = null;

                this.setStep(ns);
            }
            else {
                var stepShown = this.$el.find(".step-shown");
                var currentStep = stepShown.data("step");
                this.setStep(parseInt(currentStep) + 1);
            }
        }
        , nextButton: function (bool) {
            var nextButton = this.$el.find(".btn-next");
            nextButton.prop("disabled", !bool); 
        }
        , _step0callback: function (data) {
            var that = this;
            var status = data.status;
            
            if (status == "shown") {
                //if it's already unregistered (therefore uninstalled) then skip step 1 and 1-alt
                if (!this.model.get("registered")) {
                    this.options.MYREFERENCES.nextStep = 4;

                    this.options.MYREFERENCES.migration_info.name = this.model.get("name");
                    this.options.MYREFERENCES.migration_info.address = this.model.get("address"); 
                }
            }
        }
        , _step1callback: function (data) {
            var that = this; 
            var status = data.status;

            this.options.MYREFERENCES.nextStep = 4;
            var registeredStatusChange = function () {
                if (!that.model.get("registered")) {
                    that.options.MYREFERENCES.migration_info.name = that.model.get("name");
                    that.options.MYREFERENCES.migration_info.address = that.model.get("address");
                }

                that.nextButton(!that.model.get("registered"));
            }; 

            if (status == "shown") {
                this.listenTo(this.model, "change:registered", registeredStatusChange);
                registeredStatusChange(); 
            }

            if (status == "hidden") {
                this.listenTo(this.model, "change:registered", registeredStatusChange); 
            }

            this.$el.find(".a-remote-deactivation").click(function () {
                that.setStep("1-alt"); 
            }); 
        }
        , _step1AltCallback: function () {
            this.nextButton(true); 
            this.options.MYREFERENCES.nextStep = 2;
        }
        , _step2callback: function (data) {
            var that = this;
            var status = data.status;
            var nextBtn = this.$el.find(".btn-next");
            var cancelBtn = this.$el.find(".btn-cancel");
            var closeBtn = this.$el.find(".btn-close");

            nextBtn.html('Start Migration');
        }
        , _step3callback: function (data) {
            var that = this; 
            var nextBtn = this.$el.find(".btn-next");
            var cancelBtn = this.$el.find(".btn-cancel");
            var closeBtn = this.$el.find(".btn-close");
            var uppercloseBtn = this.$el.find(".close");

            nextBtn.addClass("hide");
            cancelBtn.addClass("hide");
            closeBtn.addClass("hide");
            uppercloseBtn.addClass("hide");

            var QP = new Core.Database.QueryParameters();
            QP.Add("AgentId", "INT", this.model.get("id")); 

            var minTime = 3000;
            var startTime = new Date();

            var checkMinTime = function checkMinTime(st, mt, fn) {
                var current = new Date();
                var diff = Math.abs((st.getTime() - current.getTime()) / 1000);
                if (diff < (mt / 1000)) setTimeout(function () { checkMinTime(st, mt, fn); }, 100);
                else fn.call(this, fn); 
            }; 

            app.CallProcedure(app.DatabaseNames.IH + ".WEB.MigrateAgent", QP,
                {
                    onSuccess: function (data) {
                        checkMinTime(startTime, minTime, function () {
                            if (data && data.Table && data.Table[0]) {
                                data = data.Table[0];
                                if (data.Status == "OK") {
                                    _.extend(that.options.MYREFERENCES.migration_info, {
                                        id: data["Migrated_Id"],
                                        name: data["Migrated_Name"],
                                        address: data["Migrated_Address"],
                                    });

                                    that.$el.find(".download-custom-agent-button-section").addClass("hide"); 
                                    that.setStep(4);
                                    that.generateCustomDownload();
                                }
                            } else {
                                alert("something failed.");
                            }
                        }); 
                    },
                    onFailure: function (data) {
                        checkMinTime(startTime, minTime, function () {
                            alert("something failed."); 
                        }); 
                    }
                },
            app.ConnectionStrings.app);
        }
        , _step4callback: function (data) {
            var that = this; 
            var status = data.status;
            var nextBtn = this.$el.find(".btn-next");
            var cancelBtn = this.$el.find(".btn-cancel");
            var closeBtn = this.$el.find(".btn-close"); 

            if (status == "shown") {
                nextBtn.addClass("hide"); 
                cancelBtn.addClass("hide");
                closeBtn.removeClass("hide");
            }
        }
        , generateCustomDownload: function () {
            var frm = this.$el.find(".form-generate-download");
            var action = frm.prop("action");
            var systemType = this.model.get("systemType"); 
            var sourceName = "OPC"; 

            switch (systemType) {
                case "OPC":
                    sourceName = "OPC";
                    break;
                case "PLC":
                    sourceName = "PLCSiemensS7";
                    break;
            }

            var closeBtn = this.$el.find(".btn-close");
            var upperCloseBtn = this.$el.find(".close");
            closeBtn.addClass("hide");
            upperCloseBtn.addClass("hide");

            var downloadButtonSection = this.$el.find(".download-custom-agent-button-section");
            var startingDownload = this.$el.find(".starting-download");
            var downloadFailed = this.$el.find(".download-failed");

            downloadButtonSection.addClass("hide");
            startingDownload.addClass("hide");
            downloadFailed.addClass("hide");

            var downloadProgressSection = this.$el.find(".download-custom-agent-progress-section");
            downloadProgressSection.removeClass("hide"); 

            $.ajax({
                url: action,
                type: 'POST',
                data: {
                    accountnumber: app.models.user.get("accountNumber"),
                    sourceName: sourceName, 
                    agentName: this.options.MYREFERENCES.migration_info.name,
                    agentAddress: encodeURI(this.options.MYREFERENCES.migration_info.address), 
                },
                dataType: "json"
            })
            .done(this.generateCustomDownloadComplete)
            .fail(this.generateCustomDownloadFailed);
        }
        , generateCustomDownloadComplete: function (e) {
            var downloadProgressSection = this.$el.find(".download-custom-agent-progress-section");
            downloadProgressSection.addClass("hide");

            var startingDownload = this.$el.find(".starting-download");
            var downloadFailed = this.$el.find(".download-failed");

            this.$el.find(".btn-close").removeClass("hide");
            this.$el.find(".close").removeClass("hide");

            if (e && e.status && e.status == "OK") {
                startingDownload.removeClass("hide");
                this.$el.find(".download-direct-link").attr("href", e.path);

                //trigger automatic download
                location.href = e.path;
            } else {
                downloadFailed.removeClass("hide");
            }
        }
        , generateCustomDownloadFailed: function () {
            var downloadProgressSection = this.$el.find(".download-custom-agent-progress-section");
            downloadProgressSection.addClass("hide");

            var downloadFailed = this.$el.find(".download-failed");
            downloadFailed.removeClass("hide"); 

            this.$el.find(".btn-try-again").click(this.generateCustomDownload); 

            this.$el.find(".btn-close").removeClass("hide");
            this.$el.find(".close").removeClass("hide");
        }
        , bindStepEvents: function () {
            this.on("step0shown", this._step0callback);
            this.on("step1shown", this._step1callback);
            this.on("step1hidden", this._step1callback);
            this.on("step2shown", this._step2callback);
            this.on("step3shown", this._step3callback);
            this.on("step4shown", this._step4callback);
            this.on("step1-altshown", this._step1AltCallback);
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false,
                backdrop: 'static',
            });

            $backdrop = $('.modal-backdrop');

            //$backdrop.one('click', function () {
            //    if (self.options.content && self.options.content.trigger) {
            //        self.options.content.trigger('cancel', self);
            //    }

            //    self.trigger('cancel');
            //});

            //$(document).one('keyup.dismiss.modal', function (e) {
            //    e.which == 27 && self.trigger('cancel');

            //    if (self.options.content && self.options.content.trigger) {
            //        e.which == 27 && self.options.content.trigger('shown', self);
            //    }
            //});

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }
        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }
        , refresh: function () {
            try {
            } catch (Error) { }
        }
        , 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
        }
        , close: function () {
            this.remove();
            this.unbind();
        }
        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.ScreensModal = Backbone.View.extend({
        className: "modal hide fade modal-wider"
        //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
        , initialize: function () {
            this.options.MYREFERENCES = {
                nextScreen: null,
            };

            if (this.options.viewParams) {
            }

            this.options._isRendered = false;

            this.bindEvents();
            this.bindScreenEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            'click .btn-close, .btn-cancel': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            },
            'click .btn-next': "nextScreen",
        },
        render: function (container) {
            //var that = this;
            //var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

            //T.render.call(this, this.template, function (tmp) {
            //    //loading the view and appeding it to the views's $el.
            //    that.$el.html(tmp({}));
            //    that.options._isRendered = true;

            //    that.checkScreen();
            //}, customPath, "migrate_datasource_modal");
        }
        , checkScreen: function () {
            this.setScreen(0);
        }
        , setScreen: function (screen) {
            var screenShown = this.$el.find(".screen-shown");
            var currentScreen = screenShown.data("screen");
            screenShown.removeClass("screen-shown").addClass("hide");

            if (currentScreen) {
                this.trigger("screen[" + currentScreen + "]hidden", { status: "hidden" });
            }

            var screenToShow = this.$el.find("[data-screen='" + screen + "']");
            screenToShow.removeClass("hide").addClass("screen-shown");
            this.trigger("screen[" + screen + "]shown", { status: "shown" });
        }
        , nextScreen: function () {
            if (this.options.MYREFERENCES.nextScreen) {
                var ns = this.options.MYREFERENCES.nextScreen;
                //resetting next screen back to null, 
                this.options.MYREFERENCES.nextScreen = null;

                this.setScreen(ns);
            }
            else {
                var screenShown = this.$el.find(".screen-shown");
                var currentScreen = screenShown.data("screen");
                this.setScreen(parseInt(currentScreen) + 1);
            }
        }
        , nextButton: function (bool) {
            var nextButton = this.$el.find(".btn-next");
            nextButton.prop("disabled", !bool);
        }
        , setFooter: function (name) {
            this.$el.find(".modal-footer").addClass("hide");
            this.$el.find("." + name).removeClass("hide"); 
        }
        , setHeader: function (name) {
            this.$el.find(".modal-header").addClass("hide");
            this.$el.find("." + name).removeClass("hide");
        }
        , bindScreenEvents: function () {
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false,
                backdrop: 'static',
            });

            $backdrop = $('.modal-backdrop');

            //$backdrop.one('click', function () {
            //    if (self.options.content && self.options.content.trigger) {
            //        self.options.content.trigger('cancel', self);
            //    }

            //    self.trigger('cancel');
            //});

            //$(document).one('keyup.dismiss.modal', function (e) {
            //    e.which == 27 && self.trigger('cancel');

            //    if (self.options.content && self.options.content.trigger) {
            //        e.which == 27 && self.options.content.trigger('shown', self);
            //    }
            //});

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }
        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }
                self.close();

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');
            });

            $el.modal('hide');
        }
        , refresh: function () {
            try {
            } catch (Error) { }
        }
        , 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
        }
        , close: function () {
            this.remove();
            this.unbind();
        }
        , preRender: function () {
        }

        , reRender: function () {
        }
    });

    DataSourcesConfiguration.Views.RemoveClearDashModal = DataSourcesConfiguration.Views.ScreensModal.extend({
        template: "data-sources-configuration"
        , id: "remove-clear-dash-modal"
        , title: ""
        , className: "modal hide fade modal-wider"
        , events: _.extend(DataSourcesConfiguration.Views.ScreensModal.prototype.events, {
            "click .btn-clear-dash-data": "clearDashData",
            "click .btn-remove-dash": "removeDash", 
        })
        , render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";
            
            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;

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

                    that.options._isRendered = true;
                    that.checkScreen();
                }, true, customPath); 
            }, customPath, "remove_clear_dash_modal");
        }
        , checkScreen: function () {
            switch(this.options.viewParams.mode){
                case "DS-CLEAR-DATA":
                    this.setScreen("clear_dash_data");
                    break;
                case "DS-REMOVE":
                    this.setScreen("remove_dash");
                    break;
            }
        }
        , renderDOTsTable: function () {
            var dotModel = Backbone.Model.extend({
                defaults: {
                    id: null, 
                    name: null,
                    friendlyName: null,
                    connected: null, 
                }, 
            });
            var dotCollection = Backbone.Collection.extend({
                model: dotModel,
                fetch: function (dataSourceId) {
                    var that = this; 
                    var QP = new Core.Database.QueryParameters();
                    QP.Add("DataSourceId", "INT", dataSourceId); 

                    Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].GetDOTs", QP, {
                        onSuccess: function (data) {
                            if (data && data.Table) {
                                var data = data.Table;
                                var dotsArr = []; 
                                for (var i = 0, len = data.length; i < len; i++) {
                                    var dotData = data[i]; 
                                    var dm = new dotModel({
                                        id: dotData.Id, 
                                        name: dotData.Name,
                                        friendlyName: dotData.FriendlyName,
                                        connected: dotData.IsConnected, 
                                    });

                                    dotsArr.push(dm); 
                                }

                                that.set(dotsArr); 
                            }
                        }
                    }, app.ConnectionStrings.app);
                }, 
            });

            var dots = new dotCollection();

            var columns = [
                {
                    name: "name",
                    label: "Name",
                    editable: false,
                    sortable: false, 
                    cell: Backgrid.StringCell.extend({
                        orderSeparator: '',
                        className: "string-cell align-center-cell",
                    })
                },
                {
                    name: "friendlyName",
                    label: "Friendly Name",
                    editable: false,
                    sortable: false, 
                    cell: Backgrid.StringCell.extend({
                        orderSeparator: '',
                        className: "string-cell align-center-cell",
                    })
                },
                {
                    name: "connected",
                    label: "Connected",
                    editable: false,
                    sortable: false, 
                    cell: Backgrid.StringCell.extend({
                        orderSeparator: '',
                        className: "string-cell align-center-cell",
                    })
                },
            ];
            
            var grid = new Backgrid.Grid({
                className: "backgrid table table-hover",
                columns: columns,
                collection: dots,
            });

            this.$el.find(".section-screen:not(.hide)").find(".dots-list-container").append(grid.render().el);
            dots.fetch(this.model.get("id"));
        }
        , clearDashData: function () {
            var that = this; 
            var QP = new QueryParameters();
            QP.Add("@DataSourceId", "INT", this.model.get("id"));

            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_clear_data_action_message").fetch());

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.DeleteDataSourceHistory", QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table[0] && data.Table[0].Status == "OK") {
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_clear_data_message").fetch(), { stay: 3000 });
                    } else {
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_clear_data_error_message").fetch(), { stay: 3000 });
                    }

                    that.options.parent.refresh(); 
                }
                , onFailure: function () {
                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_clear_data_error_message").fetch(), { stay: 3000 });

                    that.options.parent.refresh();
                }
            }, app.ConnectionStrings.app);

            this.hide(); 
        }
        , removeDash: function () {
            var that = this;
            var QP = new QueryParameters();
            QP.Add("@DataSourceId", "INT", this.model.get("id"));
            QP.Add("@DeleteAllData", "BIT", true);

            app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_removed_action_message").fetch());

            Core.Json.CallProcedure(app.DatabaseNames.IH + ".WEB.DeleteDataSource", QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table[0] && data.Table[0].Status == "SUCCESS") {
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_removed_message").fetch(), { stay: 3000 });
                    } else {
                        app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_removed_error_message").fetch(), { stay: 3000 });
                    }

                    that.options.parent.refresh();
                }
                , onFailure: function () {
                    app.views.topMessages.showMessage(that.options.i18n[that.template].translate("dash_removed_error_message").fetch(), { stay: 3000 });

                    that.options.parent.refresh();
                }
            }, app.ConnectionStrings.app);

            this.hide();
        }
        , clear_dash_data_callback: function (data) {
            var that = this;
            var status = data.status;

            if (status == "shown") {
                this.setFooter("footer-1");
                this.renderDOTsTable(); 
            }
        }
        , remove_dash_callback: function (data) {
            var that = this;
            var status = data.status;

            if (status == "shown") {
                this.setFooter("footer-2");
                this.renderDOTsTable();
            }
        }
        , bindScreenEvents: function () {
            this.on("screen[clear_dash_data]shown", this.clear_dash_data_callback);
            this.on("screen[remove_dash]shown", this.remove_dash_callback);
        }
    }); 

    DataSourcesConfiguration.Views.RemoveDataSourceModal = DataSourcesConfiguration.Views.ScreensModal.extend({
        template: "data-sources-configuration"
        , id: "migrate-datasource-modal"
        , title: "Remove Datasource Modal"
        , className: "modal hide fade modal-wider"
        , events: _.extend(DataSourcesConfiguration.Views.ScreensModal.prototype.events, {
            "click .a-remote-deactivation": "remoteDeactivation_click",
            "click .btn-deactivate-and-remove": "deactivateAndRemove_click",
            "click .btn-remove-all-data": "removeAllData_click",
        })
        , render: function (container) {
            var that = this;
            var thatContainer = 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/IHConfiguration/data-sources-configuration-v2/";

            T.render.call(this, this.template, function (tmp) {
                //loading the view and appeding it to the views's $el.
                that.$el.html(tmp({}));
                that.options._isRendered = true;

                that.checkScreen();
            }, customPath, "remove_datasource_modal");
        }
        , checkScreen: function () {
            var registered = this.model.get("registered"); 

            if (registered) this.setScreen("prompt_uninstall");
            else this.setScreen("keep_delete_data"); 
        }
        , remoteDeactivation_click: function(){
            this.setScreen("remote_deactivation_explanation");
        }
        , deactivateAndRemove_click: function () {
            var that = this; 
            var QP = new Core.Database.QueryParameters();
            QP.Add("AgentId", "INT", this.model.get("id"));
            QP.Add("ClearData", "BIT", 1); 

            app.CallProcedure(app.DatabaseNames.IH + ".WEB.[UnregisterAgentRemotely]", QP,
                {
                    onSuccess: function (data) {
                        var status = (data && data.Table[0] && data.Table[0].Status == 1) ? true : false; 
                        that.options.parent.refresh();
                        that.hide();
                    },
                    onFailure: function (data) {
                        that.options.parent.refresh();
                        that.hide(); 
                    }
                },
            app.ConnectionStrings.app);
        }
        , removeAllData_click: function () {
            var QP = new Core.Database.QueryParameters();
            QP.Add("DataSourceId", "INT", this.model.get("id"));
            QP.Add("DeleteAllData", "BIT", 1);

            var that = this; 
            Core.Json.CallProcedure(app.DatabaseNames.IH + ".[WEB].DeleteDataSource", QP, {
                onSuccess: function (data) {
                    that.options.parent.refresh();
                    that.hide();
                }
            }, app.ConnectionStrings.app);
        }
        , _prompt_uninstall_callback: function (data) {
            var that = this;
            var status = data.status;

            if (status == "shown") {
                this.setFooter("footer-1"); 
            }
        }
        , _remote_deactivation_explanation_callback: function (data) {
            var that = this;
            var status = data.status;

            if (status == "shown") {
                this.setFooter("footer-2");
            }
        }
        , _keep_delete_data_callback: function (data) {
            var that = this;
            var status = data.status;

            if (status == "shown") {
                this.setFooter("footer-3");
            }
        }
        , bindScreenEvents: function () {
            this.on("screen[prompt_uninstall]shown", this._prompt_uninstall_callback);
            this.on("screen[remote_deactivation_explanation]shown", this._remote_deactivation_explanation_callback);
            this.on("screen[keep_delete_data]shown", this._keep_delete_data_callback);
        }
    });

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

});

