//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/d3v4/d3.v4',
    'backgrid/grouped-columns',
    'js/jquery.clearsearch/jquery.clearsearch',
    'js/backgrid-0.3.5/extensions/valid-min-max-cell/backgrid-valid-min-max-cell',
    'backgrid/calendar-cell',
    'backgrid/moment-cell',
    'js/jquery.timepicker/jquery.timepicker',
    'backgrid/time-cell'
  
  ],
  function (app, T, Backgrid, moment, Modal, d3) {
      //replace all 'Screen' with your view's name.
      var Screen = {
          Models: {},
          Views: {},
          Collections: {},
      };
  
      Screen.Models.Main = Backbone.Epoxy.Model.extend({
          defaults: {
  
              productionDate: new moment().subtract(1, 'days').format('MM/DD/YYYY'),
  
              shiftId: 'D',
              crewId: 'C',
              shifts: [],        
              hasData: true,
              isLoading: false,
              tphValues: null,
  
              showCaster2Data: true,
              showCaster1Data: true,
              showCaster1UncutTails: true,
              showDelaysCaster1Data: true,
              showDelaysCaster2Data: true,
          },
          initialize: function () {
              this.itemsWarehouseCosts = new Screen.Collections.ItemsCollection();
              this.itemsProductsCast = new Screen.Collections.ItemsCollection();
              this.itemsShiftResume = new Screen.Collections.ItemsCollection();
              this.itemsLogBook = new Screen.Collections.ItemsCollection();
              this.itemsShiftResumeCaster1 = new Screen.Collections.ItemsCollection();
              this.itemsMeltOrdersCaster1 = new Screen.Collections.ItemsCollection();
              this.itemsShiftResumeCaster2 = new Screen.Collections.ItemsCollection();
              this.itemsMeltOrdersCaster2 = new Screen.Collections.ItemsCollection();
              this.itemsUncutTails = new Screen.Collections.ItemsCollection();
  
              this.itemsAllHeats = new Screen.Collections.ItemsAllHeats();
              this.itemsAllDelays = new Screen.Collections.ItemsAllDelays();
              this.itemsTPH = new Screen.Collections.ItemsTPH();
              this.srdCategories = new Screen.Collections.SRDCategories();
              this.itemsDelays = new Screen.Collections.ItemsDelays();
              this.topDelaysCaster1 = new Screen.Collections.ItemsDelays();
              this.topDelaysCaster2 = new Screen.Collections.ItemsDelays();
          },
  
          computeds: {
              currentShift: {
                  deps: ['shiftId', 'productionDate','crewId'],
                  get: function (shiftId, productionDate, crewId) {
                      let shift = shiftId === 'D' ? 'Day Shift' : 'Night Shift';
                      let crew = `${crewId} Crew`;
                      return `${productionDate} | ${shift} | ${crew}`           
                  },
              },           
          },
  
          fetchData: function (params) {
              var that = this,
                  qp = new Core.Database.QueryParameters();
  
              this.fixedParameters = [
                  { Name: '@ProductionDate', Type: 'DATE', Value: params.productionDate, },
                  { Name: '@ShiftId', Type: 'INT', Value: params.shiftId == '1' ? 1 : (params.shiftId == '2' ? 2 : null), },
                  { Name: '@timeZoneCode', Type: 'CHAR(10)', Value: app.models.user.get('timezoneCode') },
              ];
  
              _.each(this.fixedParameters, function (qpParams) {
                  qp.Add(qpParams.Name, qpParams.Type, qpParams.Value);
              });
  
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.CAS.GetShiftReport',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              if (resp) {
                                  if (resp.Table15 && resp.Table15[0]) {
                                      that.set({
                                          showCaster1Data: resp.Table15[0].hasCaster1Data === 1 ? true : false,
                                          showCaster2Data: resp.Table15[0].hasCaster2Data === 1 ? true : false,
                                      });
                                  }
  
                                  if (resp.Table2) that.itemsWarehouseCosts.setDataColl(resp.Table2);
                                  if (resp.Table8) that.itemsProductsCast.setDataColl(resp.Table8);
                                  if (resp.Table9) that.itemsShiftResume.setDataColl(resp.Table9);
                                  if (resp.Table10) that.itemsLogBook.setDataColl(resp.Table10);
                                  if (resp.Table11) that.itemsShiftResumeCaster1.setDataColl(resp.Table11);
                                  if (resp.Table12) that.itemsMeltOrdersCaster1.setDataColl(resp.Table12);
                                  if (resp.Table13) that.itemsShiftResumeCaster2.setDataColl(resp.Table13);
                                  if (resp.Table14) that.itemsMeltOrdersCaster2.setDataColl(resp.Table14);
                                  if (resp.Table17) that.itemsAllDelays.setDataColl(resp.Table17, params.shiftId, params.productionDate);
                                  if (resp.Table18) that.srdCategories.setDataColl(resp.Table18);
                                  if (resp.Table19) {
                                      that.set({
                                          showDelaysCaster1Data: resp.Table19.some(x => x.CasterCode == 1),
                                          showDelaysCaster2Data: resp.Table19.some(x => x.CasterCode == 2),
                                      });
                                      that.itemsDelays.setDataColl(resp.Table19);
                                      that.topDelaysCaster1.setDataColl(resp.Table19.filter(x => x.CasterCode == 1));
                                      that.topDelaysCaster2.setDataColl(resp.Table19.filter(x => x.CasterCode == 2));
                                  } 
  
                                  if (resp.Table16) {
                                      that.set({
                                          showCaster1UncutTails: resp.Table16.length > 0 ? true : false,
                                      });
                                      that.itemsUncutTails.setDataColl(resp.Table16);
                                  }
                                      
  
                                  var strands = null;
                                  var strandsCaster2 = null;
  
                                  that.set({
                                      tphValues: resp.Table4 && resp.Table4[0] ? resp.Table4[0] : {},
                                      crewId: resp.Table && resp.Table.CrewId ?  resp.Table.CrewId : '-' ,
                                  })
  
                                  if (resp.Table6) strands = resp.Table6;
                                  if (resp.Table7) strandsCaster2 = resp.Table7;
  
                                  if (resp.Table) that.itemsAllHeats.setDataColl(resp.Table, params.shiftId, params.productionDate, strands, strandsCaster2);
                                  if (resp.Table17) that.itemsAllDelays.setDataColl(resp.Table17, params.shiftId, params.productionDate);
  
                                  
                                  that.trigger('fetch',resp);
                              }
                              else {
                                  if ((resp) && (resp.Message))
                                      console.error(new Error(resp.Message).stack);
                                  else
                                      console.error(new Error('SERVER_RESPONSE_NOT_VALID').stack);
  
                                  that.set({
                                      isLoading: false,
                                      hasData: false
                                  });
                              }
                          }
                          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;
          },
  
          fetchPickers: function (params, options) {
              var that = this,
                  qp = new Core.Database.QueryParameters(),
                  opt = _.extend({ async: true, }, options);
  
              Core.Json.CallProcedure(
                  app.DatabaseNames.MES + '.EAF.GetShiftReportPickers',
                  qp,
                  {
                      onSuccess: function (resp) {
                          try {
                              if ((resp) && (resp.Table)) {
                                  _.each(resp.Table, function (obj) {
                                      var tableKey = 'Table' + obj.Index;
  
                                      switch (obj.Name) {
                                          case 'SHIFTS':
                                              that.set('shifts', _.map(resp[tableKey], function (obj) {
                                                  return {
                                                      value: obj.Shift,
                                                      label: obj.Shift,
                                                  };
                                              }));
                                              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;
          },
      });
  
      Screen.Collections.ItemsCollection = Backbone.Collection.extend({
          setDataColl: function (data) {
              var newColl,
                  that = this;
              newColl = data;
              that.set(newColl).trigger('fetch', that, data);
          },
      });
  
      //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 'casters-shift-report';
          } catch (Error) { }
      }
  
      Screen.Views.Main = Backbone.Epoxy.View.extend({
          template: 'casters-shift-report'
          , id: 'casters-shift-report'
          , title: 'Casters Shift Report'
  
          //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 #refreshBtn': this.refreshBtn_click,
                  'click #printBtn': this.printBtn_click,
                  'click #forwardNavBtn': this.forwardNavBtn_click,
                  'click #backNavBtn': this.backNavBtn_click,
              };
          }
          , bindings: 'data-bind'
  
          , viewParams: 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.bindEvents();
          }
  
          
          , referencesChart: function () {
              
              // create svg element:
              var svg = d3.select("#refs-caster1").append("svg").attr("width", 670).attr("height", 45)
              var svgCategories = d3.select("#refs-caster1-categories").append("svg").attr("width", 650).attr("height", 45)
              // Add the path using this helper function
  
              //Get Caster 1 categories and Color
              var causeCategoriesCaster1 = this.model.srdCategories.filter(x => x.get("casterCode") == 1);
              var categoriesRecHeight = 20;
              var categoriesRecWidth = 20;
              var categoriesTextFontSize = 13; 
              var categoriesYpos = 15;
  
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 10)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Speeds");
  
              svg.append('rect')
                  .attr('x', 130)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f11919');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 160)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("< 25%");
  
  
              svg.append('rect')
                  .attr('x', 220)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f79f2d');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 250)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 25% & 50%");
  
              svg.append('rect')
                  .attr('x', 380)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f7e44f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 410)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 50% & 75%");
  
  
              svg.append('rect')
                  .attr('x', 540)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#34ba4f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 570)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("> 75%");
  
  
              var xDist = 10;
  
              svgCategories.append("text")
                  .attr("y", categoriesYpos)
                  .attr("x", 0)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Delays");
  
  
              svgCategories.append('rect')
                  .attr('x', 150 - xDist)
                  .attr('y', 0)
                  .attr('width', categoriesRecWidth)
                  .attr('height', categoriesRecHeight)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster1.filter(x => x.get("description") == "Operating Planned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', categoriesYpos)
                  .attr("x", 175 - xDist)
                  .attr("font-size", categoriesTextFontSize)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Planned");
  
              svgCategories.append('rect')
                  .attr('x', 310 - xDist)
                  .attr('y', 0)
                  .attr('width', categoriesRecWidth)
                  .attr('height',categoriesRecHeight )
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster1.filter(x => x.get("description") == "Operating Unplanned")[0].get('color'));

                  svgCategories.append("text")
                  .attr('y', categoriesYpos)
                  .attr("x", 335 - xDist)
                  .attr("font-size", categoriesTextFontSize)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Unplanned");
  
             
              var svg = d3.select("#refs-caster2").append("svg").attr("width", 670).attr("height", 45)
              // Add the path using this helper function
              var svgCategories = d3.select("#refs-caster2-categories").append("svg").attr("width", 650).attr("height", 45)
  
              //Get Caster 2 categories and Color
              var causeCategoriesCaster2 = this.model.srdCategories.filter(x => x.get("casterCode") == 2);
  
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 10)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Speeds");
  
              svg.append('rect')
                  .attr('x', 130)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f11919');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 160)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("< 25%");
  
  
              svg.append('rect')
                  .attr('x', 220)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f79f2d');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 250)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 25% & 50%");
  
              svg.append('rect')
                  .attr('x', 380)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f7e44f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 410)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 50% & 75%");
  
  
              svg.append('rect')
                  .attr('x', 540)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#34ba4f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 570)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("> 75%");
  
  
              svgCategories.append("text")
                  .attr("y", categoriesYpos)
                  .attr("x", 0)
                  .attr("font-size", 14)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Delay");
  
                  svgCategories.append('rect')
                  .attr('x', 150 - xDist)
                  .attr('y', 0)
                  .attr('width', categoriesRecWidth)
                  .attr('height', categoriesRecHeight)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster2.filter(x => x.get("description") == "Operating Planned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', categoriesYpos)
                  .attr("x", 175 - xDist)
                  .attr("font-size", categoriesTextFontSize)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Planned");
  
              svgCategories.append('rect')
                  .attr('x', 310 - xDist)
                  .attr('y', 0)
                  .attr('width', categoriesRecWidth)
                  .attr('height',categoriesRecHeight )
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster2.filter(x => x.get("description") == "Operating Unplanned")[0].get('color'));

                  svgCategories.append("text")
                  .attr('y', categoriesYpos)
                  .attr("x", 335 - xDist)
                  .attr("font-size", categoriesTextFontSize)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Unplanned");
  
              
  
              // create svg element:
  
              var svg = d3.select("#refs-screen-caster1").append("svg").attr("width", 670).attr("height", 45)
              var svgCategories = d3.select("#refs-screen-caster1-categories").append("svg").attr("width", 670).attr("height", 45)
              // Add the path using this helper function
  
               //Get Caster 1 categories and Color
              var causeCategoriesCaster1 = this.model.srdCategories.filter(x => x.get("casterCode") == 1);
  
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 0)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Strand Speeds");
  
              svg.append('rect')
                  .attr('x', 130)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f11919');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 160)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("< 25%");     
  
  
              svg.append('rect')
                  .attr('x', 220)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f79f2d');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 250)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 25% & 50%");  
  
              svg.append('rect')
                  .attr('x', 380 )
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f7e44f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 410)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")        
                  .text("Btw 50% & 75%");
      
  
              svg.append('rect')
                  .attr('x', 540)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#34ba4f');  
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 570  )
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("> 75%");
  
  
  
              svgCategories.append("text")
                  .attr("y", 18)
                  .attr("x", 0)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Delay Cat.");
  
  
              svgCategories.append('rect')
                  .attr('x', 110)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster1.filter(x => x.get("description") == "Operating Planned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', 18)
                  .attr("x", 140)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Planned");
  
              svgCategories.append('rect')
                  .attr('x', 300)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster1.filter(x => x.get("description") == "Operating Unplanned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', 18)
                  .attr("x", 330)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Unplanned");
  
  
              var svg = d3.select("#refs-screen-caster2").append("svg").attr("width", 670).attr("height", 45)
              // Add the path using this helper function
              var svgCategories = d3.select("#refs-screen-caster2-categories").append("svg").attr("width", 670).attr("height", 45)
  
              //Get Caster 1 categories and Color
              var causeCategoriesCaster2 = this.model.srdCategories.filter(x => x.get("casterCode") == 2);
  
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 0)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Strand Speeds");
  
              svg.append('rect')
                  .attr('x', 130)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f11919');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 160)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("< 25%");
  
  
              svg.append('rect')
                  .attr('x', 220)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f79f2d');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 250)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 25% & 50%");
  
              svg.append('rect')
                  .attr('x', 380)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#f7e44f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 410)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Btw 50% & 75%");
  
  
              svg.append('rect')
                  .attr('x', 540)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', '#34ba4f');
              svg.append("text")
                  .attr("y", 16)
                  .attr("x", 570)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("> 75%");
  
  
              svgCategories.append("text")
                  .attr("y", 18)
                  .attr("x", 0)
                  .attr("font-size", 16)
                  .attr("font-weight", "bold")
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Delay Cat.");
  
  
  
              
  
              svgCategories.append('rect')
                  .attr('x', 110)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster2.filter(x => x.get("description") == "Operating Planned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', 18)
                  .attr("x", 140)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Planned");
  
              svgCategories.append('rect')
                  .attr('x', 300)
                  .attr('y', 0)
                  .attr('width', 25)
                  .attr('height', 25)
                  .attr('stroke', 'rgb(80, 80, 80)')
                  .attr('fill', causeCategoriesCaster2.filter(x => x.get("description") == "Operating Unplanned")[0].get('color'));
  
              svgCategories.append("text")
                  .attr('y', 18)
                  .attr("x", 330)
                  .attr("font-size", 16)
                  .attr("fill", "#505050")
                  .attr("font-family", "Helvetica Neue,Helvetica,Arial,sans-serif")
                  .text("Operating Unplanned");
  
              
  
          }
          , forwardNavBtn_click: function () {
              this.UpdateNav(true);
          }
          , backNavBtn_click: function () {
              this.UpdateNav(false);
          }
  
          , printBtn_click: function () {
              window.scrollTo(0, 0);
              window.print();
              return false;
          }
  
          , refreshBtn_click: function (model) {
              this.UpdateURL();
              this.refresh();
          }
  
  
          , bindEvents: function () {
              this.listenTo(this.model, 'fetch', this.fetched);
  
              this.listenTo(this.model, 'caster2_READY', this.caster1_chart);
              this.listenTo(this.model.itemsAllHeats, 'fetch', this.itemsAllHeats_ready);
          },
  
  
          itemsCaster1_ready: function () {
              try {
                  var that = this;
                  setTimeout(
                      function () {
                          that.model.set({
                              hasData_caster1: (that.model.itemsCaster1.length > 0),
                              //isLoading_caster1: false,
                          });
                      },
                      100
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          },
          itemsCaster2_ready: function () {
              try {
                  var that = this;
                  setTimeout(
                      function () {
                          that.model.set({
                              hasData_caster2: (that.model.itemsCaster2.length > 0),
                              isLoading_caster2: false,
                          });
                      },
                      100
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }, 
  
          itemsAllHeats_ready: function () {
              try {
                  var that = this;
                  setTimeout(
                      function () {
                          that.model.set({
                              hasData_allHeats: (that.model.itemsAllHeats.length > 0),
                              isLoading_allHeats: false,
                          });
                          that.caster2_chart();
  
                          that.referencesChart();
                      },
                      100
                  );
  
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }, 
  
          caster1_chart: function () {
              var that = this;
  
              setTimeout(
                  function () {
                      that.getChart(true, 680, true);
                      that.getChart(true, 1400, false);
                      that.model.set({
                          isLoading_caster1: false,
                      });
                  },
                  100
              );
  
          }, 
          caster2_chart: function () {
              var that = this;
              setTimeout(
                  function () {
                      that.getChart(false, 680, true);
                      that.getChart(false, 1400, false);
                      that.model.trigger('caster2_READY', that);
                  },
                  100
              );
          }, 
  
  
          getChart(caster1,width,print) {
              var chartHeight = 110,
                  chartWeight = width,
  
              /*dataHeight = chartHeight / 2,*/
                  dataHeight = 68, //chartHeight / 2,
                  delayHeight = 28, //chartHeight / 8,
                  yPosDelays = 72,
                  divisions = 12,
                  pixelHour = (chartWeight) / divisions,
                  pixelMinute = pixelHour / 60,
                  separationPixels = 10,
                  axisHeight = 20,
                  startHourPixel = 0,
                  start = 0,
                  start_yPos = 0,
                  data = [],
                  size_letter = 10;
              var strandsData = [];
  
              var that = this;
              if (caster1) {
                  _.each(this.model.itemsAllHeats.getHeats_caster1(), function (obj) {
                      data.push(obj);
                  })
                  _.each(this.model.itemsAllDelays.getDelay_caster1(), function (obj) {
                      data.push(obj);
                  });
                  _.each(this.model.itemsAllHeats.getStrandSpeeds(), function (obj) {
                      strandsData.push(obj);
                  });
                  var chart_class = print ? ".caster1-gantt" : ".caster1-gantt-screen";
              } else {
                  _.each(this.model.itemsAllHeats.getHeats_caster2(), function (obj) {
                      data.push(obj);
                  })
                  _.each(this.model.itemsAllDelays.getDelay_caster2(), function (obj) {
                      data.push(obj);
                  });
                  _.each(this.model.itemsAllHeats.getCaster2StrandSpeeds(), function (obj) {
                      strandsData.push(obj);
                  });
                  var chart_class = print ? ".caster2-gantt" : ".caster2-gantt-screen";
              }
              if (data.length > 0) {
                  var chart = d3.select(chart_class)
                      .attr("width", 1650)
                      .attr("height", chartHeight + separationPixels + axisHeight)
  
                  var tph = this.model.get('tphValues');
  
                  //TPH
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 706 + "," + 20 + ")" : "translate(" + 1448 + "," + 20 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return 'TPH' })
  
                  var tphs1s5 = caster1 ? tph.S1TPH.toFixed(2) : tph.S5TPH.toFixed(2);
                  var tphs2s6 = caster1 ? tph.S2TPH.toFixed(2) : tph.S6TPH.toFixed(2);
                  var tphs3s8 = caster1 ? tph.S3TPH.toFixed(2) : tph.S8TPH.toFixed(2);
                  var tphs4s9 = caster1 ? tph.S4TPH.toFixed(2) : tph.S9TPH.toFixed(2);
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 708 + "," + 40 + ")" : "translate(" + 1448 + "," + 40 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return tphs1s5 ? tphs1s5 : '-' })
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 708 + "," + 55 + ")" : "translate(" + 1448 + "," + 55 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return tphs2s6 ? tphs2s6 : '-' })
  
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 708 + "," + 70 + ")" : "translate(" + 1448 + "," + 70 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return tphs3s8 ? tphs3s8 : '-' })
  
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 708 + "," + 85 + ")" : "translate(" + 1448 + "," + 85 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return tphs4s9 ? tphs4s9 : '-' })
  
                  ////Strands
                  //chart.append("text")
                  //    .attr("class", "strand_text")
                  //    .attr("y", function (d) { return 0; })
                  //    .attr("transform", function (d) { return "translate(" + 710 + "," + 10 + ")"; })
                  //    .text(function (d) { return 'S' })
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 683 + "," + 40 + ")" : "translate(" + 1410 + "," + 40 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return caster1 ? '|S1|' : '|S5|'; })
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 683 + "," + 55 + ")" : "translate(" + 1410 + "," + 55 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return caster1 ? '|S2|' : '|S6|'; })
  
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 683 + "," + 70 + ")" : "translate(" + 1410 + "," + 70 + ")"; })
                      .attr("font-size","10px")
                      .text(function (d) { return caster1 ? '|S3|' : '|S8|'; })
  
  
                  chart.append("text")
                      .attr("class", "strand_text")
                      .attr("y", function (d) { return 0; })
                      .attr("transform", function (d) { return print ? "translate(" + 683 + "," + 85 + ")" : "translate(" + 1410 + "," + 85 + ")"; })
                      .attr("font-size", "10px")
                      .text(function (d) { return caster1 ? '|S4|' : '|S9|'; })
  
                  // Append the horizontal lines
                  chart.append("rect")
                      .attr("class", "line")
                      .attr("width", chartWeight)
                      .attr("height", 0.5)
                      .style('opacity', 1)
                      //.attr("transform", "translate(" + 0 + "," + dataHeight / 2 + ")")
                      .attr("transform", "translate(" + 0 + "," + 55 + ")")
                      .style('fill', '#404040')
  
                  //chart.append("rect")
                  //    .attr("class", "line")
                  //    .attr("width", chartWeight)
                  //    .attr("height", 0.5)
                  //    .style('opacity', 1)
                  //    .attr("transform", "translate(" + 0 + "," + (parseFloat(dataHeight / 4) + parseFloat(dataHeight) + separationPixels) + ")")
                  //    .style('fill', '#404040')
  
                  var bar = chart.selectAll("g")
                      .data(data)
                      .enter().append("g")
  
                  //Append delays and heats
                  bar.append("rect")
                      .attr("width", function (d) { return (d.diffHours > 0) ? d.diffHours * pixelHour : 0; })
                      .attr("height", function (d) {
                          if (d.type === 'delay') return delayHeight;
                          return dataHeight;
                      })
                      .attr("transform", function (d) {
                          start = parseFloat(d.startHour);
                          start_yPos = (d.type == "heat") ? parseInt(0) : yPosDelays;
                          if (d.shift == "D") {
                              startHourPixel = start - 9;
                          }
                          else if (d.shift == "N") {
                              if (d.startHour >= 21) {
                                  startHourPixel = start - 21;
                              }
                              else if (d.startHour < 21) {
                                  startHourPixel = start + 3;
                              }
                          }
                          return "translate(" + startHourPixel * pixelHour + "," + start_yPos + ")";
                      })
                      .style('fill', function (d) {
                          if (d.type === 'heat') return '#eee';
                          else return d.color;
                      })
                      .style('opacity', 1)
                      .attr('stroke', '#404040')
                      .on('click', function (d) {
                        if (d.type === 'delay') {
                            try {
                                //Format the date as YYYYMMDD
                                var startDelay = d.start.slice(0, 10).replace(/-/g, ''); 
                                
                                var endDelay = '';
                                if (d.end && d.end !== '') {
                                    let endDate = new Date(d.end.slice(0, 10)); 
                                    endDate.setDate(endDate.getDate() + 1); // Add one day for Caster Delays Maanger screen
                                    
                                    // Format to YYYYMMDD
                                    endDelay = endDate.toISOString().slice(0, 10).replace(/-/g, ''); 
                                }
                                
                                Backbone.history.navigate('!/caster-delays-manager/'+startDelay+'/'+endDelay+'/'+d.delayId, { trigger: true });
                            }
                            catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
                        }
                        })
                        .style('cursor', function(d) {
                            // Only show pointer if this is a delay
                            return (d.type === 'delay') ? 'pointer' : 'default';
                        })
                      .on('mouseover', function () {
                          d3.select(this)
                              .transition()
                              .duration(500)
                              .attr('stroke', 'red')
                              .attr('stroke-width', 2)
                      })
                      .on('mouseout', function () {
                          d3.select(this)
                              .transition()
                              .duration(500)
                              .attr('stroke', '#404040')
                              .attr('stroke-width', 1)
                      })
                      .append("svg:title")
                      .text(function (d) {
                          if (d.type == 'delay') return "Delay: " + d.causeName + " | Start: " + d.start + " | Dur: " + d.duration
                          return "Heat: " + d.heatName + " | Start: " + d.start + " | Dur: " + d.duration
                      })
  
  
                  //------------------------------------
                  //--- NEW STRANDS DRAW
                  //------------------------------------                
                  _.each(data, function (d) {
                      var strand = caster1 ? 1 : 5;
                      var strs = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
  
                      if (strs.length > 0) {
                          var currentHeatInfo = _.where(data, { heatName: d.heatName })[0];
                          var strandsInfo = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
                          start = parseFloat(currentHeatInfo.startHour);
                          if (currentHeatInfo.shift === "D") startHourPixel = start - 9;
                          else {
                              if (currentHeatInfo.startHour >= 21) startHourPixel = start - 21;
                              else startHourPixel = start + 3;
                          }
  
  
                          _.each(strandsInfo, function (obj, i) {
                              bar.append("rect")
                                  .attr("width", function (d) { return pixelMinute; })
                                  .attr("height", function (d) { return (11.25); })
                                  .attr("transform", function (d) {
                                      y = obj.Strand === 1 || obj.Strand === 5 ? parseInt(30)
                                          : (obj.Strand === 2 || obj.Strand === 6 ? parseInt(45)
                                              : (obj.Strand === 3 || obj.Strand === 8 ? parseInt(60) : parseInt(75)));
                                      var s = pixelMinute * i + startHourPixel * pixelHour;
                                      return "translate(" + s + "," + y + ")";
                                  })
                                  .style('fill', function (d) { return obj.Color })
                                  .style('opacity', 1)
                                  .attr('stroke', obj.Color)
                          });
                      }
  
                      strand = caster1 ? 2 : 6;
                      strs = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
  
                      if (strs.length > 0) {
                          var currentHeatInfo = _.where(data, { heatName: d.heatName })[0];
                          var strandsInfo = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
                          start = parseFloat(currentHeatInfo.startHour);
  
                          if (currentHeatInfo.shift === "D") startHourPixel = start - 9;
                          else {
                              if (currentHeatInfo.startHour >= 21) startHourPixel = start - 21;
                              else startHourPixel = start + 3;
                          }
  
  
                          _.each(strandsInfo, function (obj, i) {
                              bar.append("rect")
                                  .attr("width", function (d) { return pixelMinute; })
                                  .attr("height", function (d) { return (11.25); })
                                  .attr("transform", function (d) {
                                      y = obj.Strand === 1 || obj.Strand === 5 ? parseInt(30)
                                          : (obj.Strand === 2 || obj.Strand === 6 ? parseInt(45)
                                              : (obj.Strand === 3 || obj.Strand === 8 ? parseInt(60) : parseInt(75)));
                                      var s = pixelMinute * i + startHourPixel * pixelHour;
                                      return "translate(" + s + "," + y + ")";
                                  })
                                  .style('fill', function (d) { return obj.Color })
                                  .style('opacity', 1)
                                  .attr('stroke', obj.Color)
                          });
                      }
  
  
  
                      strand = caster1 ? 3 : 8;
                      strs = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
  
                      if (strs.length > 0) {
                          var currentHeatInfo = _.where(data, { heatName: d.heatName })[0];
                          var strandsInfo = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
                          start = parseFloat(currentHeatInfo.startHour);
  
                          if (currentHeatInfo.shift === "D") startHourPixel = start - 9;
                          else {
                              if (currentHeatInfo.startHour >= 21) startHourPixel = start - 21;
                              else startHourPixel = start + 3;
                          }
  
  
                          _.each(strandsInfo, function (obj, i) {
                              bar.append("rect")
                                  .attr("width", function (d) { return pixelMinute; })
                                  .attr("height", function (d) { return (11.25); })
                                  .attr("transform", function (d) {
                                      y = obj.Strand === 1 || obj.Strand === 5 ? parseInt(30)
                                          : (obj.Strand === 2 || obj.Strand === 6 ? parseInt(45)
                                              : (obj.Strand === 3 || obj.Strand === 8 ? parseInt(60) : parseInt(75)));
                                      var s = pixelMinute * i + startHourPixel * pixelHour;
                                      return "translate(" + s + "," + y + ")";
                                  })
                                  .style('fill', function (d) { return obj.Color })
                                  .style('opacity', 1)
                                  .attr('stroke', obj.Color)
                          });
                      }
  
                      strand = caster1 ? 4 : 9;
                      strs = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
  
                      if (strs.length > 0) {
                          var currentHeatInfo = _.where(data, { heatName: d.heatName })[0];
                          var strandsInfo = _.where(strandsData, { HeatName: d.heatName, Strand: strand });
                          start = parseFloat(currentHeatInfo.startHour);
  
                          if (currentHeatInfo.shift === "D") startHourPixel = start - 9;
                          else {
                              if (currentHeatInfo.startHour >= 21) startHourPixel = start - 21;
                              else startHourPixel = start + 3;
                          }
  
  
                          _.each(strandsInfo, function (obj, i) {
                              bar.append("rect")
                                  .attr("width", function (d) { return pixelMinute; })
                                  .attr("height", function (d) { return (11.25); })
                                  .attr("transform", function (d) {
                                      y = obj.Strand === 1 || obj.Strand === 5 ? parseInt(30)
                                          : (obj.Strand === 2 || obj.Strand === 6 ? parseInt(45)
                                              : (obj.Strand === 3 || obj.Strand === 8 ? parseInt(60) : parseInt(75)));
                                      var s = pixelMinute * i + startHourPixel * pixelHour;
                                      return "translate(" + s + "," + y + ")";
                                  })
                                  .style('fill', function (d) { return obj.Color })
                                  .style('opacity', 1)
                                  .attr('stroke', obj.Color)
                          });
                      }
                  });
  
  
                  //-----------------------------------
                  //-----------------------------------
  
                  ////Append top text
  
                  bar.append("text")
                      .attr("class", "top_text")
                      .attr("y", function (d) {
                          var currentY = (d.type == "heat") ? (parseInt(0) + 2 * size_letter) : (dataHeight + separationPixels + 2 * size_letter);
                          return currentY - 8;
  
                      })
                      .text(function (d) {
                          if (d.type === 'heat') {
                              return d.name;
                          } else {
                              return '';
                          }
                      })
                      .attr('font-size', '10px')
                      .attr("id", function (d, i) { return "int_text" + "_" + i });
  
                  // Center the top text in the rectangle
                  chart.selectAll("g")
                      .select(".top_text")
                      .attr("x", function (d, i) {
                         // var text_element = document.getElementById("int_text" + "_" + i);
                          /* var text_element_width = text_element.getBoundingClientRect().width;*/
                          var text_element_width = 16.7;
  
                          start = parseFloat(d.startHour);
                          if (d.shift == "D") startHourPixel = start - 9;
                          else if (d.shift == "N") {
                              if (d.startHour >= 21) startHourPixel = start - 21;
                              else if (d.startHour < 21) startHourPixel = start + 3;
                          }
                          var rect_start = startHourPixel * pixelHour,
                              rect_width = d.diffHours * pixelHour;
                          return (rect_start + rect_width - (rect_width / 2.0) - (text_element_width / 2.0));
  
                      });
  
  
                  chart.selectAll("g")
                      .select("rect")
                      //.attr("height", function (d, i) {
                      //    return "68"
                      //})
                      .attr("y", function (d, i) {
                          return "22"
                      });
  
  
                  //----------------------------------------//
                  //-----------------Strands ---------------//
                  //----------------------------------------//
  
                  //Select the correct scale
                  var params = this.model.toJSON();
                  if (params.shiftId == 'D') {
                      var scale = d3.scalePoint()
                          .domain(["9AM", "10AM", "11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM"])
                          .range([0, chartWeight]);
                  } else if (params.shiftId == 'N') {
                      var scale = d3.scalePoint()
                          .domain(["9PM", "10PM", "11PM", "12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM", "9AM"])
                          .range([0, chartWeight]);
                  }
                  // Append x axis
                  var x_axis = d3.axisBottom()
                      .scale(scale);
  
                  chart.append("g")
                      .attr("class", "axis_label")
                      .attr("transform", "translate(" + 0 + "," + (chartHeight + separationPixels + 4) + ")")
                      .call(x_axis);
  
                  var array_id = [];
                  chart.selectAll("g")
                      .select(".tick text")
                      .attr("id", function (d, i) {
                          array_id.push(i);
                          return "text_hour" + "_" + i
                      });
  
                  chart.selectAll("g")
                      .select("#text_hour_" + array_id[1]).attr("x", 10);
  
                  chart.selectAll("g")
                      .select("#text_hour_" + array_id[13]).attr("x", -10);
              }
          },           
  
  
          fetched: function (resp) {
              var model = this.model.toJSON();
              let shiftId = model.shiftId;
              let productionDate = model.productionDate;
              let crewId = model.crewId;            
              let shift = shiftId === 'D' ? 'Day Shift' : 'Night Shift';
              let crew = `${crewId} Crew`;           
  
              //if (document.getElementById("shift-name-screen") && document.getElementById("shift-name-screen").textContent)
              //    document.getElementById("shift-name-screen").textContent = `${productionDate} | ${shift} | ${crew}`;
  
  
              this.setURLClassGrid('caster1-production');
              this.setURLClassGrid('caster2-production');
  
              document.getElementById("shift-name").textContent = `${productionDate} | ${shift} | ${crew}`;
              this.model.set({
                  isLoading: false,
                  hasData:
                      (resp && resp.Table && resp.Table.length > 0) ||
                      (resp && resp.Table1 && resp.Table1.length > 0) ||
                      (resp && resp.Table2 && resp.Table2.length > 0) ? true : false,
              });
  
          
          },
  
          
      
          setURLClassGrid: function (id) {
              var heatFound = '';
              var found;
              var gridElement = document.getElementById(id);
              var aTags = gridElement.getElementsByTagName("td");
              for (var i = 0; i < aTags.length; i++) {
                  if (aTags[i].textContent[0] && (aTags[i].textContent[0] === 'A' || aTags[i].textContent[0] === 'B' || aTags[i].textContent[0] === 'C' || aTags[i].textContent[0] === 'D') 
                      && !isNaN(aTags[i].textContent[1])
                      && !isNaN(aTags[i].textContent[2])
                      && !isNaN(aTags[i].textContent[3])
                      && !isNaN(aTags[i].textContent[4])
                      && !isNaN(aTags[i].textContent[5])
                      && !isNaN(aTags[i].textContent[6])
                      ) {
                      heatFound = aTags[i].textContent;
                      found = aTags[i];
                      aTags[i].textContent = '';
                      $(found).removeClass('string-cell');
                      $(found).addClass('uri-cell');
                      $(found).append("<a tabindex='- 1' " + "href='!/" + "caster-heat-report/" + heatFound + "'" + "target='_blank'>" + heatFound + "</a>");
                  }
              }
          }
  
  
          , render: function (container, viewParams) {
              var that = this;
  
              var thatContainer = (this.options.container) ? this.options.container : container;
              this.options.container = thatContainer;
              var flag = false;
              //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);
  
  
  
                              // Warehouse Costs
                              var grid_warehouseCosts = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Department',
                                          label: '',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'MonthIssues',
                                          label: 'Issues',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'MonthReturns',
                                          label: 'Returns',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Total',
                                          label: 'Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Warehouse Costs', children:
                                                      [
                                                          {
                                                              name: 'MTD', children: [
                                                                  { name: 'Department' }
                                                                  , { name: 'MonthIssues' }
                                                                  , { name: 'MonthReturns' }
                                                                  , { name: 'Total' }
                                                              ]
                                                          },
                                                          
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsWarehouseCosts,
                              });
                              var grid_warehouseCosts_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Department',
                                          label: '',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'MonthIssues',
                                          label: 'Issues',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'MonthReturns',
                                          label: 'Returns',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Total',
                                          label: 'Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Warehouse Costs', children:
                                                      [
                                                          {
                                                              name: 'MTD', children: [
                                                                  { name: 'Department' }
                                                                  , { name: 'MonthIssues' }
                                                                  , { name: 'MonthReturns' }
                                                                  , { name: 'Total' }
                                                              ]
                                                          },
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsWarehouseCosts,
                              });
                              that.$el.find('.items-grid-container-warehouse-costs').append(grid_warehouseCosts.render().el);
                              that.$el.find('.items-grid-container-warehouse-costs-screen').append(grid_warehouseCosts_screen.render().el);
  
                              // Products Cast
                              var grid_productsCast = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Caster1',
                                          label: 'Caster 1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Caster2',
                                          label: 'Caster 2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Products Cast', children:
                                                      [
                                                          { name: 'Caster1' }
                                                          , { name: 'Caster2' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsProductsCast,
                              });
                              var grid_productsCast_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Caster1',
                                          label: 'Caster 1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Caster2',
                                          label: 'Caster 2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Products Cast', children:
                                                      [
                                                          { name: 'Caster1' }
                                                          , { name: 'Caster2' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsProductsCast,
                              });
                              that.$el.find('.items-grid-container-products-cast').append(grid_productsCast.render().el);
                              that.$el.find('.items-grid-container-products-cast-screen').append(grid_productsCast_screen.render().el);
  
  
                              // Shift Resume
                              var grid_shiftResume = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'TotalTons',
                                          label: 'Total Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'TotalHeats',
                                          label: 'Total Heats',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelaysCaster1',
                                          label: 'Delays C1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'RobotCaster1',
                                          label: 'Robot C1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelaysCaster2',
                                          label: 'Delays C2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'RobotCaster2',
                                          label: 'Robot C2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      
                                  ],
  
                                  collection: that.model.itemsShiftResume,
                              });
                              var grid_shiftResume_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'TotalTons',
                                          label: 'Total Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'TotalHeats',
                                          label: 'Total Heats',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelaysCaster1',
                                          label: 'Delays C1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'RobotCaster1',
                                          label: 'Robot C1',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelaysCaster2',
                                          label: 'Delays C2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'RobotCaster2',
                                          label: 'Robot C2',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  collection: that.model.itemsShiftResume,
                              });
                              that.$el.find('.items-grid-container-shift-resume').append(grid_shiftResume.render().el);
                              that.$el.find('.items-grid-container-shift-resume-screen').append(grid_shiftResume_screen.render().el);
  
  
                              // Products Cast
                              var grid_logBook = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Timestamp',
                                          label: 'Timestamp',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'momment-cell align-center-cell timestamp',
                                              modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                              displayFormat: 'MM/DD/YY HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'Type',
                                          label: 'Type',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
  
                                      //{
                                      //    name: 'Area',
                                      //    label: 'Area',
                                      //    editable: false,
                                      //    cell: Backgrid.StringCell.extend({
                                      //        className: 'string-cell align-center-cell',
                                      //    }),
                                      //},
                                      {
                                          name: 'Equipment',
                                          label: 'Equipment',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Comments',
                                          label: 'Comments',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Log Book', children:
                                                      [
                                                          { name: 'Timestamp' }
                                                          , { name: 'Type' }
                                                          //, { name: 'Area' }
                                                          , { name: 'Equipment' }
                                                          , { name: 'Comments' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsLogBook,
                              });
                              var grid_logBook_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'Timestamp',
                                          label: 'Timestamp',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'momment-cell align-center-cell timestamp',
                                              modelFormat: 'YYYY-MM-DD HH:mm:ss',
                                              displayFormat: 'MM/DD/YY HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'Type',
                                          label: 'Type',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
  
                                      //{
                                      //    name: 'Area',
                                      //    label: 'Area',
                                      //    editable: false,
                                      //    cell: Backgrid.StringCell.extend({
                                      //        className: 'string-cell align-center-cell',
                                      //    }),
                                      //},
  
                                      {
                                          name: 'Equipment',
                                          label: 'Equipment',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Comments',
                                          label: 'Comments',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Log Book', children:
                                                      [
                                                          { name: 'Timestamp' }
                                                          , { name: 'Type' }
                                                          //, { name: 'Area' }
                                                          , { name: 'Equipment' }
                                                          , { name: 'Comments' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsLogBook,
                              });
                              that.$el.find('.items-grid-container-log-book').append(grid_logBook.render().el);
                              that.$el.find('.items-grid-container-log-book-screen').append(grid_logBook_screen.render().el);
  
                              // Shift Resume Caster 1
                              var grid_shiftResumeCaster1 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'PrimeTons',
                                          label: 'Prime Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'ScrapTons',
                                          label: 'Scrap Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelayTotal',
                                          label: 'Delays Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Caster 1', children:
                                                      [
                                                          { name: 'PrimeTons' }
                                                          , { name: 'ScrapTons' }
                                                          , { name: 'DelayTotal' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsShiftResumeCaster1,
                              });
                              var grid_shiftResumeCaster1_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'PrimeTons',
                                          label: 'Prime Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'ScrapTons',
                                          label: 'Scrap Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelayTotal',
                                          label: 'Delays Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Caster 1', children:
                                                      [
                                                          { name: 'PrimeTons' }
                                                          , { name: 'ScrapTons' }
                                                          , { name: 'DelayTotal' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsShiftResumeCaster1,
                              });
  
                              that.$el.find('.items-grid-container-shift-resume-caster-1').append(grid_shiftResumeCaster1.render().el);
                              that.$el.find('.items-grid-container-shift-resume-caster-1-screen').append(grid_shiftResumeCaster1_screen.render().el);
  
  
                                  var grid_uncutTailsCaster1 = new Backgrid.Grid({
                                      className: 'backgrid table table-hover table-condensed',
                                      columns: [
                                          {
                                              name: 'ProductNumber',
                                              label: 'Product Number',
                                              editable: false,
                                              cell: Backgrid.StringCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                          {
                                              name: 'CutComplete',
                                              label: 'Cut Time',
                                              editable: false,
                                              cell: Backgrid.StringCell.extend({
                                                  className: 'string-cell align-center-cell',
                                                  render: function () {
                                                      var cutDate = new moment(this.model.get('CutComplete')).format('HH:mm');
                                                      this.$el.append(cutDate);
                                                      return this;
                                                  },
                                              }),
                                          },
                                          {
                                              name: 'Weight',
                                              label: 'Weight',
                                              editable: false,
                                              cell: Backgrid.NumberCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                          {
                                              name: 'Length',
                                              label: 'Length',
                                              editable: false,
                                              cell: Backgrid.NumberCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                      ],
  
                                      header: Backgrid.Extension.GroupedHeader.extend({
                                          columnLayout:
                                              [
                                                  {
                                                      name: 'Uncut Products', children:
                                                          [
                                                              { name: 'ProductNumber' }
                                                              , { name: 'CutComplete' }
                                                              , { name: 'Weight' }
                                                              , { name: 'Length' }
                                                          ]
  
                                                  },
                                              ],
                                          initialize: function (options) {
                                              Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                          },
                                          render: function () {
                                              var that = this;
                                              Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                              return this;
                                          },
                                      }),
                                      collection: that.model.itemsUncutTails,
                                  });
  
                                  var grid_uncutTailsCaster1_screen = new Backgrid.Grid({
                                      className: 'backgrid table table-hover table-condensed',
                                      columns: [
                                          {
                                              name: 'ProductNumber',
                                              label: 'Product Number',
                                              editable: false,
                                              cell: Backgrid.StringCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                          {
                                              name: 'CutComplete',
                                              label: 'Cut Time',
                                              editable: false,
                                              cell: Backgrid.StringCell.extend({
                                                  className: 'string-cell align-center-cell',
                                                  render: function () {
                                                      var cutDate = new moment(this.model.get('CutComplete')).format('HH:mm');
                                                      this.$el.append(cutDate);
                                                      return this;
                                                  },
                                              }),
                                          },
                                          {
                                              name: 'Weight',
                                              label: 'Weight',
                                              editable: false,
                                              cell: Backgrid.NumberCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                          {
                                              name: 'Length',
                                              label: 'Length',
                                              editable: false,
                                              cell: Backgrid.NumberCell.extend({
                                                  className: 'string-cell align-center-cell',
                                              }),
                                          },
                                      ],
  
                                      header: Backgrid.Extension.GroupedHeader.extend({
                                          columnLayout:
                                              [
                                                  {
                                                      name: 'Uncut Products', children:
                                                          [
                                                              { name: 'ProductNumber' }
                                                              , { name: 'CutComplete' }
                                                              , { name: 'Weight' }
                                                              , { name: 'Length' }
                                                          ]
  
                                                  },
                                              ],
                                          initialize: function (options) {
                                              Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                          },
                                          render: function () {
                                              var that = this;
                                              Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                              return this;
                                          },
                                      }),
                                      collection: that.model.itemsUncutTails,
                                  });
  
                                  that.$el.find('.items-grid-container-uncut-tails-caster-1').append(grid_uncutTailsCaster1.render().el);
                                  that.$el.find('.items-grid-container-uncut-tails-caster-1-screen').append(grid_uncutTailsCaster1_screen.render().el);
  
  
                              
  
                              // Melt Orders Caster 1
                              var grid_meltOrdersCaster1 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'MeltOrder',
                                          label: 'MO',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CasterSequence',
                                          label: 'Caster Seq',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatName',
                                          label: 'Heat',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Pieces',
                                          label: 'Pieces',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'OpenTime',
                                          label: 'Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CloseTime',
                                          label: 'Close',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CastMin',
                                          label: 'Cast Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatInSequence',
                                          label: 'Heat in Sequence',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Product',
                                          label: 'Prod',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'FreeOpen',
                                          label: 'Free Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                     
                                  ],
  
                                  collection: that.model.itemsMeltOrdersCaster1,
                              });
                              var grid_meltOrdersCaster1_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'MeltOrder',
                                          label: 'MO',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CasterSequence',
                                          label: 'Caster Seq',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatName',
                                          label: 'Heat',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Pieces',
                                          label: 'Pieces',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'OpenTime',
                                          label: 'Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CloseTime',
                                          label: 'Close',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CastMin',
                                          label: 'Cast Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatInSequence',
                                          label: 'Heat in Sequence',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Product',
                                          label: 'Prod',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'FreeOpen',
                                          label: 'Free Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
  
                                  ],
  
                                  collection: that.model.itemsMeltOrdersCaster1,
                              });
                              that.$el.find('.items-grid-container-melt-order-caster-1').append(grid_meltOrdersCaster1.render().el);
                              that.$el.find('.items-grid-container-melt-order-caster-1-screen').append(grid_meltOrdersCaster1_screen.render().el);
  
                              // Shift Resume Caster 2
                              var grid_shiftResumeCaster2 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'PrimeTons',
                                          label: 'Prime Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'ScrapTons',
                                          label: 'Scrap Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelayTotal',
                                          label: 'Delays Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Caster 2', children:
                                                      [
                                                          { name: 'PrimeTons' }
                                                          , { name: 'ScrapTons' }
                                                          , { name: 'DelayTotal' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsShiftResumeCaster2,
                              });
                              var grid_shiftResumeCaster2_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'PrimeTons',
                                          label: 'Prime Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'ScrapTons',
                                          label: 'Scrap Tons',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'DelayTotal',
                                          label: 'Delays Total',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                  ],
  
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Caster 2', children:
                                                      [
                                                          { name: 'PrimeTons' }
                                                          , { name: 'ScrapTons' }
                                                          , { name: 'DelayTotal' }
  
                                                      ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                                  collection: that.model.itemsShiftResumeCaster2,
                              });
                              that.$el.find('.items-grid-container-shift-resume-caster-2').append(grid_shiftResumeCaster2.render().el);
                              that.$el.find('.items-grid-container-shift-resume-caster-2-screen').append(grid_shiftResumeCaster2_screen.render().el);
  
                              // Melt Orders Caster 1
                              var grid_meltOrdersCaster2 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'MeltOrder',
                                          label: 'MO',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CasterSequence',
                                          label: 'Caster Seq',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatName',
                                          label: 'Heat',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Pieces',
                                          label: 'Pieces',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'OpenTime',
                                          label: 'Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CloseTime',
                                          label: 'Close',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CastMin',
                                          label: 'Cast Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatInSequence',
                                          label: 'Heat in Sequence',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Product',
                                          label: 'Prod',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'FreeOpen',
                                          label: 'Free Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
  
                                  ],
  
                                  collection: that.model.itemsMeltOrdersCaster2,
                              });
                              var grid_meltOrdersCaster2_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'MeltOrder',
                                          label: 'MO',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CasterSequence',
                                          label: 'Caster Seq',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatName',
                                          label: 'Heat',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Pieces',
                                          label: 'Pieces',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'OpenTime',
                                          label: 'Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CloseTime',
                                          label: 'Close',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'CastMin',
                                          label: 'Cast Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'HeatInSequence',
                                          label: 'Heat in Sequence',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'Product',
                                          label: 'Prod',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
                                      {
                                          name: 'FreeOpen',
                                          label: 'Free Open',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell',
                                          }),
                                      },
  
                                  ],
  
                                  collection: that.model.itemsMeltOrdersCaster2,
                              });
                              that.$el.find('.items-grid-container-melt-order-caster-2').append(grid_meltOrdersCaster2.render().el);
                              that.$el.find('.items-grid-container-melt-order-caster-2-screen').append(grid_meltOrdersCaster2_screen.render().el);
  
                              var grid_delays_screen = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'CasterName',
                                          label: 'Caster',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'CauseName',
                                          label: 'Cause',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'AreaName',
                                          label: 'Area',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Duration',
                                          label: 'Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Start',
                                          label: 'Start',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'End',
                                          label: 'End',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                  ],
                                  collection: that.model.topDelaysCaster1,
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Delays', children: [
                                                      { name: 'CasterName' }
                                                      , { name: 'CauseName' }
                                                      , { name: 'AreaName' }
                                                      , { name: 'Duration' }
                                                      , { name: 'Start' }
                                                      , { name: 'End' }
                                                  ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                              });
                              that.$el.find('.items-grid-container-delays1-screen').append(grid_delays_screen.render().el);
  
                              var grid_delays = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'CasterName',
                                          label: 'Caster',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'CauseName',
                                          label: 'Cause',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'AreaName',
                                          label: 'Area',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Duration',
                                          label: 'Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Start',
                                          label: 'Start',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'End',
                                          label: 'End',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                  ],
                                  collection: that.model.topDelaysCaster1,
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Delays', children: [
                                                      { name: 'CasterName' }
                                                      , { name: 'CauseName' }
                                                      , { name: 'AreaName' }
                                                      , { name: 'Duration' }
                                                      , { name: 'Start' }
                                                      , { name: 'End' }
                                                  ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                              });
                              that.$el.find('.items-grid-container-delays1').append(grid_delays.render().el);
  
  
                              var grid_delays_screen2 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'CasterName',
                                          label: 'Caster',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'CauseName',
                                          label: 'Cause',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'AreaName',
                                          label: 'Area',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Duration',
                                          label: 'Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Start',
                                          label: 'Start',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'End',
                                          label: 'End',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                  ],
                                  collection: that.model.topDelaysCaster2,
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Delays', children: [
                                                      { name: 'CasterName' }
                                                      , { name: 'CauseName' }
                                                      , { name: 'AreaName' }
                                                      , { name: 'Duration' }
                                                      , { name: 'Start' }
                                                      , { name: 'End' }
                                                  ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                              });
                              that.$el.find('.items-grid-container-delays2-screen').append(grid_delays_screen2.render().el);
  
                              var grid_delays2 = new Backgrid.Grid({
                                  className: 'backgrid table table-hover table-condensed',
                                  columns: [
                                      {
                                          name: 'CasterName',
                                          label: 'Caster',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'CauseName',
                                          label: 'Cause',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'AreaName',
                                          label: 'Area',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Duration',
                                          label: 'Min',
                                          editable: false,
                                          cell: Backgrid.StringCell.extend({
                                              className: 'string-cell align-center-cell element',
                                          }),
                                      },
                                      {
                                          name: 'Start',
                                          label: 'Start',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                      {
                                          name: 'End',
                                          label: 'End',
                                          editable: false,
                                          cell: Backgrid.Extension.MomentCell.extend({
                                              className: 'moment-cell align-center-cell element',
                                              modelFormat: 'MM/DD/YYYY HH:mm:ss',
                                              displayFormat: 'HH:mm',
                                          }),
                                      },
                                  ],
                                  collection: that.model.topDelaysCaster2,
                                  header: Backgrid.Extension.GroupedHeader.extend({
                                      columnLayout:
                                          [
                                              {
                                                  name: 'Delays', children: [
                                                      { name: 'CasterName' }
                                                      , { name: 'CauseName' }
                                                      , { name: 'AreaName' }
                                                      , { name: 'Duration' }
                                                      , { name: 'Start' }
                                                      , { name: 'End' }
                                                  ]
  
                                              },
                                          ],
                                      initialize: function (options) {
                                          Backgrid.Extension.GroupedHeader.prototype.initialize.apply(this, arguments);
                                      },
                                      render: function () {
                                          var that = this;
                                          Backgrid.Extension.GroupedHeader.prototype.render.apply(this, arguments);
                                          return this;
                                      },
                                  }),
                              });
                              that.$el.find('.items-grid-container-delays2').append(grid_delays2.render().el);
  
  
  
                              that.$el.find('.input-date').datepicker();
                              // Load pickers synchronously
                              that.model.fetchPickers({ async: false });
  
                              var fixedParams = _.extend({}, viewParams);
  
                              if (fixedParams.productionDate)
                                  fixedParams.productionDate = new moment(fixedParams.productionDate, 'YYYYMMDD').format('MM/DD/YYYY');
                              if (fixedParams.shiftId)
                                  fixedParams.shiftId = fixedParams.shiftId;
                              if (fixedParams.crewId) {
                                  fixedParams.crewId = fixedParams.crewId;
  
                              }
                              that.model.set(fixedParams);
                              // refresh collection
                              that.refresh();
                          },
                          true,
                          customPath
                      );
                  },
                  customPath
              );
          }
  
          , refresh: function () {
              try {
                  var params = this.model.toJSON();
  
                  this.$el.find('#refs-caster2').html('');
                  this.$el.find('#refs-screen-caster2-categories').html('');
                  this.$el.find('#refs-screen-caster2').html('');
                  this.$el.find('#refs-caster1').html('');
                  this.$el.find('#refs-screen-caster1-categories').html('');
                  this.$el.find('#refs-screen-caster1').html('');
  
  
                  this.$el.find('.caster1-gantt').html('');
                  this.$el.find('.caster1-gantt-screen').html('');
                  this.$el.find('.caster2-gantt').html('');
                  this.$el.find('.caster2-gantt-screen').html('');
  
                  this.$el.find('#refs-caster1-categories').html('');
                  this.$el.find('#refs-caster2-categories').html('');
  
  
                  var shift = '1';
                  if (params.shiftId == 'D') shift = '1';
                  else if (params.shiftId == 'N') shift = '2';
  
                  this.model.set({
                      isLoading: true,
                      hasData:false,
                  })
                  // reload collections 
                  this.model.fetchData({
                      productionDate: params.productionDate,
                      shiftId: shift,
                  });
  
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
        
          , UpdateNav: function (nav) {
              var params = this.model.toJSON();
              if (nav && this.model.get('shiftId') == 'N')
                  this.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').add(1, 'day').format('MM/DD/YYYY'));
  
              if (!nav && this.model.get('shiftId') == 'D')
                  this.model.set('productionDate', new moment(params.productionDate, 'MM/DD/YYYY').subtract(1, 'day').format('MM/DD/YYYY'));
  
  
              if (this.model.get('shiftId') == 'N') this.model.set('shiftId', 'D');
              else
                  if (this.model.get('shiftId') == 'D') this.model.set('shiftId', 'N');
  
              this.UpdateURL();
              this.refresh();
          }
  
          , UpdateURL: function () {
              try {
                  var params = this.model.toJSON();
                  app.router.navigate(
                      app.router.resolveURL(
                          app.router.currentModule,
                          _.extend(
                              {},
                              params,
                              {
                                  productionDate: new moment(params.productionDate, "MM/DD/YYYY").format("YYYYMMDD"),
                              }
                          ),
                          false
                      ),
                      { trigger: false, }
                  );
              }
              catch (e) { console.error((e.stack) ? e.stack : new Error(e).stack); }
          }
       
               
          
  
          // Common functions
          , append: function (container, el) {
              el = (el != null && el != undefined) ? el : this.$el;
  
              if (this.options.state == app.view_states.loading
                  || this.options.state == app.view_states.shown) {
                  //appending view to the main container and set state to shown
  
                  this.options.state = app.view_states.shown;
                  container.append(el);
  
                  this.options.onappend(this);
              }
  
              if (this.options.state == app.view_states.hidden) {
                  //append and remain hidden
                  container.append(el);
              }
  
              if (this.options.state == app.view_states.closed) {
                  //return without appending.
                  return;
              }
          }
          , bindViewScopedEvents: function () {
              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.ItemAllHeat = Backbone.Epoxy.Model.extend({
          parse: function (obj) {
              var result = {
                  CasterNumber: obj.CasterNumber,
                  HeatName: obj.HeatName,
                  Start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                  End: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                  PowerOn: obj.PowerOn,
  
              };
              return result;
          },
      });
  
      Screen.Collections.ItemsAllHeats = Backbone.Collection.extend({
          model: Screen.Models.ItemAllHeat,
  
          caster1_heats: [],
          caster2_heats: [],
          strandSpeeds: [],
          strandSpeedsCaster2: [],
          setDataColl: function (data, shiftId, productionDate, strands, strandsCaster2) {
              var newColl,
                  that = this;
              that.setDataChart(data, shiftId, productionDate, strands, strandsCaster2);
              newColl = _.map(data, that.model.prototype.parse);
              that.set(newColl).trigger('fetch', that, data);
          },
  
          setDataChart: function (heats, shiftId, prodDate, strands, strandsCaster2) {
              var caster1_heats = [],
                  caster2_heats = [],
                  aux_heats = [];
  
              var aux_start = null,
                  aux_end = null,
                  shift = 'D',
                  aux_duration = null;
  
              var START_D = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  END_D = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  START_N = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  END_N = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').add(1, 'd').format('YYYY-MM-DD HH:mm:ss');
  
              if (shiftId == '1') shift = 'D';
              else if (shiftId == '2') shift = 'N';
  
              _.each(heats, function (obj) {
                  var start = new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss");
                  var end = new moment(obj.End).format("YYYY-MM-DD HH:mm:ss");
                  var push = false;
                  if (shift == 'D') {
                      if (moment(START_D).isBefore(end) && moment(start).isBefore(END_D)) {
                          push = true;
                          if (moment(start).isBefore(START_D)) aux_start = START_D;
                          else aux_start = start;
                          if (moment(END_D).isBefore(end)) aux_end = END_D;
                          else aux_end = end;
                      }
                  } else if (shift == 'N') {
                      if (moment(START_N).isBefore(end) && moment(start).isBefore(END_N)) {
                          push = true;
                          if (moment(start).isBefore(START_N)) aux_start = START_N;
                          else aux_start = start;
                          if (moment(END_N).isBefore(end)) aux_end = END_N;
                          else aux_end = end;
                      }
                  };
  
                  if (push) {
                      var aux_start_diff = moment(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                      var aux_end_diff = moment(new moment(aux_end, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                      var diffHours = aux_end_diff.diff(aux_start_diff, 'hours', true).toFixed(2);
                      var m = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('mm')) / 60;
                      var s = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('ss')) / 3600;
                      var aux = parseFloat(parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('HH')) + m + s).toFixed(2);
  
                      var aux_color = '#3ebf3c';
                      if (parseFloat(obj.Duration) > parseFloat(40) && parseFloat(obj.Duration) <= parseFloat(50)) aux_color = '#f3f317';
                      else if (parseFloat(obj.Duration) > parseFloat(50)) aux_color = '#ff5900';
  
                      if (obj.CasterNumber == 'Caster 1') {
                          caster1_heats.push({
                              type: 'heat',
                              name: obj.HeatName.substr(obj.HeatName.length - 3),
                              diffHours: diffHours,
                              duration: obj.Duration + ' Min',
                              color: aux_color,
                              start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                              startHour: aux,
                              end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                              shift: shift,
                              powerOn: obj.PowerOn,
                              enabledS1: obj.EnabledS1,
                              enabledS2: obj.EnabledS2,
                              enabledS3: obj.EnabledS3,
                              enabledS4: obj.EnabledS4,
                              heatName: obj.HeatName,
                          });
                      } else if (obj.CasterNumber == 'Caster 2') {
                          caster2_heats.push({
                              type: 'heat',
                              name: obj.HeatName.substr(obj.HeatName.length - 3),
                              diffHours: diffHours,
                              color: aux_color,
                              duration: obj.Duration + ' Min',
                              start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                              startHour: aux,
                              end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                              shift: shift,
                              powerOn: obj.PowerOn,
                              enabledS1: obj.EnabledS1,
                              enabledS2: obj.EnabledS2,
                              enabledS3: obj.EnabledS3,
                              enabledS4: obj.EnabledS4,
                              heatName: obj.HeatName,
                          });
                      }
                  }
  
  
              });
              this.caster1_heats = caster1_heats;
              this.caster2_heats = caster2_heats;
              this.strandSpeeds = strands;
              this.strandSpeedsCaster2 = strandsCaster2;
          },
          getHeats_caster1: function () {
              return this.caster1_heats;
          },
          getHeats_caster2: function () {
              return this.caster2_heats;
          },
          getStrandSpeeds: function () {
              return this.strandSpeeds;
          },
          getCaster2StrandSpeeds: function () {
              return this.strandSpeedsCaster2;
          }
  
  
      });
  
  
      Screen.Models.ItemAllDelay = Backbone.Epoxy.Model.extend({
          parse: function (obj) {
              var result = {
                  CasterName: obj.CasterName,
                  Code: obj.Code,
                  Start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                  End: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                  Duration: obj.Duration,
                  Color: obj.Color,
              };
              return result;
          },
      });
      Screen.Collections.ItemsAllDelays = Backbone.Collection.extend({
          model: Screen.Models.ItemAllDelay,
  
          caster1_delays: [],
          caster2_delays: [],
  
          setDataColl: function (data, shiftId, productionDate) {
              var newColl,
                  that = this;
              that.setDataChart(data, shiftId, productionDate);
              newColl = _.map(data, that.model.prototype.parse);
              that.set(newColl).trigger('fetch', that, data);
          },
  
          setDataChart: function (delays, shiftId, prodDate) {
              var caster1_delays = [],
                  caster2_delays = [],
                  aux_delay = [];
  
              var aux_start = null,
                  aux_end = null,
                  shift = 'D',
                  aux_duration = null;
  
              var START_D = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  END_D = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  START_N = new moment(prodDate + ' ' + '21:00:00', 'MM/DD/YYYY HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
                  END_N = new moment(prodDate + ' ' + '09:00:00', 'MM/DD/YYYY HH:mm:ss').add(1, 'd').format('YYYY-MM-DD HH:mm:ss');
  
              if (shiftId == '1') shift = 'D';
              else if (shiftId == '2') shift = 'N';
  
              _.each(delays, function (obj) {
                  var start = new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss");
                  var end = new moment(obj.End).format("YYYY-MM-DD HH:mm:ss");
                  var push = false;
                  if (shift == 'D') {
                      if (moment(START_D).isBefore(end) && moment(start).isBefore(END_D)) {
                          push = true;
                          if (moment(start).isBefore(START_D)) aux_start = START_D;
                          else aux_start = start;
                          if (moment(END_D).isBefore(end)) aux_end = END_D;
                          else aux_end = end;
                      }
                  } else if (shift == 'N') {
                      if (moment(START_N).isBefore(end) && moment(start).isBefore(END_N)) {
                          push = true;
                          if (moment(start).isBefore(START_N)) aux_start = START_N;
                          else aux_start = start;
                          if (moment(END_N).isBefore(end)) aux_end = END_N;
                          else aux_end = end;
                      }
                  };
  
                  if (push) {
                      var aux_start_diff = moment(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                      var aux_end_diff = moment(new moment(aux_end, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'), 'YYYY-MM-DD HH:mm:ss');
                      var diffHours = aux_end_diff.diff(aux_start_diff, 'hours', true).toFixed(2);
                      var m = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('mm')) / 60;
                      var s = parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:SS').format('ss')) / 3600;
                      var aux = parseFloat(parseInt(new moment(aux_start, 'YYYY-MM-DD HH:mm:ss').format('HH')) + m + s).toFixed(2);
                      if (obj.CasterName == 'Caster 1') {
                          caster1_delays.push({
                              type: 'delay',
                              name: obj.Duration + ' Min',
                              diffHours: diffHours,
                              duration: obj.Duration + ' Min',
                              color: obj.Color,
                              start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                              startHour: aux,
                              end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                              shift: shift,
                              causeName: obj.CauseName,
                              delayId: obj.Id
                          });
                      } else if (obj.CasterName == 'Caster 2') {
                          caster2_delays.push({
                              type: 'delay',
                              name: obj.Duration + ' Min',
                              diffHours: diffHours,
                              duration: obj.Duration + ' Min',
                              color: obj.Color,
                              start: new moment(obj.Start).format("YYYY-MM-DD HH:mm:ss"),
                              startHour: aux,
                              end: new moment(obj.End).format("YYYY-MM-DD HH:mm:ss"),
                              shift: shift,
                              causeName: obj.CauseName,
                              delayId: obj.Id
                          });
                      }
                  }
  
  
              });
              this.caster1_delays = caster1_delays;
              this.caster2_delays = caster2_delays;
  
          },
          getDelay_caster1: function () {
              return this.caster1_delays;
          },
          getDelay_caster2: function () {
              return this.caster2_delays;
          },
  
      });
  
      Screen.Collections.ItemsTPH = Backbone.Collection.extend({
          setDataColl: function (data) {
              var newColl,
                  that = this;
              newColl = data;
              that.set(newColl).trigger('fetch', that, data);
          },
  
      });
  
      Screen.Models.SRDCategory = Backbone.Epoxy.Model.extend({
          parse: function (obj) {
              var result = {
                  id: obj.DelayCategoryId,
                  description: obj.DelayCategoryName,
                  color: obj.DelayCategoryColor,
                  casterCode: obj.DelayAreaAssetId == 1000 ? 1 : 2,
              };
  
              return result;
          },
      });
      Screen.Collections.SRDCategories = Backbone.Collection.extend({
          fixedParameters: [],
          model: Screen.Models.SRDCategory,
          setDataColl: function (data) {
              var newColl,
                  that = this;
              newColl = _.map(data, that.model.prototype.parse);
              that.set(newColl).trigger('fetch', that, data);
          },
  
      });
  
      Screen.Models.ItemDelay = Backbone.Epoxy.Model.extend({
          parse: function (obj) {
              var result = {
                  RN: obj.rn,
                  CasterName: obj.CasterName,
                  AreaName: obj.AreaName,
                  Start: new moment(obj.Start).format("MM/DD/YYYY HH:mm:ss"),
                  End: new moment(obj.End).format("MM/DD/YYYY HH:mm:ss"),
                  Duration: obj.Duration,
                  CauseName: obj.CauseName,
                  CasterCode: obj.CasterCode
              };
              return result;
          },
      });
      Screen.Collections.ItemsDelays = Backbone.Collection.extend({
          model: Screen.Models.ItemDelay,
  
          setDataColl: function (data) {
              var newColl,
                  that = this;
              newColl = _.map(data, that.model.prototype.parse);
              that.set(newColl).trigger('fetch', that, data);
  
          },
      });
  
      // Required, return the module for AMD compliance.
      return Screen;
  
  });