//SCREEN-BOILERPLATE

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

define([
    // Application variable, always include it to have access to app methods.
    'app',
  
    //templates-loader: this loads templates async.
    'js/templates-loader',
    'backgrid',
    'moment',
      'modules/modal2',
  
     // 'js/autocomplete/autocomplete',
    'backgrid/moment-cell',
    'js/jquery.clearsearch/jquery.clearsearch',
    'js/jstree/jstree',
      'backgrid/infinator',
      'js/autocomplete/backbone.autocomplete',
      'js/multiselect/virtual-select.min',
  ],
      function (app, T, Backgrid, moment, Modal) {
      var Screen = { Models: {}, Views: {}, Collections: {},
  
          SEARCH_MODE : 1, SHIFT_NAVIGATION_MODE: 2,
          MODAL_PICKER: 4, MODAL_DATA_ENTRY: 5,
  
      };
  
      Screen.Models.Main = Backbone.Epoxy.Model.extend({
          defaults: {
  
              crews: [],
              logEntryTypes: [],
              shifts: [],
              users: [],
  
              typesSelected: [],
              start: new moment().format('MM/DD/YYYY'),
              end: new moment().format('MM/DD/YYYY'),
              crewId: '-',
              logEntryTypeId: '-',
              shiftId: '-',
              searchText: '',
              author: '',
              id: '-',
              selectedDate: new moment().format('MM/DD/YYYY HH:mm:ss'),
              selectedShift: 'D',
              userId: '-',
  
              itemId: '',
              itemTitle: '',
              itemDate: new moment().format('YYYY-MM-DD'),
              itemShift: '',
              itemCrew: '',
              itemAuthor: '',
              itemDescription: '',
              itemLogEntryType: '',
              itemTime: '', 
              itemEquipment: '',
              itemProductionDate: new moment().format('YYYY-MM-DD'),
              showShiftPickers: '',
              showDataEntryMode: '',
              currentMode: Screen.SEARCH_MODE,
  
              equipmentTable: [],
              equipmentCodeId: null,
              equipmentCodeName: '',
              modalSelected: Screen.MODAL_PICKER,
              equipmentPickerName: '',
              equipmentDataEntryName: '',
              index: null,
              hasData: false,
              isLoading: 0,
              grid: null,
              lockTitle: true,
  
              writePermissions: false,
          },
          initialize: function () {
              this.fetchPickers({ async: false });
          },
  
          changeSelectedItem: function (item) {
              if (item) {
                  this.set({
                      itemTitle: item.get('title'),
                      itemId: item.get('id'),
                      itemCrew: item.get('crew'),
                      itemShift: item.get('shift'),
                      itemAuthor: item.get('author'),
                      itemDate: new moment(item.get('time'), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD'),
                      itemDescription: item.get('description'),
                      itemLogEntryType: item.get('logEntryType'),
                      equipmentDataEntryName: item.get('equipmentCodeName'),
                      itemEquipment: item.get('equipment'),
                      itemTime: new moment(item.get('time'), 'YYYY-MM-DD HH:mm:ss').format('HH:mm:ss'),
                      itemProductionDate: new moment(item.get('productionDate')).format('YYYY-MM-DD'),
                  });
              }
              else {
                  this.set(this.defaults);
              }
          },
  
          fetchPickers: function (options) {
              var that = this,
                  qp = new Core.Database.QueryParameters(),
                  opt = _.extend({ async: true, }, options);
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.LogBook.GetLogBookCatalogs',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              if ((resp) && (resp.Table)) {
                                  _.each(resp.Table, function (obj) {
                                      var tableKey = 'Table' + obj.Index;
                                      switch (obj.Name) {
                                         case 'CREWS':
                                              that.set('crews', _.map(resp[tableKey], function (obj) {
                                                  return {
                                                      value: obj.Crew,
                                                      label: obj.Crew,
                                                  };
                                              }));
                                              break;
                                          case 'SHIFTS':
                                              that.set('shifts', _.map(resp[tableKey], function (obj) {
                                                  return {
                                                      value: obj.Shift,
                                                      label: obj.Shift,
                                                  };
                                              }));
                                              break;
  
                                          case 'LOGENTRYTYPES':
                                              that.set('logEntryTypes', _.map(resp[tableKey], function (obj) {
                                                  return {
                                                      value: obj.LogEntryTypeId,
                                                      label: obj.LogEntryTypeName,
                                                  };
                                              }));
                                              break;
                                          case 'EQUIPMENTS':
                                              newItems = [];
                                              _.each(resp[tableKey], function (obj) {
                                                      newItems.push({
                                                          id: obj.Id,
                                                          equipmentId: obj.EquipmentId,
                                                          name: obj.EquipmentName,
                                                  });
                                                  that.set('equipmentTable', newItems);
                                              });
                                          break;
                                          case 'USERS':
                                              that.set('users', _.map(resp[tableKey], function (obj) {
                                                  return {
                                                      name: obj.Author,
                                                  };
                                              }));
                                          break;
                                      }
                                  });
                              }
                              else {
                                  if ((resp) && (resp.Message))
                                      console.error(new Error(resp.Message).stack);
                                  else
                                      console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                              }
                          }
                          catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                      },
                      onFailure: function (resp) {
                          console.error(resp);
                      },
                      Secured: true,
                      Async: opt.async,
                  },
                  app.ConnectionStrings.app
              );
  
              return this;
          },
  
  
      });
  
      //the generate id method is called everytime a view is going to be shown by the router and returns and id that
      //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
      //this is useful in case your view is reusable, and displays different data depending on url parameters 
      //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
      //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
      Screen.generateID = function (viewParams) {
          try {
              //if the viewparams change the view id, then evaluate the viewparams here
              //and return the appropiate id.refreshbtn
              return 'log-book';
          } catch (Error) { }
      }
      Screen.Models.Users = Backbone.Model.extend({
          label: function () {
              return this.get("name");
          }
      });
  
      Screen.Collections.Users = Backbone.Collection.extend({
              model: Screen.Models.Users,
      });
  
      Screen.Views.Main = Backbone.Epoxy.View.extend({
          template: 'log-book'
          , id: 'log-book'
          , title: 'Melting Log Book'
  
          //default not cacheable, change this if you want the view to be cacheable
          // if the view is set as cacheable should also have a _refresh method to reset the view without erasing the DOM.
          , isCacheable: false
          , events: function () {
              return {
                  'click #addItemBtn': this.addItemBtn_click,
                  'click #addElectrodeBtn': this.addElectrodeBtn_click,
                  'click #deleteItemBtn': this.deleteItemBtn_click,
                  'click #refreshBtn': this.refreshBtn_click,
                  'click #saveItemBtn': this.saveItemBtn_click,
                  'click #forwardNavBtn': this.forwardNavBtn_click,
                  'click #backNavBtn': this.backNavBtn_click,
                  'click #shiftViewBtn': this.shiftViewBtn_click,
                  'click #searchViewBtn': this.searchViewBtn_click,
                  'click #excelBtn': this.excelBtn_click,
                  'click #equipmentPicker': this.equipmentPicker_click,
                  'click #equipmentEntry': this.equipmentEntry_click,
                  'keypress #searchTbx': this.searchTbx_keypress,
                  'click #showSearchItemsBtn': this.showSearchItemsBtn_click,
              };
          }
          , bindings: 'data-bind'
          , setIdNull: false
          , itemsColl: null
          , searchTbx: null
          , initialize: function () {
              this.options.state = app.view_states.loading;
              this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };
             
              this.model = new Screen.Models.Main();
              this.itemsColl = new Screen.Collections.Items();
  
              this.model.set('writePermissions', this.getPermissions());
              this.bindEvents();
  
        
          }
          , getPermissions: function () {
              var write = $.inArray('logbook_readWrite', app.models.user.get('roles'));
              var ctx = {
                  write: write != -1 ? true : false,
              };
              return ctx.write;
          }
  
          , equipmentPicker_click: function () {
              this.model.set('modalSelected', Screen.MODAL_PICKER);
              this.showEquipmentModal();
          }
          , equipmentEntry_click: function () {
              this.model.set('modalSelected', Screen.MODAL_DATA_ENTRY);
              this.showEquipmentModal();
          }
  
          , showEquipmentModal: function () {
              this.EquipmentModal = new Screen.Views.EquipmentModal({
                  parent: this,
              });
              this.EquipmentModal.setEquipmentCodes();
              this.EquipmentModal.show();
          }
  
          , render: function (container, viewParams) {
              var that = this;
              var thatContainer = (this.options.container) ? this.options.container : container;
              this.options.container = thatContainer;
              //the screens have a custompath, so it has to be specified in the customPath variable that is
              //then sent to the template loader.
              var customPath = '/app/custom-screens/' + this.template + '/';
  
              T.render.call(
                  this,
                  this.template,
                  function (tmp) {
  
                      //getInternationalizationData
                      if (!that.options.i18n) that.options.i18n = {};
                      
                      app.getI18NJed(
                          that,
                          that.template,
                          function (i18nJED) {
                              //storing internationalization data
                              that.options.i18n[that.template] = i18nJED;
                              that.$el.html(tmp());
                              that.applyBindings();
                              that.append(thatContainer, that.$el);
                              //var write = that.getPermissions();
  
  
                              var Users = new Screen.Collections.Users()
                              _.each(that.model.get('users'), function (obj) {
                                  Users.add(obj);
                              });
                              new AutoCompleteView({
                                  input: $("#search"),
                                  minKeywordLength: 1,
                                  model: Users,
                              }).render();
  
                              var grid = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'time',
                                          label: app.translate(that, 'item_datetime_col_label'),
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'string-cell align-center-cell time-column',
                                              modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                              displayFormat: app.translate([that, app], 'YYYY-MM-DD HH:mm'),
                                          }),
                                      },
                                      {
                                          name: 'crew',
                                          label: app.translate(that, 'item_crew_col_label'),
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell crew-column',
                                          }),
  
                                      },
                                      {
                                          name: 'title',
                                          label: app.translate(that, 'item_title_col_label'),
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell title-column',
                                          }),
                                      },
                                      {
                                          name: 'desc',
                                          label: app.translate(that, 'item_description_col_label'),
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell desc-column',
                                          }),
                                      },
                                      {
                                          name: 'logEntryTypeName',
                                          label: 'Type',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  row: Backgrid.Row.extend({
                                      initialize: function (options) {
                                          Backgrid.Row.prototype.initialize.apply(this, arguments);
                                          var title = this.model.toJSON().title;
                                          if (title[0] == 'A' || title[0] == 'B') {
                                              if (title[6] == '0') this.$el.addClass('color-zero');
                                              if (title[6] == '1') this.$el.addClass('color-one');
                                              if (title[6] == '2') this.$el.addClass('color-two');
                                              if (title[6] == '3') this.$el.addClass('color-three');
                                              if (title[6] == '4') this.$el.addClass('color-four');
                                              if (title[6] == '5') this.$el.addClass('color-five');
                                              if (title[6] == '6') this.$el.addClass('color-six');
                                              if (title[6] == '7') this.$el.addClass('color-seven');
                                              if (title[6] == '8') this.$el.addClass('color-eight');
                                              if (title[6] == '9') this.$el.addClass('color-nine');
                                          }
  
                                          
                                      },
                                      events: {
                                          click: 'click',
                                      },
  
                                      click: function (e) {
                                          try {
                                              var previousIndex = that.model.get('index');
  
                                              if (!this.$el.hasClass("selectedItem")) {
                                                  that.model.changeSelectedItem(this.model);
                                                  this.$el.addClass("selectedItem");
                                              }
  
                                              var rowsView = that.model.get('grid').body.rows;
                                              var newIndex = _.indexOf(rowsView, this);
                                              if (previousIndex != null && previousIndex != newIndex) rowsView[previousIndex].$el.removeClass("selectedItem");
  
                                              that.model.set({
                                                  index: newIndex,
                                                  showDataEntryMode: '1',
  
                                              });
  
                                              that.UpdateURL();
                                          }
                                          catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                                      },
                                  }),
  
                                  collection: that.itemsColl,
  
  
                                  header: Backgrid.Header.extend({
                                      initialize: function (options) {
                                          Backgrid.Header.prototype.initialize.apply(this, arguments);
                                          this.listenTo(this.collection, 'backgrid:sort', function (obj) {
                                              that.model.set({
                                                  index: null,
                                                  showDataEntryMode: '',
                                              });
                                          });
                                      },
  
                                  }),
                              });
  
                              that.model.set({ grid: grid });
                              that.$el.find('.items-grid-container').append(grid.render().el);
  
                              that.$el.find('.input-date').datepicker();
  
                              that.$el.find('#timepicker1').timepicker({
                                  showMeridian: false,
                                  secondStep: 1,
                                  minuteStep: 1,
                                  showSeconds: true,
                              });
  
                              that.multiselect_pickers();
                              if (viewParams.start) {
                                  viewParams.start = new moment(viewParams.start, 'YYYYMMDD').format('MM/DD/YYYY');
                              }
                              if (viewParams.end) {
                                  viewParams.end = new moment(viewParams.end, 'YYYYMMDD').format('MM/DD/YYYY');
                              }
  
                              if (viewParams.id && !isNaN(viewParams.id)) {
                                  viewParams.itemId = viewParams.id;
                              }
                              // set view parameters as model parameters
                              that.model.set(viewParams);
                              that.getCurrentMode();
                              
                              // refresh collection
                              that.refresh(); 
                          },
                          true,
                          customPath
                      );
                  },
                  customPath
              );
          }, 
  
  
          multiselect_pickers() {
              var that = this;
              var typePicker = new VirtualSelect.init({
                  ele: '#types-picker-multi-select',
                  options: that.model.get('logEntryTypes'),
                  multiple: true,
                  search: true,
                  placeholder: 'Select Type',
                  showSelectedOptionsFirst: true,
              });
              document.querySelector('#types-picker-multi-select').addEventListener('change', function () {
                  var gradeGroupId = parseInt(this.value[0]);
                  var typesSelected = [];
                  if (this.value) {
                      _.each(this.value, function (obj) {
  
                          typesSelected.push({ value: obj });
                      });
                  }
                  that.model.set({
                      typesSelected: typesSelected
                  })
  
              });
          },
          getCurrentMode() {
              var params = this.model.toJSON();
              if (params.mode == Screen.SHIFT_NAVIGATION_MODE)
                  this.model.set('currentMode', Screen.SHIFT_NAVIGATION_MODE);
              else if (params.mode == Screen.SEARCH_MODE)
                  this.model.set('currentMode', Screen.SEARCH_MODE);
              else 
                  this.model.set('currentMode', Screen.SEARCH_MODE);
          },
  
          refresh: function () {
              try {
                  this.itemsColl.reset();
                  this.model.set({
                      index: null,
                      isLoading: true,
                      hasData: false,
                  });
                  // reload collection 
                  this.itemsColl.fetch({
                      itemId: this.model.get('itemId'),
                      start: this.model.get('start'),
                      end: this.model.get('end'),
                      crewId: this.model.get('crewId'),
                      shiftId: this.model.get('shiftId'),
                      searchText: this.model.get('searchText'),
                      logEntryTypeId: this.model.get('logEntryTypeId'),
                      equipmentCodeId: this.model.get('equipmentCodeId'),
                      author: this.model.get('author'),
                      refresh: true,
                      typesSelected: this.model.get('typesSelected'),
                  });
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
  
          , append: function (container, el) {
              el = (el != null && el != undefined) ? el : this.$el;
  
              if (this.options.state == app.view_states.loading
                  || this.options.state == app.view_states.shown) {
                  //appending view to the main container and set state to shown
  
                  this.options.state = app.view_states.shown;
                  container.append(el);
  
                  this.options.onappend(this);
              }
  
              if (this.options.state == app.view_states.hidden) {
                  //append and remain hidden
                  container.append(el);
              }
  
              if (this.options.state == app.view_states.closed) {
                  //return without appending.
                  return;
              }
          }
          , 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(event_equipment, 'new_equipmentId', this.trigger_equipment);
              this.listenTo(this.itemsColl, 'fetch', this.itemsColl_fetch),
                  _.bindAll(this, 'on_keypress'),
                  $(document).bind('keydown', this.on_keypress);
              this.listenTo(this.model, 'change:currentMode', this.setPickersParams);
              this.listenTo(this.model, 'change:itemDate change:itemTime', this.itemDatetime_change);
              this.listenTo(this.model, 'change:index', this.index_changed);
  
          }
  
          , index_changed: function () {
              rowsView = this.model.get('grid').body.rows;
              if (this.model.get('index')) {
                  row = rowsView[this.model.get('index')].model.toJSON();
                  if (row.autoGenerated == 1) document.getElementById("input-title").disabled = true;
                  else document.getElementById("input-title").disabled = false;
              } else document.getElementById("input-title").disabled = false;
              
          }
          , itemDatetime_change: function () {
              var params = this.itemsColl.model.prototype.getDefaultItem({
                  Datetime: this.model.get('itemDate') + ' ' + this.model.get('itemTime'),
              });
              this.model.set({
                  itemShift: params.itemShift,
                  itemCrew: params.itemCrew,
                  itemProductionDate: params.itemProductionDateDef,
              });
          }
  
          , setPickersParams: function () {
              var params = this.model.toJSON();
              switch (this.model.get('currentMode')) {
                  case Screen.SEARCH_MODE:
                      this.model.set({
                          showDataEntryMode: '',
                          showShiftPickers: '',
                          mode: '0',
                          shiftId: '-',
                          start: new moment(this.model.get('selectedDate'), 'MM-DD-YYYY').format('MM/DD/YYYY'),
                          end: new moment(this.model.get('selectedDate'), 'MM-DD-YYYY').format('MM/DD/YYYY'),
                      });
                      break;
                  case Screen.SHIFT_NAVIGATION_MODE:
                          var blank = this.itemsColl.model.prototype.getDefault();
                          if (params.shiftId != 'N' && params.shiftId != 'D') {
                              this.model.set({
                                  shiftId: blank.itemShift,
                                  selectedShift: blank.itemShift,
                              });
                          } else {
                              this.model.set({
                                  shiftId: params.shiftId,
                                  selectedShift: params.shiftId,
                              });
                          } 
                          this.model.set({
                              showDataEntryMode: '',
                              showShiftPickers: '1',
                              mode: '1',  
                              selectedDate: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                              start: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                              end: new moment(this.model.get('start'), 'MM/DD/YYYY').format('MM-DD-YYYY'),
                              equipmentCodeId: null,
                              crewId: '-',
                              logEntryTypeId: '-',
                              searchText: '',
                              author: '',
                          });
                      
                      break;
  
                      this.UpdateURL();
                      this.refresh();
              }   
          }
  
          , trigger_equipment: function (attrs) {
               
              var table = this.model.get('equipmentTable');
              var that = this;
              if (this.model.get('modalSelected') == Screen.MODAL_PICKER) {
                  _.map(this.model.get('equipmentTable'), function (obj) {
                      if (obj.equipmentId == attrs.equipmentCodeId) {
                          that.model.set('equipmentPickerName', obj.name);
                      }
                  })
                  that.model.set('equipmentCodeId', attrs.equipmentCodeId);
                  if (attrs.equipmentCodeId == null) {
                      that.model.set('equipmentPickerName', null);
                      app.views.topMessages.showMessage('Equipment not assigned', { stay: 5000, });
                  }
                      
              }
              if (this.model.get('modalSelected') == Screen.MODAL_DATA_ENTRY) {
                  _.map(this.model.get('equipmentTable'), function (obj) {
                      if (obj.equipmentId == attrs.equipmentCodeId) {
                          that.model.set('equipmentDataEntryName', obj.name);
                      }
                  })
  
                  this.model.set('itemEquipment', attrs.equipmentCodeId);
                  if (attrs.equipmentCodeId == null) {
                      that.model.set('equipmentDataEntryName', null);
                      app.views.topMessages.showMessage('Equipment not assigned', { stay: 5000, });
                  }
              }
          }
          
          , excelBtn_click: function (e) {
              try {
                  var qp = new Core.Database.QueryParameters(),
                      attrs = this.model.toJSON(),
                      params;
  
                  params = [
                      { Name: '@Start', Type: 'DATE', Value: attrs.start, },
                      { Name: '@End', Type: 'DATE', Value: attrs.end, },
                      { Name: '@TimeZoneCode', Type: 'CHAR(10)', Value: 'EDTIND' },
                  ];
                  _.each(params, function (qpParams) {
                      qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
                  });
  
                  var cellsData = [
                      { Column: 'A', Value: 'Date' },   
                      { Column: 'B', Value: 'Shift' },
                      { Column: 'C', Value: 'Crew' },
                      { Column: 'D', Value: 'Title' },
                      { Column: 'E', Value: 'Author' },
                      { Column: 'F', Value: 'Description' },
                      { Column: 'G', Value: 'LogEntryType' },
                      { Column: 'H', Value: 'Equipment' },
  
                  ];
  
                  var SQLCellsData = [
                      { ExcelColumnName: 'A', SQLDataColumnName: 'ProductionDate', DataType: 'String'},
                      { ExcelColumnName: 'B', SQLDataColumnName: 'ShiftID', DataType: 'String' },
                      { ExcelColumnName: 'C', SQLDataColumnName: 'CrewID', DataType: 'String' },
                      { ExcelColumnName: 'D', SQLDataColumnName: 'Title', DataType: 'String' },
                      { ExcelColumnName: 'E', SQLDataColumnName: 'Author', DataType: 'String' },
                      { ExcelColumnName: 'F', SQLDataColumnName: 'Description', DataType: 'String' },
                      { ExcelColumnName: 'G', SQLDataColumnName: 'TypeName', DataType: 'String' },
                      { ExcelColumnName: 'H', SQLDataColumnName: 'EquipmentName', DataType: 'String' },
                  ];
  
                  Core.Export.Excel({
                      Data: [
                          {
                              SheetName: 'Data',
                              RowsData: [{
                                  CellsData: cellsData
                              }],
                              StartRowIndex: 1,
                          },
                          {
                              SheetName: 'Data',
                              RowsData: [],
                              StartRowIndex: 2,
                              DataSourceName: 'data',
                              DataSourceTableIndex: 0,
                              SQLCellsData: SQLCellsData
                          }
                      ],
                      ConnectionStringName: 'APP',
                      ExportMethod: 3,
                      FileName: 'LogBook',
                      TemplateFileFullPath: 'generic.xls',
                      SQLDataSources: [
                          {
                              Name: 'data',
                              DatabaseParameters: {
                                  DBEngine: 'SQLSERVER',
                                  Procedure: app.DatabaseNames.MES + '.LogBook.GetLogBook',
                                  QueryParameters: qp,
                              },
                          },
                      ]},
                      function (resp) {
                          try {
                              if ((resp) && (resp.Success == true) && (resp.Data)) {
                                  location.href = app.foldersRoot + '/excel/' + resp.Data;
                              }
                              else {
                                  if ((resp) && (resp.Message))
                                      console.error(resp.Message);
                                  else
                                      console.error('Server response not valid.');
                              }
                          }
                          catch (Error) { console.error(Error); }
                      },
                      function (resp) {
                          console.error(resp);
                      }
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
  
  
          , itemsColl_fetch: function (coll, resp) {
              try {
                  var that = this;
                  // reload data entry
                  var selectedItemId = this.model.get('itemId');
                  if (selectedItemId) {
                      var item = this.itemsColl.select(function (model) { return model.get('id') == selectedItemId })
                      if (item && item[0]) this.model.changeSelectedItem(item[0]);
                  }
                  
                  setTimeout(
                      function () {
                          that.model.set({
                              hasData: (that.itemsColl.length > 0),
                              isLoading: false,
                          });
                      },
                      100
                  );
  
                  if (that.itemsColl.length > 0)
                      that.scrollToBottomTrigger(that.itemsColl);
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
  
          ,scrollToBottomTrigger: function (collection) {
              let listContainer = document.getElementById(collection.getGridId());
              listContainer.addEventListener('scroll', function (e) {
                  if (listContainer.scrollTop >= (listContainer.scrollHeight - listContainer.offsetHeight))
                      collection.getNextPage();
              });
          }
  
          , deleteItemBtn_click: function (model) {
              try {
                  var that = this;
                  var modal = new Modal.Views.Main({
                      focusOk: false,
                      focusSelector: '#deleteItemBtn',
                      title: app.translate([that, app], "delete_item_confirm_title"),
                      message: app.translate([that, app], "delete_item_confirm_message"),
                      buttons_type: "CONTINUE-CANCEL",
                  });
                  this.listenToOnce(modal, "continue", function (modal) {
                      this.itemsColl.deleteItem({
                          itemId: this.model.get('itemId'),
                      });
                      this.model.set(this.itemsColl.model.prototype.getDefault());
                      this.model.set('showDataEntryMode', '');
                      this.UpdateURL();
                      this.refresh();
                  });
                  modal.show();
  
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
          
          , addElectrodeBtn_click: function (model) {
              var that = this;
  
              var modal = new Screen.Views.AddElectrodeModal({
                  data: this.model,
                  parent: this
              });
              modal.show();
  
          }
          , addItemBtn_click: function (model) {
              this.model.set(this.itemsColl.model.prototype.getDefault());
              this.model.set('showDataEntryMode', '1');
          }
  
          , saveItemBtn_click: function (model) {
              this.itemsColl.upsertItem(this.model);
              this.model.set(this.itemsColl.model.prototype.getDefault());
              this.model.set('showDataEntryMode', ''); 
              this.UpdateURL();
              this.refresh();
          }
          , UpdateURL: function () {
              try {
                  var params = this.model.toJSON();
                  app.router.navigate(
                      app.router.resolveURL(
                          app.router.currentModule,
                          _.extend(
                              {},
                              params,
                              {
                                  start: new moment(params.start, "MM/DD/YYYY").format("YYYYMMDD"),
                                  end: new moment(params.end, "MM/DD/YYYY").format("YYYYMMDD"),
                              }
                          ),
                          false
                      ),
                      { trigger: false, }
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
          , refreshBtn_click: function (model) {
              this.model.set('showDataEntryMode', '');
              this.model.set('itemId', null);
              this.UpdateURL();
              this.refresh();
          }
  
          , UpdateNav(nav) {
              var params = this.model.toJSON();
              if (nav && this.model.get('selectedShift') == 'N')
                  this.model.set('selectedDate', new moment(params.selectedDate, 'MM/DD/YYYY').add(1, 'day').format('MM-DD-YYYY'));
  
              if (!nav && this.model.get('selectedShift') == 'D')
                  this.model.set('selectedDate', new moment(params.selectedDate, 'MM/DD/YYYY').subtract(1, 'day').format('MM-DD-YYYY'));
  
  
              if (this.model.get('selectedShift') == 'N') this.model.set('selectedShift', 'D');
              else
                  if (this.model.get('selectedShift') == 'D') this.model.set('selectedShift', 'N');
  
              this.model.set('showDataEntryMode', '');
              this.model.set('itemId', null);
  
              var params = this.model.toJSON();
              this.model.set('start', new moment(params.selectedDate, 'MM-DD-YYYY').format('MM/DD/YYYY'));
              this.model.set('end', new moment(params.selectedDate, 'MM-DD-YYYY').format('MM/DD/YYYY'));
              this.model.set('shiftId', this.model.get('selectedShift'));
  
              this.UpdateURL();
              this.refresh();
          },
  
          forwardNavBtn_click: function () {
              this.UpdateNav(true);
          },
          backNavBtn_click: function () {
              this.UpdateNav(false);
          },
  
          shiftViewBtn_click: function () {
              this.model.set('currentMode', Screen.SHIFT_NAVIGATION_MODE)
              this.UpdateURL();
              this.refresh();
          },
          
          searchViewBtn_click: function () {
              this.model.set('currentMode', Screen.SEARCH_MODE);
              this.refresh();
          },
  
  
          hasScrollBar: function () {
              var element = document.getElementById("grid-logBook");
              if (element) {
                  var scrollBarHeight = element.scrollHeight;
  
                  if (parseFloat(scrollBarHeight) > window.innerHeight) {
                      return true;
                  }
                  else
                      return false;
              }
              
          },
  
          insideInputOrTextarea: function () {
              var comments = document.getElementById('entry-textarea'),
                  title = document.getElementById('input-title'),
                  author = document.getElementById('input-author');
              return (document.activeElement === comments || document.activeElement === title || document.activeElement === author);
          },
  
          on_keypress: function (e) {
              var that = this,
                  rowsView = that.model.get('grid').body.rows,
                  previousIndex = that.model.get('index');
  
              if (!this.insideInputOrTextarea()) {
                  if (this.hasScrollBar()) {
                      var hel = document.getElementsByClassName("selectedItem"),
                          gridHeight = document.getElementsByClassName("items-grid-container"),
                          element = document.getElementById("grid-logBook"),
                          scrollTop = element.scrollTop,
                          constLevelSup = parseInt(window.innerHeight * 0.27),
                          constLevelInf = constLevelSup + constLevelSup,
                          diff = 0;
                      if (hel[0]) diff = hel[0].offsetTop - scrollTop + parseInt(constLevelSup);
                      if ([38, 40].indexOf(e.keyCode) > -1) {
                          if (window.event.code == 'ArrowDown') {
                              if ((parseFloat(diff) < parseFloat(gridHeight[0].offsetHeight)) && (diff - parseInt(constLevelSup) > 0)) {
                                  e.preventDefault();
                              }
                          }
                          if (window.event.code == 'ArrowUp') {
                              if ((diff - parseInt(constLevelInf)) > 0) {
                                  e.preventDefault();
                              }
                          }
                      }
                  }
  
                  if (window.event.code == 'ArrowUp' && previousIndex != 0) {
                      rowsView[previousIndex].$el.removeClass("selectedItem");
                      rowsView[previousIndex - 1].$el.addClass("selectedItem");
                      that.model.set({
                          index: previousIndex - 1,
                      });
                      that.model.changeSelectedItem(rowsView[previousIndex - 1].model);
                  }
  
                  if (window.event.code == 'ArrowDown' && (previousIndex != (rowsView.length - 1))) {
                      rowsView[previousIndex].$el.removeClass("selectedItem");
                      rowsView[previousIndex + 1].$el.addClass("selectedItem");
                      that.model.set({
                          index: previousIndex + 1,
                      });
                      that.model.changeSelectedItem(rowsView[previousIndex + 1].model);
  
                  }
                  
              }
  
          },
          bindViewScopedEvents: function () {
              var that = this;
          },
          unbindViewScopedEvents: function () {
  
          },
          close: function () {
              this.options.state = app.view_states.closed;
  
              this.remove();
              this.unbindViewScopedEvents();
              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();
          },
          preRender: function () {
              app.models.subnavbar.set('subnavbar', false);
          },
          reRender: function (viewParams) {
              try {
                  this.refresh();
              } catch (Error) { }
          },
  
  
      });
  
          
      Screen.Models.Item = Backbone.Epoxy.Model.extend({
          defaults: {
              id: null,
              author: null,
              productionDate: new moment().format('YYYY-MM-DD'),
              shift: null,
              crew: null,
              title: null,
              description: null,
              logEntryType: null,
              logEntryTypeName: null,
              equipmentCodeName: null,
              equipmentId: null,
              time: null,
          },
  
          parse: function (obj) {
              var result = {
                  id: obj.ID,
                  author: obj.Author,
                  productionDate: new moment(obj.ProductionDate),
                  shift: obj.ShiftID,
                  crew: obj.CrewID,
                  title: obj.Title,
                  desc: obj.Description ? String(obj.Description).substring(0, 100) : '',
                  description: obj.Description,
                  logEntryType: obj.LogEntryTypeID,
                  logEntryTypeName: obj.TypeName,
                  equipmentCodeName: obj.EquipmentName,
                  equipment: obj.EquipmentId,
                  time: obj.Time ? new moment(obj.Time).format('YYYY-MM-DD HH:mm:ss') : new moment(obj.ProductionDate).format('YYYY-MM-DD') + ' ' + '00:00:00',
                  autoGenerated: obj.AutoGenerated,
              };
              return result;
          }
  
          , getDefaultItem: function (params) {
              try {
                  var that = this;
                  var qp = new QueryParameters();
                  var result = {};
                  var item = [];
                  item = [
                      { name: 'Datetime', type: 'DATETIME', value: params.Datetime },
                      { name: '@TimeZoneCode', type: 'CHAR', value: app.models.user.get('timezoneCode') },
                  ];
  
                  for (var q in item) {
                      qp.Add(item[q].name, item[q].type, item[q].value);
  
                  }
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LogBook.GetDefaultLogEntry',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp && resp.Table && resp.Table[0]) {
                                      obj = resp.Table[0];
                                      result = {
                                          itemCrew: obj.CrewID,
                                          itemShift: obj.ShiftID == '1' ? 'D' : 'N',
                                          itemProductionDateDef: new moment(obj.ProductionDate).format('MM/DD/YYYY'),
                                      }
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                      }
                                      else
                                          console.error("Server response not valid.");
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: false
                      },
                      app.ConnectionStrings.app
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
              return result;
          }
          
          , getDefault: function () {
              try {
                  var that = this;
                  var qp = new QueryParameters();
                  var result = {};
                  var item = [
                      { name: '@TimeZoneCode', type: 'CHAR', value: app.models.user.get('timezoneCode') },
                  ];
  
                  for (var q in item) {
                      qp.Add(item[q].name, item[q].type, item[q].value);
  
                  }
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LogBook.GetDefaultLogEntry',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp && resp.Table && resp.Table[0]) {
                                      obj = resp.Table[0];
                                      result = {
                                          itemCrew: obj.CrewID,
                                          itemDate: new moment().format('YYYY-MM-DD'),
                                          itemShift: obj.ShiftID == '1' ? 'D' : 'N',
                                          itemTitle: '',
                                          itemAuthor: obj.CurrentUser,
                                          itemDescription: '',
                                          itemId: 'new',
                                          itemLogEntryType: obj.LogEntryTypeID,
                                          itemEquipment: null,
                                          itemTime: new moment().format('HH:mm:ss'),
                                          equipmentDataEntryName: '',
                                      }
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                      }
                                      else
                                          console.error("Server response not valid.");
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: false
                      },
                      app.ConnectionStrings.app
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
              return result;
          }
      });
  
      Screen.Collections.Items = Backbone.Collection.extend({
          model: Screen.Models.Item,
  
          isFetching: false,
          currentPage: 1,
          pageSize: 100,
  
  
          fixedParameters: [],
  
          getGridId: function () {
              return 'grid-logBook';
          },
  
          fetch: function (params) {
              var that = this,
                  qp = new Core.Database.QueryParameters(),
                  options = params ? _.clone(params) : {};
              if (options.refresh) {
                  this.resetPagination(true);
  
                
  
                  if ($.isNumeric(params.itemId)) {
                      this.fixedParameters = [
                          { Name: '@Id', Type: 'INT', Value: params.itemId, }
                      ]
                  }
                  else {
                      this.fixedParameters = [
                          { Name: '@Start', Type: 'DATETIME', Value: params.start, },
                          { Name: '@End', Type: 'DATETIME', Value: params.end, },
                          { Name: '@CrewId', Type: 'CHAR', Value: params.crewId != '-' ? params.crewId : null, },
                          { Name: '@ShiftId', Type: 'CHAR', Value: params.shiftId != '-' ? params.shiftId : null, },
                          //{ Name: '@LogEntryTypeID', Type: 'INT', Value: params.logEntryTypeId != '-' ? params.logEntryTypeId : null, },
                          { Name: '@EquipmentId', Type: 'INT', Value: params.equipmentCodeId, },
                          { Name: '@SearchText', Type: 'VARCHAR', Value: params.searchText != '' ? params.searchText : null, },
                          { Name: '@Author', Type: 'VARCHAR', Value: params.author != '' ? params.author : null, },
                          { Name: '@TimeZoneCode', Type: 'CHAR', Value: app.models.user.get('timezoneCode'), },
                      ];
  
                      //layout data xml parameter
                      qp.Add(
                          'LayoutTypes',
                          'XML',
                          app.jsonArrayToXml(
                              params.typesSelected,
                              [
                                  'value',
                              ]
                          )
                      );
                  }
              }
              this.isFetching = true;
  
              _.each(this.fixedParameters, function (qpParams) {
                  qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
              });
  
              if (!options.refresh) {
                  qp.Add('@fromRow', 'INT', (this.currentPage - 1) * this.pageSize + 1);
                  qp.Add('@rowsToFetch', 'INT', this.pageSize -1);
              } else {
                  qp.Add('@fromRow', 'INT', 0);
                  qp.Add('@toRow', 'INT', this.currentPage * this.pageSize);
                  qp.Add('@rowsToFetch', 'INT', this.pageSize);
              }
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.LogBook.GetLogBook',
                   qp,
                   {
                       onSuccess: function (resp) {
                           try {
  
                               if ((resp) && (resp.Table)) {
                                   var newColl = _.map(resp.Table, that.model.prototype.parse);
                                   var method = (options.refresh) ? 'set' : 'add';
  
                                   that[method](newColl);
                                   that.trigger('fetch', that, newColl);
  
                                   if (newColl.length == 0 && method == 'add')
                                       that.currentPage--;
  
  
                                   that.isFetching = false;
  
  
                               }
                               else {
                                   if ((resp) && (resp.Message)) {
                                       console.error(new Error(resp.Message).stack);
                                       app.views.topMessages.showMessage('CALL TO DATABASE FAILED', { stay: 5000, });
                                   }
                                   else {
                                       app.views.topMessages.showMessage('SERVER RESPONSE NOT VALID', { stay: 5000, });
                                       console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
                                   }
                               }
                           }
                           catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                       },
                       onFailure: function (resp) {
                           console.error(resp);
                       },
                       Secured: true,
                       Async: true,
                   },
                   app.ConnectionStrings.app
              );
              return this;
          },
          getNextPage: function (options) {
              if (!this.isFetching) {
                  this.currentPage++;
                  options = (_.isObject(options)) ? options : {};
                  this.fetch(options);
              }
          },
          resetPagination: function (force) {
              if (!this.isFetching || force == true) {
                  this.currentPage = 1;
              } else {
                  _.delay(this.resetPagination, 100);
              }
          },
          deleteItem: function (params) {
              try {
                  var that = this;
                  var qp = new QueryParameters();
                  qp.Add('@Id', 'INT', params.itemId);
  
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LogBook.DeleteLogEntry',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if (resp) {
                                      app.views.topMessages.showMessage('Log entry deleted', { stay: 5000, });
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                      }
                                      else
                                          console.error("Server response not valid.");
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: false,
                      },
                          app.ConnectionStrings.app
                      );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
  
          upsertItem: function (model) {
              try {
                  item = [
                      { name: '@Title', type: 'VARCHAR', value: model.get('itemTitle') },
                      { name: '@Description', type: 'VARCHAR', value: model.get('itemDescription') },
                      { name: '@LogEntryTypeId', type: 'INT', value: model.get('itemLogEntryType') },
                      { name: '@EquipmentId', type: 'INT', value: model.get('itemEquipment') },
                      { name: '@Datetime', type: 'DATETIME', value: model.get('itemDate') + ' ' + model.get('itemTime') },
                      { name: '@TimeZoneCode', type: 'CHAR(10)', value: app.models.user.get('timezoneCode') },
  
                  ];
  
  
                  if ($.isNumeric(model.get('itemId'))) {
                      item.push({ name: '@Id', type: 'INT', value: model.get('itemId') });
                  };
  
                  if (model.get('itemId') == 'new') {
                      item.push({ name: '@NewEntry', type: 'BIT', value: 1 });
                  }
  
                  var that = this;
                  var qp = new QueryParameters();
  
                  for (var q in item) {
                      qp.Add(item[q].name, item[q].type, item[q].value);
  
                  }
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LogBook.UpsertLogEntry',
                         qp,
                         {
                             onSuccess: function (resp) {
                                 try {
                                     if ((resp) && (resp.Table)) {
                                         if ((resp.Table[0]) && (resp.Table[0].ID)) {
                                             model.set('itemId', resp.Table[0].ID);
                                         } else {
                                             model.set('itemId', null);
                                         }
                                         app.views.topMessages.showMessage('Log entry saved', { stay: 5000, });
                                     }
                                     else {
                                         if ((resp) && (resp.Message)) {
                                             app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                             console.error(resp.Message);
                                         }
                                         else {
                                             app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                             console.error("Server response not valid.");
                                         }
                                     }
                                 }
                                 catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                             },
                             onFailure: function (resp) {
                                 console.error(resp);
                             },
                             Secured: true,
                             Async: false,
                         },
                         app.ConnectionStrings.app
                     );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          upsertItemBrokenElectrode: function (model) {
              try {
                  
  
                  var electrode1Checked = document.getElementById("electrode1Check").checked;
                  var electrode2Checked = document.getElementById("electrode2Check").checked;
                  var electrode3Checked = document.getElementById("electrode3Check").checked;
  
                  var electrode1ChangedManually = electrode1Checked != model.get('initialValueElectrode1') ? true : false
                  var electrode2ChangedManually = electrode2Checked != model.get('initialValueElectrode2') ? true : false
                  var electrode3ChangedManually = electrode3Checked != model.get('initialValueElectrode3') ? true : false
                  item = [
                      { name: '@Title', type: 'VARCHAR', value: model.get('itemTitle') },
                      { name: '@Description', type: 'VARCHAR', value: model.get('itemDescription') },
                      { name: '@LogEntryTypeId', type: 'INT', value: model.get('itemLogEntryType') },
                      { name: '@EquipmentId', type: 'INT', value: model.get('itemEquipment') },
                      { name: '@Datetime', type: 'DATETIME', value: model.get('itemDate') + ' ' + model.get('itemTime') },
                      { name: '@HeatName', type: 'VARCHAR', value: model.get('heatName') },
                      { name: '@Electrode1ChangedManually', type: 'BIT', value: electrode1ChangedManually },
                      { name: '@Electrode2ChangedManually', type: 'BIT', value: electrode2ChangedManually },
                      { name: '@Electrode3ChangedManually', type: 'BIT', value: electrode3ChangedManually },
                      { name: '@Electrode1Value', type: 'BIT', value: electrode1Checked },
                      { name: '@Electrode2Value', type: 'BIT', value: electrode2Checked },
                      { name: '@Electrode3Value', type: 'BIT', value: electrode3Checked },
                      { name: '@TimeZoneCode', type: 'CHAR(10)', value: app.models.user.get('timezoneCode') },
  
                  ];
  
  
                  if ($.isNumeric(model.get('itemId'))) {
                      item.push({ name: '@Id', type: 'INT', value: model.get('itemId') });
                  };
  
  
                  var that = this;
                  var qp = new QueryParameters();
  
                  for (var q in item) {
                      qp.Add(item[q].name, item[q].type, item[q].value);
  
                  }
                  Core.Json.CallProcedure(
                      app.DatabaseNames.MES + '.LogBook.InsertBrokenElectrodeEntry',
                      qp,
                      {
                          onSuccess: function (resp) {
                              try {
                                  if ((resp) && (resp.Table)) {
                                      if ((resp.Table[0]) && (resp.Table[0].ID)) {
                                          model.set('itemId', resp.Table[0].ID);
                                      } else {
                                          model.set('itemId', null);
                                      }
                                      app.views.topMessages.showMessage('Log entry saved', { stay: 5000, });
                                  }
                                  else {
                                      if ((resp) && (resp.Message)) {
                                          app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                          console.error(resp.Message);
                                      }
                                      else {
                                          app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                          console.error("Server response not valid.");
                                      }
                                  }
                              }
                              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                          },
                          onFailure: function (resp) {
                              console.error(resp);
                          },
                          Secured: true,
                          Async: false,
                      },
                      app.ConnectionStrings.app
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
  
      });
  
      Screen.Models.EquipmentModal = Backbone.Epoxy.Model.extend({
          defaults: {
              equipmentCodeId: null,
              equipmentCodes: [],
  
              errorMsg: '',
              processing: false,
  
              curEquipmentCodeId: null,
  
          },
  
          fetchEquipmentCodes: function () {
              var that = this,
                  qp = new Core.Database.QueryParameters();
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.LogBook.GetLogBookCatalogs',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              if ((resp) && (resp.Table)) {
                                  _.each(resp.Table, function (obj) { 
                                      var tableKey = 'Table' + obj.Index;
                                      switch (obj.Name) {
                                          case 'EQUIPMENTS':
                                              newItems = [];
                                              _.each(resp[tableKey], function (obj) {
                                                  newItems.push({
                                                      id:obj.Id,
                                                      parentId:obj.ParentId,
                                                      typeName:obj.TypeName,
                                                      equipmentName: obj.EquipmentName,
                                                      equipmentId: obj.EquipmentId,
                                                  })
                                              });
                                              that.set('equipmentCodes', newItems);
                                          break;
                                          
                                      }
                                  })
                              }     
                              else {
                                  if ((resp) && (resp.Message))
                                      console.error(resp.Message);
                                  else
                                      console.error("Server response not valid.");
                              }
                          }
                          catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                      },
                      onFailure: function (resp) {
                          console.error(resp);
                      },
                      Secured: true,
                      Async: false,
                  },
                  app.ConnectionStrings.app
              );
  
              return this;
          },
          reset: function () {
              this.set(this.defaults);
          },
      });
  
      var event_equipment = _({}).extend(Backbone.Events);
  
  
      Screen.Views.EquipmentModal = Backbone.Epoxy.View.extend({
          template: 'log-book',
          id: 'log-book',
          className: "modal modal-delays 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.
          bindings: "data-bind",
          isCacheable: false,
          events: function () {
              return {
                  "click #acceptBtn": this.acceptBtn_click,
                  "click #cancelBtn": this.cancelBtn_click,
                  "submit form": this.form_submit,
                  "keypress": this.modal_keypress,
                  "show.bs.modal": this.modal_show,
                  "shown.bs.modal": this.modal_shown,
                  "hidden.bs.modal": this.modal_hidden,
              };
          },
  
          container: null,
          content: null,
          disposed: false,
          isRendered: false,
          parent: null,
          preventDispose: false,
          visible: false,
  
          equipmentCodesTree: null,
          equipmentCodesTreeItemsColl: null,
          
  
          initialize: function (options) {
              _.extend(this, options);
              if (!this.model)
                  this.model = new Screen.Models.EquipmentModal();
  
              var parentModel = options.parent.model.toJSON();
              
              this.model.set('curEquipmentCodeId',parentModel.itemEquipment);
              this.bindEvents();
              return this;
          },
  
          hide: function (preventDispose) {
              this.preventDispose = (preventDispose);
  
              this.$el.modal('hide');
          },
  
          render: function (container) {
              if (container)
                  this.container = container;
  
              var that = this;
              var customPath = '/app/custom-screens/log-book/';
  
              T.render.call(
                  this,
                  this.template,
                  function (tmp) {
                      //getInternationalizationData
                      if (!that.i18n) that.i18n = {};
                      app.getI18NJed(
                          that,
                          that.template,
                          function (i18nJED) {
                              //storing internationalization data
                              that.i18n[that.template] = i18nJED;
                              //loading the view and appeding it to the views's $el.
                              that.$el.html(tmp(that.model.toJSON()));
                              that.applyBindings();
                             
                              $.jstree.defaults.core.themes.variant = 'large';
                              that.$el.find('.equipment-codes-tree').jstree({
                                  core: {
                                      check_callback: true,
                                      data: function (obj, cb) {
                                          var modelAttrs = that.model.toJSON();
                                          var data = modelAttrs.equipmentCodes;
                                          var curEquipmentCodeId = that.model.get('curEquipmentCodeId');
  
                                          var items = [{
                                              id: -100,
                                              equipmentId: null,
                                              parent: '#',
                                              type: 'root',
                                              text: app.translate(that, 'codes_tree_text'),
                                              state: {
                                                  disabled: false,
                                                  opened: true,
                                              },
                                          }];
  
                                          _.each(data, function (itemData) {
                                              items.push({
                                                  id: itemData.id,
                                                  equipmentId: itemData.equipmentId,
                                                  parent: (itemData.parentId != null) ? itemData.parentId : -100,
                                                  state: {
                                                      disabled: (modelAttrs.processing),
                                                      selected: curEquipmentCodeId ? (itemData.equipmentId == curEquipmentCodeId) : false,
                                                  },
                                                  type: 'code',
                                                  text: (itemData.equipmentName != null) ? (itemData.typeName + ' - ' + itemData.equipmentName) : itemData.typeName,
                                              });
                                          });
  
                                         
  
                                          cb.call(this, items);
                                      },
                                  },
                                  types: {
                                      '#': {
                                          valid_children: ['root'],
                                          max_children: 1,
                                      },
                                      'root': {
                                          icon: 'fa fa-ellipsis-h',
                                          valid_children: ['code'],
                                      },
                                      'code': {
                                          'icon': 'fa fa-circle-thin',
                                          valid_children: ['code'],
                                          max_depth: 1,
                                      },
                                  },
                                  plugins: [
                                      'wholerow',
                                      'types',
                                  ],
                              });
                              that.equipmentCodesTree = that.$el.find('.equipment-codes-tree').jstree(true);
  
                              that.$el.find('.equipment-codes-tree').bind({
                                  'select_node.jstree': _.bind(that.equipmentCodesTree_selectNode, that),
                              });
                              
                              that.isRendered = true;
  
                              that.trigger("render");
                          },
                          true,
                          customPath
                      );
  
  
                  }, customPath, "equipment_declare_modal");
          },
          reset: function () {
              this.model.reset();
          },
          setData: function (attrs) {
              this.model.set(attrs);
          },
          setEquipmentCodes: function () {
              this.model.fetchEquipmentCodes();
          },
          save: function () {
              var that = this,
                  attrs = this.model.toJSON();
  
              //this.model.set({
              //    errorMsg: "",
              //    processing: true,
              //});
             
          },
          show: function () {
              if (!this.isRendered) {
                  this.render();
              }
              else {
                  if (this.model.get('manual') == false) {
                      this.$el.modal({
                          keyboard: false,
                          backdrop: 'static',
                      });
                  }
                  else {
                      this.$el.modal({
                          keyboard: true,
                          backdrop: 'both',
                      });
                  }
              }
  
              return this;
          },
  
          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.listenToOnce(this, "render", this.view_render)
                  .listenTo(this.model, "change:equipmentCodeId", this.model_change_equipmentCodeId)
                  .listenTo(this.model, "change:equipmentCodes", this.model_change_equipmentCodes);
          },
          close: function () {
  
              if (this.disposed == false) {
                  if (this.visible == true) {
                      this.hide();
                  }
                  else {
                      this.trigger('close');
  
                      //Do not close the modal like we do with others to prevent a rerender every time that is displayed.
                      this.remove();
                      this.unbind();
  
                      this.disposed = true;
                  }
              }
          },
          preRender: function () {
              app.models.subnavbar.set("dateControl", false);
          },
          reRender: function () {
          },
  
          acceptBtn_click: function (e) {
              try {
                  var attrs = this.model.toJSON();
                  event_equipment.trigger('new_equipmentId', attrs);
                  this.close();
  
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          equipmentCodesTree_selectNode: function (e, obj) {
              try {
                  //this.model.set('equipmentCodeId', obj.node.id);
                  this.model.set('equipmentCodeId', obj.node.original.equipmentId);
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          form_submit: function (e) {
              try {
                  e.preventDefault();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_keypress: function (e) {
              try {
                  var attrs = this.model.toJSON();
  
                  if (((e.which == 13) && (e.shiftKey == false))
                      && (attrs.processing == false)) {
                      this.save();
                      e.preventDefault();
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_hidden: function (e) {
              try {
                  this.visible = false;
  
                  if (!this.preventDispose)
                      this.close();
                  else
                      this.preventDispose = false;
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_show: function (e) {
              try {
                  this.visible = true;
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_shown: function (e) {
              try {
                  this.$el.find(".autofocus").focus();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          model_change_equipmentCodeId: function (model) {
              try {
                  if (this.isRendered == true) {
                      this.equipmentCodesTree.deselect_all();
                      this.equipmentCodesTree.select_node(this.model.get('equipmentCodeId'));
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          model_change_equipmentCodes: function (model) {
              try {
                  if (this.isRendered == true) {
                      this.equipmentCodesTree.refresh();
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          view_render: function () {
              try {
                  this.show();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
      });
  
  
  
      Screen.Models.AddElectrodeModal = Backbone.Epoxy.Model.extend({
          defaults: {
              heatName: null,
              itemDate: new moment().format('YYYY-MM-DD'),
              itemTime: new moment().format('HH:mm:ss'),
              errorMsg: '',
              itemDescription: '',
              processing: false,
              heatNames: [],
              heatName: null,
              crews: [],
              crewId: '-',
              itemShift: null,
              itemTitle: null,
              itemLogEntryType: 8,
              itemEquipment: null,
              itemId: 'new',
              initialValueElectrode1: false,
              initialValueElectrode2: false,
              initialValueElectrode3: false,
              
  
          },
          initialize: function () {
  
          },
          fetchCatalogs: function () {
              var that = this;
              var qp = new Core.Database.QueryParameters();
              qp.Add('@HeatName', 'VARCHAR(10)', that.get('heatName'));
              qp.Add('@Asset', 'CHAR(3)', 'EAF');
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              if (resp && resp.Table) {
                                  that.set({
                                      heatNames: resp.Table,
                                      heatName: resp.Table[0] && resp.Table[0].value ? resp.Table[0].value : '',
                                      processId: resp.Table[0] && resp.Table[0].processId ? resp.Table[0].processId : null,
                                  });
                                  that.trigger('catalogs-fetched');
                              }
                              else {
                                  if ((resp) && (resp.Message)) {
                                      app.views.topMessages.showMessage(resp.Message, { stay: 5000, });
                                      console.error(resp.Message);
                                      that.set({
                                          hasData_process: false,
                                          isLoading_process: false,
  
  
                                      });
                                  }
                                  else {
                                      app.views.topMessages.showMessage("Server response not valid.", { stay: 5000, });
                                      console.error("Server response not valid.");
                                      that.set({
                                          hasData_process: false,
                                          isLoading_process: false,
                                      });
                                  }
  
                              }
  
  
                          }
                          catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                      },
                      Secured: true,
                      Async: false,
                  },
                  app.ConnectionStrings.app
              );
          },
          reset: function () {
              this.set(this.defaults);
          },
      });
      Screen.Views.AddElectrodeModal = Backbone.Epoxy.View.extend({
          template: 'log-book',
          id: 'electrode-modal',
          className: "modal modal-add-electrode 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.
          bindings: "data-bind",
          isCacheable: false,
          events: function () {
              return {
                  "click #addBrkElectrodeBtn": this.acceptBtn_click,
                  "click #cancelBrkElectrodeBtn": this.cancelBtn_click,
                  "submit form": this.form_submit,
                  "keypress": this.modal_keypress,
                  "show.bs.modal": this.modal_show,
                  "shown.bs.modal": this.modal_shown,
                  "hidden.bs.modal": this.modal_hidden,
              };
          },
  
          container: null,
          content: null,
          disposed: false,
          isRendered: false,
          parent: null,
          preventDispose: false,
          visible: false,
  
          equipmentCodesTree: null,
          equipmentCodesTreeItemsColl: null,
  
  
          initialize: function (options) {
              _.extend(this, options);
              if (!this.model)
                  this.model = new Screen.Models.AddElectrodeModal();
  
              var parentModel = options.parent.model.toJSON();
              this.model.set('crews', parentModel.crews);
              this.model.set('itemCrew', parentModel.itemCrew);
              this.model.set('itemShift', parentModel.itemShift);
              //this.model.set('curEquipmentCodeId', parentModel.itemEquipment);
              this.bindEvents();
              return this;
          },
  
          hide: function (preventDispose) {
              this.preventDispose = (preventDispose);
  
              this.$el.modal('hide');
          },
  
          render: function (container) {
              if (container)
                  this.container = container;
  
              var that = this;
              var customPath = '/app/custom-screens/log-book/';
  
              T.render.call(
                  this,
                  this.template,
                  function (tmp) {
                      //getInternationalizationData
                      if (!that.i18n) that.i18n = {};
                      app.getI18NJed(
                          that,
                          that.template,
                          function (i18nJED) {
                              //storing internationalization data
                              that.i18n[that.template] = i18nJED;
                              //loading the view and appeding it to the views's $el.
                              that.$el.html(tmp(that.model.toJSON()));
                              that.applyBindings();
                              that.model.fetchCatalogs();
  
                              that.$el.find('#dateEntryElectrode').datepicker();
  
                              that.$el.find('#timepickerElectrode').timepicker({
                                  showMeridian: false,
                                  secondStep: 1,
                                  minuteStep: 1,
                                  showSeconds: true,
                              });
  
                              that.renderMultipicker();
                                  
                              that.isRendered = true;
  
                              that.trigger("render");
                          },
                          true,
                          customPath
                      );
  
  
                  }, customPath, "add_broken_electrode_modal");
          },
          renderMultipicker: function () {
              var that = this;
              var heatNamesPicker = new VirtualSelect.init({
                  ele: this.$el[0].querySelector('#heat-picker-multi-select'),
                  options: that.model.get('heatNames'),
                  multiple: false,
                  search: true,
                  placeholder: 'Select Heat',
                  hasOptionDescription: false,
                  showSelectedOptionsFirst: true,
                  hideClearButton: true,
                  onServerSearch: that.onSampleSelectServerSearch,
              });
              var heat = that.model.get('heatName');
              this.$el[0].querySelector('#heat-picker-multi-select').setOptions(that.model.get('heatNames'));
              this.$el[0].querySelector('#heat-picker-multi-select').setValue(heat);
              this.$el[0].querySelector('#heat-picker-multi-select').addEventListener('change', function () {
                  $('.vscomp-search-clear').click();
                  if (this.value === that.model.get('heatName')) {
                      return 0;
                  }
                  else {
                      var newHeatName = this.value;
                      if (newHeatName && newHeatName != '') {
                          that.model.set({
                              heatName: newHeatName
                          });
                      }
                  }
              });
  
          },
  
          onSampleSelectServerSearch: function (searchValue, virtualSelect) {
              var qp = new Core.Database.QueryParameters();
              qp.Add('@HeatName', 'VARCHAR(10)', searchValue);
              qp.Add('@SelectedHeatName', 'VARCHAR(10)', this.selectedValues[0]);
              qp.Add('@Asset', 'CHAR(3)', 'EAF');
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.MES.GetAutocompleteHeats',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              virtualSelect.setServerOptions(resp.Table);
  
                          }
                          catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                      },
                      Secured: true,
                      Async: false,
                  },
                  app.ConnectionStrings.app
              );
          },
          fetchHeatElectrodes: function () {
              var that = this;
              var qp = new Core.Database.QueryParameters();
              var heatName = that.model.get('heatName');
              qp.Add('@HeatName', 'VARCHAR(10)', heatName);
              var electrodes = {};
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.EAF.GetElectrodesByHeat',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              electrodes = {
                                  Electrode1: resp.Table[0].Electrode1Changed,
                                  Electrode2: resp.Table[0].Electrode2Changed,
                                  Electrode3: resp.Table[0].Electrode3Changed,
                              }
  
                             
  
                          }
                          catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                      },
                      Secured: true,
                      Async: false,
                  },
                  app.ConnectionStrings.app
              );
              return electrodes;
          },
          fetchShiftandCrewfromDatetime: function () {
              var that = this;
              var qp = new Core.Database.QueryParameters();
              var itemDateTime = that.model.get('itemDate')+ ' '+ that.model.get('itemTime');
              
              qp.Add('@dateTime', 'DATETIME', itemDateTime);
              var shiftCrewInfo = {};
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.SYSTEM.GetShiftDataForDateTimeProc',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              var data = resp.Table[0];
                              shiftCrewInfo = { shiftId: data.Id, crewId: data.CrewId }
  
  
                          }
                          catch (error) { console.error((error.stack) ? error.stack : new Error(error).stack); }
                      },
                      Secured: true,
                      Async: false,
                  },
                  app.ConnectionStrings.app
              );
              return shiftCrewInfo;
          },
          reset: function () {
              this.model.reset();
          },
          setData: function (attrs) {
              this.model.set(attrs);
          },
          save: function () {
              var that = this,
                  attrs = this.model.toJSON();
  
              //this.model.set({
              //    errorMsg: "",
              //    processing: true,
              //});
  
          },
          show: function () {
              if (!this.isRendered) {
                  this.render();
              }
              else {
                  if (this.model.get('manual') == false) {
                      this.$el.modal({
                          keyboard: false,
                          backdrop: 'static',
                      });
                  }
                  else {
                      this.$el.modal({
                          keyboard: true,
                          backdrop: 'both',
                      });
                  }
              }
  
              return this;
          },
  
          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.listenToOnce(this, "render", this.view_render)
                  .listenTo(this.model, "change:heatName", this.heatName_change_electrode)
                  .listenTo(this.model, "change:itemTime", this.itemTime_change_electrode);
          },
          itemTime_change_electrode: function () {
              var that = this;
              var shiftAndCrewResult = that.fetchShiftandCrewfromDatetime();
              that.model.set('itemShift', shiftAndCrewResult.shiftId == '1' ? 'D' : 'N')
              that.model.set('itemCrew', shiftAndCrewResult.crewId)
              console.log();
          },
          heatName_change_electrode: function () {
              var that = this;
              var electrodes = that.fetchHeatElectrodes();
              //set initial values to compare in insert
              that.model.set('initialValueElectrode1', electrodes.Electrode1);
              that.model.set('initialValueElectrode2', electrodes.Electrode2);
              that.model.set('initialValueElectrode3', electrodes.Electrode3);
              that.$el.find('#electrode1Check')[0].checked = electrodes.Electrode1
              that.$el.find('#electrode2Check')[0].checked = electrodes.Electrode2
              that.$el.find('#electrode3Check')[0].checked = electrodes.Electrode3
  
          },
          close: function () {
  
              if (this.disposed == false) {
                  if (this.visible == true) {
                      this.hide();
                  }
                  else {
                      this.trigger('close');
  
                      //Do not close the modal like we do with others to prevent a rerender every time that is displayed.
                      this.remove();
                      this.unbind();
  
                      this.disposed = true;
                  }
              }
          },
          preRender: function () {
              app.models.subnavbar.set("dateControl", false);
          },
          reRender: function () {
          },
  
          acceptBtn_click: function (e) {
              try {
                  this.model.set('itemTitle', this.model.get('heatName'));
                  this.parent.itemsColl.upsertItemBrokenElectrode(this.model); 
                  this.close();
                  this.parent.refresh();
  
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          form_submit: function (e) {
              try {
                  e.preventDefault();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_keypress: function (e) {
              try {
                  var attrs = this.model.toJSON();
  
                  if (((e.which == 13) && (e.shiftKey == false))
                      && (attrs.processing == false)) {
                      this.save();
                      e.preventDefault();
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_hidden: function (e) {
              try {
                  this.visible = false;
  
                  if (!this.preventDispose)
                      this.close();
                  else
                      this.preventDispose = false;
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_show: function (e) {
              try {
                  this.visible = true;
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          modal_shown: function (e) {
              try {
                  this.$el.find(".autofocus").focus();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          model_change_equipmentCodeId: function (model) {
              try {
                  if (this.isRendered == true) {
                      this.equipmentCodesTree.deselect_all();
                      this.equipmentCodesTree.select_node(this.model.get('equipmentCodeId'));
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          model_change_equipmentCodes: function (model) {
              try {
                  if (this.isRendered == true) {
                      this.equipmentCodesTree.refresh();
                  }
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          view_render: function () {
              try {
                  this.show();
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
      });
      // Required, return the module for AMD compliance.
      return Screen;
  
  });