/**
 * @license
 * Copyright 2022 Superflow.dev
 * SPDX-License-Identifier: MIT
 */

import { LitElement, html, css, PropertyValueMap } from 'lit';
import { customElement, query, queryAssignedElements, property } from 'lit/decorators.js';
// import {customElement, query, property} from 'lit/decorators.js';
import Util from './util';
import { SfIForm } from 'sf-i-form';
import { SfIUploader } from 'sf-i-uploader';
import { Chart, ChartItem, registerables } from 'chart.js';
import { exportBackgroundPlugin } from './exportBackgroundPlugin';
import { SfIElasticText } from 'sf-i-elastic-text';
import { SfIMultitextarea } from 'sf-i-multitextarea';
import { SfIReporting } from 'sf-i-reporting';
import { SfMultiselectSearch } from 'sf-multiselect-search';
import { SfISelect } from 'sf-i-select';
// import {LitElement, html, css} from 'lit';
// import {customElement} from 'lit/decorators.js';

/*

Modes: View, Add, Edit, Delete, Admin
DB: partitionKey, rangeKey, values

*/

/**
 * SfIEvents element.
 * @fires renderComplete - When the list is populated
 * @fires valueChanged - When the value is changed
 * @property apiId - backend api id
 * @property label - input label
 * @property name - name of the input
 * @property mode - mode of operation
 * @property selectedId - id to preselect
 * @property selectedValue - callback function
 */
@customElement('sf-i-events')
export class SfIEvents extends LitElement {

  SEARCH_BLOCK_SIZE = 10;
  FLOW_GRAPH_COMPLETENESS = "completeness";
  FLOW_GRAPH_TIMELINESS = "timeliness";
  FLOW_GRAPH_COMPLIANCE = "compliance";
  FLOW_GRAPH_RISKAREAS = "riskarea";
  FLOW_GRAPH_RISKSEVERITY = "risk";
  FLOW_GRAPH_LOCATION = "locationname";
  FLOW_GRAPH_FUNCTION = "functions";
  FLOW_GRAPH_OBLIGATIONTYPE = "obligationtype";
  FLOW_GRAPH_JURISDICTION = "jurisdiction";
  FLOW_GRAPH_FREQUENCY = "frequency";
  FLOW_GRAPH_SUBCATEGORY = "subcategory";
  TAB_GROUP_BUSINESS_UNDERSTANDING = "businessunderstanding";
  TAB_GROUP_GOVERNANCE_MAPPING = "governancemapping";
  TAB_GROUP_CUSTOMIZATION = "customize";
  TAB_GROUP_ROLLOUT = "rollout";
  TAB_GROUP_GOVERNANCE = "governance";
  TAB_YEAR = "year";
  TAB_FIND = "find";
  TAB_STREAM = "stream";
  TAB_UPCOMING = "upcoming";
  TAB_THIS = "this";
  TAB_PAST = "past";
  TAB_CUSTOM = "custom";
  TAB_ADHOC = "adhoc";
  TAB_REGISTERS = "registers";
  TAB_ALL_ROLES = "allroles";
  TAB_REPORTER = "reporter";
  TAB_APPROVER = "approver";
  TAB_FUNCTION_HEAD = "functionhead";
  TAB_AUDITOR = "auditor";
  TAB_VIEWER = "viewer";
  TAB_STATUTES = "statutes";
  TAB_COMPLIANCES = "compliances";
  TAB_NOTICES = "notices";
  TAB_ENTITIES = "entities";
  TAB_LOCATIONS = "locations";
  TAB_TAGS = "tags";
  TAB_REPORTERS = "reporters";
  TAB_APPROVERS = "approvers";
  TAB_FUNCTION_HEADS = "functionheads";
  TAB_MAKER_CHECKERS = "makercheckers";
  TAB_AUDITORS = "auditors";
  TAB_DOCS = "docs";
  TAB_VIEWERS = "viewers";
  TAB_DUEDATES = "duedates";
  TAB_EXTENSIONS = "extensions";
  TAB_TRIGGERS = "triggers";
  TAB_ALERTSCHEDULES = "alertschedules";
  TAB_ACTIVATIONS = "activations";
  TAB_INVALIDATION = "invalidations";
  TAB_INTERNALCONTROLS = "internalcontrols";
  TAB_REPORTEDLOCATIONS = "reportedlocations";
  TAB_SIGNOFF = "signoff";
  TAB_GOV_LOCATIONS = "govlocations";
  TAB_GOV_USERS = "govusers";
  TAB_FUNCTIONS = "functions";
  TAB_COUNTRIES = "countries";
  TAB_CALENDAR = "calendar";
  TAB_SUSPENSE = "suspense";
  TAB_RCM_COMPLIANCES = "compliances";
  TAB_RCM_PROJECTS = "projects";
  TAB_RCM_DATE = "date";
  TAB_RCM_CONFIRM = "confirm";
  TAB_RCM_JOBS = "jobs";
  TAB_ALL = "all";
  TAB_PENDING_ON_ME = "pending on me";
  TAB_PENDING_ON_REPORTER = "pending on reporter";
  TAB_PENDING_ON_APPROVER = "pending on approver";
  TAB_DONE = "done";
  COLOR_APPROVED = "#50cf01";
  COLOR_NOT_STARTED = "#A4A9AD";
  COLOR_PENDING_APPROVAL = "#ffe505"
  COLOR_REJECTED = "#C80036"
  COLOR_PAST_DUE_DATE = "#ffe505";
  COLOR_LATE_EXECUTED = "#840B0F";
  COLOR_LATE_APPROVED = "#EE2F36";
  COLOR_LATE_REPORTED = "#Ef9C66";
  COLOR_SCHEDULED = "#888888";
  COLOR_NOT_COMPLIED = "#C80036";
  COLOR_PARTIALLY_COMPLIED = "#F79256";
  COLOR_COMPLIED = "#50cf01";
  COLOR_COMPLIED_WITH_EXCEPTION = "#ffe505";
  COLOR_REPORTED_NON_COMPLIANCE = "#840B0F";
  STATUS_NOT_STARTED = "not-started";
  STATUS_PENDING_APPROVAL = "pending-approval";
  STATUS_REJECTED = "rejected";
  STATUS_APPROVED = "approved";
  CERTIFICATE_HTML = `
  
  <html>
    <head>  
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet">
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600&display=swap" rel="stylesheet">
      <style>
        body {
          font-family: Source Sans Pro;
          margin: 2px;
          padding: 20px;
          background-color: #efefef;
        }
        .certificate-section {
          background-image: url('https://flagggrc-images.s3.amazonaws.com/certificate_background.jpg');
          background-size: cover;
          background-position: center;
          box-shadow: inset 2px 2px 6px rgba(5, 5, 5, 0.2);
          border-top: solid 1px rgba(255, 255, 255, 0.8);
          border-left: solid 1px rgba(255, 255, 255, 0.8);
          border-bottom: solid 1px rgba(255, 255, 255, 0.8);
          border-right: solid 1px rgba(255, 255, 255, 0.8);
          overflow:hidden;
          padding-top: 10px;
          padding-bottom: 20px;
          padding-left: 20px;
          padding-right: 20px;
          border-radius: 10px;
          position: relative;
          z-index: 1;
        }
        .certificate-section h1 {
          font-family: Belanosima;
          font-weight: 600;
        }
        .person-designation {
          text-transform: capitalize;
        }
        .status-format {
          text-transform: uppercase;
        }
        .text-center {
          text-align: center;
        }
        .d-flex {
          display: flex;
        }
        .justify-center {
          justify-content: center;
        }
        .justify-between {
          justify-content: space-between;
        }
        .align-center {
          align-items: center;
        }
        
        .w-25 {
          width: 25%;
        }
        .w-16 {
          width: 16%;
        }
        .w-14 {
          width: 14%;
        }
        .w-12 {
          width: 12%;
        }
        .w-100 {
          width: 100%;
        }
        .text-center {
          text-align: center;
        }
        table {
          box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
          border-top: solid 1px rgba(255, 255, 255, 0.8);
          border-left: solid 1px rgba(255, 255, 255, 0.8);
          border-bottom: solid 1px rgba(255, 255, 255, 0.8);
          border-right: solid 1px rgba(255, 255, 255, 0.8);
          overflow:hidden;
        }
        th {
          background-color: #6a6a6a;
          color: white;
          padding: 5px;
        }
        .td-thin {
          min-width: 150px;
        }
        .td-wide {
          min-width: 300px;
        }
        td {
          padding: 5px;
          font-size: 70%;
          vertical-align: top;
          min-width: 200px;
        }
        td span {
          font-size: 130% !important;
        }
        .td-odd {
          background-color: #efefef;
          
        }
        .td-even {
          background-color: #dedede;
        }
        .color-pending {
          color: #ffe505;
        }
        .color-pending-approval {
          color: #ffe505;
        }
        .color-not-started {
          color: #888888;
        }
        .color-not-complied {
          color: #C80036;
        }
        .color-partially-complied {
          color: #F79256;
        }
        .color-scheduled {
          color: #888888;
        }
        .color-complied {
          color: #50cf01;
        
        }
        .color-done {
          color: #50cf01;
        }
        .color-rejected {
          color: #C80036;
        }
        .color-approved {
          color: #50cf01;
        }
        .color-past-due-date {
          color: #ffe505;
        }
        .color-late-executed {
          color: #840B0F;
        }
        .color-late-approved {
          color: #EE2F36;
        }
        .color-late-reported {
          color: #Ef9C66;
        }
        .watermark {
          background-image: url(https://flagggrc-images.s3.amazonaws.com/logo.png);
          background-position: center;
          background-repeat: repeat;
          background-size: 200px 53.58px;
          transform: translateZ(0);
          image-rendering: pixelated;
          opacity: 0.05;
          left: 0;
          right: 0;
          top: 0;
          bottom: 0;
          position: absolute;
          z-inidex: 0;
        }
      </style>
    </head>
    <body>
      <div class="certificate-section">
        <h1 class="text-center">Certificate</h1>
        <div class="watermark"></div>
        <p>I, PERSON_NAME, working as <span class="person-designation">PERSON_DESIGNATION</span> in PERSON_COMPANY, hereby declare that I am entrusted with the responsibility of ensuring compliance with various laws applicable to the company in the administration of business and the affairs of the company</p>
        <p>After having examined and considered all relevant information and based on the information furnished by the concerned officers, I, do hereby certify that the Finance / Technical / Administration / Legal wings / department of PERSON_COMPANY for the period PERSON_PERIOD, has in the conduct of business:</p>
        <ol>
          <li>Complied with all applicable laws, enactments, orders, rules, regulations, and other statutory requirements of the Central, State and other Statutory and local authorities concerning the business and affairs of the company;</li>
          <li>Paid all applicable statutory dues on due dates;</li>
          <li>Maintained proper registers, records, documents and books and filed proper returns, forms and statements and furnished necessary particulars to the relevant authorities; and</li>
          <li>Not done or committed any act or entered into any transactions in violation of any statutory provisions</li>
        </ol>
        <br /><br />
        <div class="d-flex justify-between align-center">
          <div>
            <div>Date: PERSON_DATE</div>
            <div>Criteria: PERSON_CRITERIA</div>
          </div>
          <div>
            <div>Name: PERSON_NAME</div>
            <div class="person-designation">Role: PERSON_DESIGNATION</div>
          </div>
        </div>
      </div>
      <br /><br />
      <div class="watermark"></div>
      <h3>Compliance Status</h3>
      PERSON_COMPLIANCE_STATUS
      <br /><br />
      <h3>Compliances List</h3>
      PERSON_COMPLIANCES
    </body>
  </html>
  
  `;

  COMPLIANCES_HTML = `
  
  <html>
    <head>  
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">  
      <link rel="preconnect" href="https://fonts.googleapis.com/">
      <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin="">
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@100;300;400;700;900&family=Oleo+Script&family=Oswald:wght@700&display=swap" rel="stylesheet">
      <style>
        body {
          font-family: DM Sans;
          margin: 2px;
          padding: 20px;
        }
        .status-format {
          text-transform: uppercase;
        }
        .text-center {
          text-align: center;
        }
        .d-flex {
          display: flex;
        }
        .justify-center {
          justify-content: center;
        }
        .justify-between {
          justify-content: space-between;
        }
        .align-center {
          align-items: center;
        }
        .flex-wrap {
          flex-wrap: wrap;
        }
        .mt-10 {
          margin-top: 10px;
        }
        .w-25 {
          width: 25%;
        }
        .w-16 {
          width: 16%;
        }
        .w-14 {
          width: 14%;
        }
        .w-12 {
          width: 12%;
        }
        .w-100 {
          width: 100%;
        }
        .w-200px {
          width: 200px;
        }
        .text-center {
          text-align: center;
        }
        table {
          box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
          border-top: solid 1px rgba(255, 255, 255, 0.8);
          border-left: solid 1px rgba(255, 255, 255, 0.8);
          border-bottom: solid 1px rgba(255, 255, 255, 0.8);
          border-right: solid 1px rgba(255, 255, 255, 0.8);
          overflow:auto;
        }
        th {
          background-color: #6a6a6a;
          color: white;
          padding: 5px;
        }
        .td-thin {
          min-width: 150px;
        }
        .td-wide {
          min-width: 300px;
        }
        .td-head {
          font-weight: 400;
          padding-left: 5px;
          vertical-align: middle;
          font-size: 80%;
          text-transform: capitalize;
          text-align: left;
        }
        td {
          padding: 5px;
          font-size: 70%;
          vertical-align: top;
          min-width: 200px;
        }
        td span {
          font-size: 130% !important;
        }
        .td-odd {
          background-color: #efefef;
        }
        .td-even {
          background-color: #dedede;
        }
        .color-pending {
          color: #ffe505;
        }
        .color-pending-approval {
          color: #ffe505;
        }
        .color-not-started {
          color: #888888;
        }
        .color-not-complied {
          color: #C80036;
        }
        .color-partially-complied {
          color: #F79256;
        }
        .color-complied {
          color: #50cf01;
        }
        .color-complied-with-gaps {
          color: #ffe505;
        }
        .color-reported-non-compliance {
          color: #840B0F;
        }
        .color-scheduled {
          color: #888888;
        }
        .color-done {
          color: #50cf01;
        }
        .color-rejected {
          color: #C80036;
        }
        .color-approved {
          color: #50cf01;
        }
        .color-past-due-date {
          color: #ffe505;
        }
        .color-late-executed {
          color: #840B0F;
        }
        .color-late-approved {
          color: #EE2F36;
        }
        .color-late-reported {
          color: #Ef9C66;
        }
        .h-100 {
          height: 100vh;
        }
        .abs {
          position: absolute;
        }
        .watermark {
          background-image: url(https://flagggrc-images.s3.amazonaws.com/logo.png);
          background-position: center;
          background-repeat: no-repeat;
          opacity: 5%;
          width: 100%;
          height: 100vh;
          position: fixed;
        }
        .scroll-x {
          display: block;
          overflow-x: auto;
        }
      </style>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.5/purify.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    </head>
    <body>
        <div>
          <h1>Compliance Report</h1>
          <div class="d-flex justify-between align-center">
            <div>
              <div>Report generated for PROJECT_NAME on REPORT_DATE</div>
            </div>
          </div>
          <div class="d-flex justify-between align-center">
            FILTERS_DATA
          </div>
          <br />
          <div class="watermark"></div>
          <div class="report">
            PERSON_COMPLIANCES
          </div>
        </div>
        <script>

        </script>
      </body>

  </html>
  
  `;

  MAPPING_HTML = `
  
  <html>
    <head>  
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
    rel="stylesheet">
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600&display=swap" rel="stylesheet">
      <script src="https://unpkg.com/@webcomponents/webcomponentsjs@latest/webcomponents-loader.js"></script>
      <script type="module">

          import {LitElement, html, css} from 'https://esm.run/lit-element/lit-element.js';
          import {SfISelect} from 'https://esm.run/sf-i-select/sf-i-select.js';
          import {SfISubSelect} from 'https://esm.run/sf-i-sub-select/sf-i-sub-select.js';
          import {SfIForm} from 'https://esm.run/sf-i-form/sf-i-form.js';
          import {SfIElasticText} from 'https://esm.run/sf-i-elastic-text/sf-i-elastic-text.js';
          import {SfIUploader} from 'https://esm.run/sf-i-uploader/sf-i-uploader.js';
          import {SfIMultitextarea} from 'https://esm.run/sf-i-multitextarea/sf-i-multitextarea.js';
          
          // import {LitElement, html, css} from 'https://unpkg.com/lit-element@3.3.3/lit-element.js?module';
          // import {SfNav} from 'https://unpkg.com/sf-nav@1.0.94/sf-nav.js?module';
          // import {SfChartPie} from 'https://unpkg.com/sf-chart-pie@1.0.4/sf-chart-pie.js?module';
          // import {SfChartBar} from 'https://unpkg.com/sf-chart-bar@1.0.6/sf-chart-bar.js?module';
          // import {SfUserAuth} from 'https://unpkg.com/sf-user-auth@1.0.89/sf-user-auth.js?module';
          // import {SfISelect} from 'https://unpkg.com/sf-i-select@1.0.91/sf-i-select.js?module';
          // import {SfISubSelect} from 'https://unpkg.com/sf-i-sub-select@1.0.82/sf-i-sub-select.js?module';
          // import {SfIForm} from 'https://unpkg.com/sf-i-form@1.0.125/sf-i-form.js?module';
          // import {SfIEvents} from 'https://unpkg.com/sf-i-events@1.0.469/sf-i-events.js?module';
          // import {SfIElasticText} from 'https://unpkg.com/sf-i-elastic-text@1.0.11/sf-i-elastic-text.js?module';
          // import {SfIUploader} from 'https://unpkg.com/sf-i-uploader@1.0.60/sf-i-uploader.js?module';
          // import {SfRandomText} from 'https://unpkg.com/sf-random-text@1.0.2/sf-random-text.js?module';
          // import {SfIMultitextarea} from 'https://unpkg.com/sf-i-multitextarea@1.0.16/sf-i-multitextarea.js?module';
          
      </script>
      <style>
        body {
          font-family: Source Sans Pro;
          margin: 2px;
          padding: 20px;
          background-color: #efefef;
        }
        .chosen {
          background-color: #E5FAD4 !important;
        }
        .td-head {
          text-transform: capitalize;
        }
        .status-format {
          text-transform: uppercase;
        }
        .text-center {
          text-align: center;
        }
        .d-flex {
          display: flex;
        }
        .justify-center {
          justify-content: center;
        }
        .justify-between {
          justify-content: space-between;
        }
        .align-center {
          align-items: center;
        }
        .w-25 {
          width: 25%;
        }
        .w-16 {
          width: 16%;
        }
        .w-14 {
          width: 14%;
        }
        .w-12 {
          width: 12%;
        }
        .w-100 {
          width: 100%;
        }
        .text-center {
          text-align: center;
        }
        table {
          box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
          border-top: solid 1px rgba(255, 255, 255, 0.8);
          border-left: solid 1px rgba(255, 255, 255, 0.8);
          border-bottom: solid 1px rgba(255, 255, 255, 0.8);
          border-right: solid 1px rgba(255, 255, 255, 0.8);
          overflow:hidden;
        }
        th {
          background-color: #6a6a6a;
          color: white;
          padding: 5px;
        }
        td {
          padding: 5px;
          font-size: 70%;
          vertical-align: top;
        }
        td span {
          font-size: 130% !important;
        }
        .td-odd {
          background-color: #efefef;
          
        }
        .td-even {
          background-color: #dedede;
        }
        .color-pending {
          color: #ffe505;
        }
        .color-pending-approval {
          color: #ffe505;
        }
        .color-not-started {
          color: #888888;
        }
        .color-not-complied {
          color: #C80036;
        }
        .color-partially-complied {
          color: #F79256;
        }
        .color-complied {
          color: #50cf01;
        }
        .color-complied-with-gaps {
          color: #ffe505;
        }
        .color-reported-non-compliance {
          color: #840B0F;
        }
        .color-scheduled {
          color: #888888;
        }
        .color-done {
          color: #50cf01;
        }
        .color-rejected {
          color: #C80036;
        }
        .color-approved {
          color: #50cf01;
        }
        .color-past-due-date {
          color: #ffe505;
        }
        .color-late-executed {
          color: #840B0F;
        }
        .color-late-approved {
          color: #EE2F36;
        }
        .color-late-reported {
          color: #Ef9C66;
        }
      </style>
    </head>
    <body>
      TABLE_DATA
    </body>
  </html>
  
  `;

  TAGGING_HTML = `
    
    <html>
      <head>  
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600&display=swap" rel="stylesheet">
        <script src="https://unpkg.com/@webcomponents/webcomponentsjs@latest/webcomponents-loader.js"></script>
        <script type="module">

            import {LitElement, html, css} from 'https://esm.run/lit-element/lit-element.js';
            import {SfISelect} from 'https://esm.run/sf-i-select/sf-i-select.js';
            import {SfISubSelect} from 'https://esm.run/sf-i-sub-select/sf-i-sub-select.js';
            import {SfIForm} from 'https://esm.run/sf-i-form/sf-i-form.js';
            import {SfIElasticText} from 'https://esm.run/sf-i-elastic-text/sf-i-elastic-text.js';
            import {SfIUploader} from 'https://esm.run/sf-i-uploader/sf-i-uploader.js';
            import {SfIMultitextarea} from 'https://esm.run/sf-i-multitextarea/sf-i-multitextarea.js';
            
            // import {LitElement, html, css} from 'https://unpkg.com/lit-element@3.3.3/lit-element.js?module';
            // import {SfNav} from 'https://unpkg.com/sf-nav@1.0.94/sf-nav.js?module';
            // import {SfChartPie} from 'https://unpkg.com/sf-chart-pie@1.0.4/sf-chart-pie.js?module';
            // import {SfChartBar} from 'https://unpkg.com/sf-chart-bar@1.0.6/sf-chart-bar.js?module';
            // import {SfUserAuth} from 'https://unpkg.com/sf-user-auth@1.0.89/sf-user-auth.js?module';
            // import {SfISelect} from 'https://unpkg.com/sf-i-select@1.0.91/sf-i-select.js?module';
            // import {SfISubSelect} from 'https://unpkg.com/sf-i-sub-select@1.0.82/sf-i-sub-select.js?module';
            // import {SfIForm} from 'https://unpkg.com/sf-i-form@1.0.125/sf-i-form.js?module';
            // import {SfIEvents} from 'https://unpkg.com/sf-i-events@1.0.469/sf-i-events.js?module';
            // import {SfIElasticText} from 'https://unpkg.com/sf-i-elastic-text@1.0.11/sf-i-elastic-text.js?module';
            // import {SfIUploader} from 'https://unpkg.com/sf-i-uploader@1.0.60/sf-i-uploader.js?module';
            // import {SfRandomText} from 'https://unpkg.com/sf-random-text@1.0.2/sf-random-text.js?module';
            // import {SfIMultitextarea} from 'https://unpkg.com/sf-i-multitextarea@1.0.16/sf-i-multitextarea.js?module';
            
        </script>
        <style>
          body {
            font-family: Source Sans Pro;
            margin: 2px;
            padding: 20px;
            background-color: #efefef;
          }
          .chosen {
            background-color: #E5FAD4 !important;
          }
          .td-head {
            text-transform: capitalize;
          }
          .status-format {
            text-transform: uppercase;
          }
          .text-center {
            text-align: center;
          }
          .d-flex {
            display: flex;
          }
          .justify-center {
            justify-content: center;
          }
          .justify-between {
            justify-content: space-between;
          }
          .align-center {
            align-items: center;
          }
          .w-25 {
            width: 25%;
          }
          .w-16 {
            width: 16%;
          }
          .w-14 {
            width: 14%;
          }
          .w-12 {
            width: 12%;
          }
          .w-100 {
            width: 100%;
          }
          .text-center {
            text-align: center;
          }
          table {
            box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
            border-top: solid 1px rgba(255, 255, 255, 0.8);
            border-left: solid 1px rgba(255, 255, 255, 0.8);
            border-bottom: solid 1px rgba(255, 255, 255, 0.8);
            border-right: solid 1px rgba(255, 255, 255, 0.8);
            overflow:hidden;
          }
          th {
            background-color: #6a6a6a;
            color: white;
            padding: 5px;
          }
          td {
            padding: 5px;
            font-size: 70%;
            vertical-align: top;
          }
          td span {
            font-size: 130% !important;
          }
          .td-odd {
            background-color: #efefef;
            
          }
          .td-even {
            background-color: #dedede;
          }
          .color-pending {
            color: #ffe505;
          }
          .color-pending-approval {
            color: #ffe505;
          }
          .color-not-started {
            color: #888888;
          }
          .color-not-complied {
            color: #C80036;
          }
          .color-partially-complied {
            color: #F79256;
          }
          .color-complied {
            color: #50cf01;
          }
          .color-scheduled {
            color: #888888;
          }
          .color-done {
            color: #50cf01;
          }
          .color-rejected {
            color: #C80036;
          }
          .color-approved {
            color: #50cf01;
          }
          .color-past-due-date {
            color: #ffe505;
          }
          .color-late-executed {
            color: #840B0F;
          }
          .color-late-approved {
            color: #EE2F36;
          }
          .color-late-reported {
            color: #Ef9C66;
          }
        </style>
      </head>
      <body>
        TABLE_DATA
      </body>
      <script>
        var preselectedValues = TABLE_VALUES;
        const inputs = document.querySelectorAll('.tags-input');
        for(var i = 0; i < inputs.length; i++) {
          inputs[i].preselectedValues = preselectedValues[i];
        }
      </script>
    </html>
  
  `;

  AUTOSAVE_FLAG = true;

  EXCLUDE_COLS_FROM_REGS: Array<string> = ["updatetype", "question", "invalidations", "activations", "alertschedule", "clientquestion", "countryname", "countryid", "entityname", "entityid", "locationname", "locationid", "reporters", "approvers", "timeframe", "responsedays", "execmodule", "functions", "shortid", "shortnumid", "countries", "tagsmap", "reportersmap", "approversmap", "functionheadsmap", "auditorsmap", "viewersmap", "approved", "documents", "comments", "lastupdated", "dateofcompletion", "mmdd", "completeness", "timeliness", "compliance", "delta", "triggers", "lastmodifiedby", "lastmodifiedtime"]

  COLS_REGS: Array<string> = ["jurisdiction", "subcategory", "obligationtype", "obligationtitle", "applicability", "obligation", "reporters", "approvers", "risk"]

  CHARTS_LIST_BY_MODULES: { [key: string]: Array<string> } = { "compliances": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "notices": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "contracts": ["compliance", "timeliness", "completeness", "location"], "licenses": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"], "rcmresources": ["compliance", "timeliness", "completeness", "riskSeverity", "riskArea", "location", "function", "obligationType", "jurisdiction", "frequency", "subCategory"] };

  chartSelectedLegend: Array<number> = [];

  statisticsLoadLocation: boolean = false;

  selectedFilters: any = null;

  barCharDataSet2: Array<any> = [];

  barCharDataSet2Arr: Array<any> = [];

  barCharDataSet3: Array<any> = [];

  barCharDataSet3Arr: Array<any> = [];

  barCharDataSet4: Array<any> = [];

  barCharDataSet4Arr: Array<any> = [];

  getallcountryevetsParams: string = "";

  @query('#decrypt-container')
  _SfDecryptContainer: any;

  @query('#sf-i-project-decrypt')
  _SfDecryptProjectInput: any;

  @query('#input-decrypt')
  _SfDecryptFileInput: any;

  @query('#button-decrypt')
  _SfDecryptButton: any;

  @property()
  decryptProjectId: string = "";

  @property()
  decryptFileName: string = "";

  @property()
  filteronboarding: string = '[]';

  getfilterOnboarding = () => {
    return JSON.parse(this.filteronboarding);
  }

  getFilterOnboardingString = () => {

    const jsonFilterOnboarding = JSON.parse(this.filteronboarding);

    var html = '';

    html += '<h5>Mapped Locations</h5>'

    html += '<table>';

    html += '<tr>';
    html += '<th part="td-head">';
    html += 'Country'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'State'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Location'
    html += '</th>';
    html += '</tr>';

    let count = 0;

    for (var i = 0; i < jsonFilterOnboarding.length; i++) {

      var country = jsonFilterOnboarding[i].country;

      if (jsonFilterOnboarding[i].locations != null && Object.keys(jsonFilterOnboarding[i].locations).length > 0) {

        for (var j = 0; j < Object.keys(jsonFilterOnboarding[i].locations).length; j++) {

          const state = Object.keys(jsonFilterOnboarding[i].locations)[j];

          var classBg = '';

          if (count % 2 === 0) {
            classBg = 'td-light';
          } else {
            classBg = 'td-dark';
          }

          html += '<tr>';

          html += '<td part="td-body1" class="' + classBg + '">';
          html += country;
          html += '</td>';

          html += '<td part="td-body1" class="' + classBg + '">';
          html += state;
          html += '</td>';

          html += '<td part="td-body1" class="' + classBg + '">';

          //console.log('gettinglocations', (jsonFilterOnboarding[i]['locations'][state]));

          var tempHtml = '';
          for (var k = 0; k < (jsonFilterOnboarding[i]['locations'][state]).length; k++) {
            const location = (jsonFilterOnboarding[i]['locations'][state])[k];
            tempHtml += location;
            if (k < ((jsonFilterOnboarding[i]['locations'][state]).length - 1)) {
              tempHtml += ', ';
            }
          }
          html += ('<div><sf-i-elastic-text exportparts="highlight,highlight-count" class="statute-summary id-9" text="' + tempHtml + '" minlength="50"></sf-i-elastic-text></div>');
          html += '</td>';

          html += '</tr>';

          count++;

        }

      }


    }

    html += '</table>';


    html += '<h5 class="mt-20">Mapped Laws</h5>'

    html += '<table>';

    html += '<tr>';
    html += '<th part="td-head">';
    html += 'Country'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'State'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Subcategory'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Exclusions'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Inclusions'
    html += '</th>';
    html += '</tr>';

    for (var i = 0; i < jsonFilterOnboarding.length; i++) {

      var classBg = '';

      if (i % 2 === 0) {
        classBg = 'td-light';
      } else {
        classBg = 'td-dark';
      }

      html += '<tr>';
      html += '<td part="td-body1" class="' + classBg + '">';
      html += jsonFilterOnboarding[i].country;
      html += '</td>';
      html += '<td part="td-body1" class="' + classBg + '">';
      for (var j = 0; j < jsonFilterOnboarding[i].states.length; j++) {
        html += ('<div>' + (jsonFilterOnboarding[i].states[j].length === 0 ? 'Federal' : jsonFilterOnboarding[i].states[j]) + '</div>');
      }
      html += '</td>';
      html += '<td part="td-body1" class="' + classBg + '">';
      for (var j = 0; j < jsonFilterOnboarding[i].subcategories.length; j++) {
        html += ('<div>' + jsonFilterOnboarding[i].subcategories[j] + '</div>');
      }
      html += '</td>';
      html += '<td part="td-body1" class="' + classBg + '">';
      if (jsonFilterOnboarding[i].excludestatutes != null) {
        for (var j = 0; j < jsonFilterOnboarding[i].excludestatutes.length; j++) {
          html += ('<div><sf-i-elastic-text exportparts="highlight,highlight-count" class="statute-summary id-9" text="' + jsonFilterOnboarding[i].excludestatutes[j] + '" minlength="10"></sf-i-elastic-text></div>');
        }
      }
      html += '</td>';
      html += '<td part="td-body1" class="' + classBg + '">';
      if (jsonFilterOnboarding[i].includestatutes != null) {
        for (var j = 0; j < jsonFilterOnboarding[i].includestatutes.length; j++) {
          html += ('<div><sf-i-elastic-text exportparts="highlight,highlight-count" class="statute-summary id-9" text="' + jsonFilterOnboarding[i].includestatutes[j] + '" minlength="20"></sf-i-elastic-text></div>');
        }
      }
      html += '</td>';
      html += '</tr>';

    }

    html += '</table>';

    return html;

  }

  @property()
  locations!: string;

  getLocations = () => {
    return JSON.parse(this.locations);
  }

  getLocationsByCountry = (country: string, statute: string) => {

    let locations = [];
    if (this.getLocations()[country] != null) {
      const states = Object.keys(this.getLocations()[country]);
      for (var i = 0; i < states.length; i++) {

        if (this.getfilterOnboarding().length === 0) {
          locations.push(...this.getLocations()[country][states[i]]);
        } else {
          for (var j = 0; j < this.getLocations()[country][states[i]].length; j++) {
            for (var k = 0; k < this.getfilterOnboarding().length; k++) {
              if (this.getfilterOnboarding()[k]['country'] == country) {

                if (this.getfilterOnboarding()[k]['locations'] != null) {
                  if (this.getfilterOnboarding()[k]['locations'][states[i]] != null) {
                    var push = true;
                    if (this.getfilterOnboarding()[k]['locations'][states[i]].includes(this.getLocations()[country][states[i]][j])) {

                      if (this.getfilterOnboarding()[k]['excludelocations'] == null) {
                      } else {
                        if (this.getfilterOnboarding()[k]['excludelocations'][statute] == null) {
                        } else {
                          if (this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]] == null) {
                          } else {
                            if (statute == "Information Technology Act, 2000") {
                              //console.log("getLocationsByCountry", push, this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]], this.getLocations()[country][states[i]][j], this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]].includes(this.getLocations()[country][states[i]][j]));
                            }
                            if (this.getfilterOnboarding()[k]['excludelocations'][statute][states[i]].includes(this.getLocations()[country][states[i]][j])) {
                              //console.log("getLocationsByCountry", 'setting false');
                              push = false;
                            }
                          }
                        }
                        if (statute == "Information Technology Act, 2000") {
                          //console.log("getLocationsByCountry", push, this.getLocations()[country][states[i]][j]);
                        }
                      }
                    } else {
                      push = false;
                    }

                  } else {
                    push = false;
                  }
                } else {
                  push = false;
                }
                if (push) {
                  locations.push(this.getLocations()[country][states[i]][j]);
                }

              }
            }
          }
        }

      }
    }

    return locations;

  }

  getLocationsByState = (country: string, state: string, statute: string) => {

    //console.log('getting getLocationsByState', country, state, this.getfilterOnboarding());

    let locations = [];

    if (this.getLocations()[country] != null) {
      if (this.getLocations()[country][state] != null) {

        if (this.getLocations()[country][state] != null) {
          if (this.getfilterOnboarding().length === 0) {
            locations.push(...this.getLocations()[country][state]);
          } else {
            for (var k = 0; k < this.getfilterOnboarding().length; k++) {
              if (this.getfilterOnboarding()[k]['country'] == country) {
                for (var i = 0; i < this.getLocations()[country][state].length; i++) {
                  var push = true;
                  if (this.getfilterOnboarding()[k]['locations'] != null) {
                    if (this.getfilterOnboarding()[k]['locations'][state] != null) {
                      if (this.getfilterOnboarding()[k]['locations'][state].includes(this.getLocations()[country][state][i])) {

                        if (this.getfilterOnboarding()[k]['excludelocations'] == null) {
                        } else {
                          if (this.getfilterOnboarding()[k]['excludelocations'][statute] == null) {
                          } else {
                            if (this.getfilterOnboarding()[k]['excludelocations'][statute][state] == null) {
                            } else {
                              if (this.getfilterOnboarding()[k]['excludelocations'][statute][state].includes(this.getLocations()[country][state][i])) {
                                push = false;
                              }
                            }
                          }
                        }
                      } else {
                        push = false;
                      }

                    } else {
                      push = false;
                    }
                  } else {
                    push = false;
                  }
                  if (push) {
                    locations.push(this.getLocations()[country][state][i]);
                  }

                }
              }
            }
          }
        }
      }
    }

    //console.log('getting getLocationsByState return ', locations);
    return locations;

  }

  @property({ type: Array })
  selectedCbs: Array<any> = [];

  @property()
  projectId!: string;

  @property()
  contractStartDate: string = "";

  @property()
  name!: string;

  @property()
  disableflagggrcresponse: string = "";

  @property()
  disablesave: string = "";

  @property()
  disableclientresponse: string = "";

  @property()
  disablesignoff: string = "";

  @property()
  apiId!: string;

  @property()
  apiId2!: string;

  @property()
  apiIdStatutes!: string;

  @property()
  apiIdDefinitions!: string;

  @property()
  apiidReportformats!: string;

  @property()
  apiIdProjects!: string;

  @property()
  apiIdCompliances!: string;

  @property()
  apiIdList!: string;

  @property()
  apiIdDetail!: string;

  @property()
  apiIdUsers!: string;

  @property()
  apiIdTags!: string;

  @property()
  apiIdUserProfiles!: string;

  @property()
  apiIdNotices!: string;

  @property()
  apiIdAgreements!: string;

  @property()
  apiIdLicenses!: string;

  @property()
  apiIdRCMResources!: string;

  @property()
  apiIdModules!: string;

  @property()
  apiIdDashboard!: string;

  @property()
  apiIdUpload!: string;

  @property()
  apiRegionUpload!: string;

  @property()
  apiMethodList!: string;

  @property()
  apiMethodDetail!: string;

  @property()
  apiBodyList!: string;

  @property()
  apiBodyDetail!: string;

  @property()
  userProfileId!: string;

  @property()
  graphParam: string = "";

  @property()
  entityId: string = "";

  @property()
  locationId: string = "";

  @property()
  showRegisterExport: string = "false";

  @property()
  countryId: string = "";

  @property()
  functionId: string = "";

  @property()
  tagId: string = "";

  @property()
  userName!: string;

  @property()
  projectName!: string;

  @property()
  selectedCriteria!: string;

  @property()
  apiResponseFieldList!: string;

  @property()
  rcmSelectedCompliance!: any;

  @property()
  rcmSelectedProjects!: any;

  @property()
  rcmSelectedDate!: any;

  @property()
  rcmSelectedMessage!: any;

  @property()
  myOnboardingTab: string = "";

  @property()
  myOnboardingTabGroup: string = "";

  @property()
  myRcmTab: string = this.TAB_RCM_COMPLIANCES;

  @property()
  myNoticesTab: string = this.TAB_COMPLIANCES;

  @property()
  myRole: string = "";

  @property()
  chart: any = null;

  @property()
  chartBase64: any = null;

  @property()
  chart2: any = null;

  @property()
  chart2Base64: any = null;

  @property()
  chart3: any = null;

  @property()
  chart3Base64: any = null;

  @property()
  chart4: any = null;

  @property()
  chart4Base64: any = null;

  @property()
  calendarStartDD!: string;

  @property()
  calendarStartMM!: string;

  @property()
  calendarStartYYYY!: string;

  @property({ type: Array })
  calendar: Date[] = [];

  @property()
  mappedValuesDueDates: any = {};

  @property()
  mappedValuesUsers: any = {};

  @property()
  mappedValuesTags: any = {};

  @property()
  unmappedEvents: any = null;

  @property()
  mappings: any = null;

  @property()
  triggers: any = null;

  @property({ type: Array })
  monthNames: string[] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  @property()
  events: any = null;

  @property()
  nextEvents: any = null;

  @property()
  registerEvents: any = null;

  @property()
  registerSelectedIds: any = [];

  @property()
  notices: any = null;

  @property()
  statistics: any = null;

  @property()
  statisticsMeta: any = null;

  @property()
  statisticsSelectedFilter: string = "";

  @property()
  statisticsFiltersData: any = null;

  @property()
  statisticsFiltersCsv: any = null;

  @property()
  statisticsFunctionsGraphData: any = null

  @property()
  statisticsLocationsGraphData: any = null

  @property()
  statisticsReportersGraphData: any = null

  @property()
  streamIndex: any = null;

  @property()
  eventsInWindow: any = null;

  @property()
  eventHideFields: any = null;

  getEventHideFields = () => {
    return JSON.parse(this.eventHideFields);
  }

  @property()
  eventPreviewFields: any = null;

  getEventPreviewFields = () => {
    return JSON.parse(this.eventPreviewFields);
  }

  @property()
  eventFields: any = null;

  getEventFields = () => {
    return JSON.parse(this.eventFields ?? "[]");
  }

  @property()
  eventFieldDependencies: any = null;

  getEventFieldDependencies = () => {
    return JSON.parse(this.eventFieldDependencies);
  }

  getApiBodyList = () => {
    //console.log('calendar api body list', this.apiBodyList);
    try {
      return JSON.parse(this.apiBodyList);
    } catch (e: any) {
      return {};
    }
  }

  getApiBodyDetail = () => {
    return JSON.parse(this.apiBodyDetail);
  }

  @property()
  csvDataRegisters: string = "";

  @property()
  csvDataCompliances: string = "";

  @property()
  csvTableData: string = "";

  @property()
  csvDataStats: string = "";

  @property()
  csvGraphStats: string = "";

  @property()
  csvCompletenessStats: string = "";

  @property()
  csvTimelinessStats: string = "";

  @property()
  csvComplianceStats: string = "";

  @property()
  htmlDataCompliances: string = "";

  @property()
  htmlDataStats: string = "";

  @property()
  htmlDataSummary: string = "";

  @property()
  htmlStatsFilter: string = "";

  @property()
  period: string = "";

  @property()
  mode!: string;

  @property({ type: Number })
  flowRcmNotification: number = 0;

  @property()
  flowGraph: string = "";

  @property()
  flow: string = "";

  @property()
  fill: string = "solid";

  @property({ type: Array })
  filterTags: string[] = [];


  @property()
  subfilter: string = "";


  @property()
  riskAreasData: any = null;

  @property()
  riskAreasPartStatusData: any = null;

  @property()
  riskAreasLateStatusData: any = null;

  @property()
  riskAreasComplianceStatusData: any = null;

  @property()
  riskSeverityData: any = null;

  @property({ type: Array })
  arrCols: Array<string> = ["country", "state", "obligationtitle", "statute", "category"];

  @property({ type: Array })
  arrRcmProjectCols: Array<string> = ["name"];

  @property()
  riskSeverityPartStatusData: any = null;

  @property()
  riskSeverityLateStatusData: any = null;

  @property()
  riskSeverityComplianceStatusData: any = null;

  @property()
  functionData: any = null;

  @property()
  functionPartStatusData: any = null;

  @property()
  functionLateStatusData: any = null;

  @property()
  functionComplianceStatusData: any = null;

  @property()
  reporterData: any = null;

  @property()
  reporterPartStatusData: any = null;

  @property()
  reporterLateStatusData: any = null;

  @property()
  reporterComplianceStatusData: any = null;

  @property()
  obligationTypeData: any = null;

  @property()
  obligationTypePartStatusData: any = null;

  @property()
  obligationTypeLateStatusData: any = null;

  @property()
  obligationTypeComplianceStatusData: any = null;

  @property()
  jurisdictionData: any = null;

  @property()
  jurisdictionPartStatusData: any = null;

  @property()
  jurisdictionLateStatusData: any = null;

  @property()
  jurisdictionComplianceStatusData: any = null;

  @property()
  currentColumnIndex: string = "";

  @property()
  frequencyData: any = null;

  @property()
  frequencyPartStatusData: any = null;

  @property()
  frequencyLateStatusData: any = null;

  @property()
  frequencyComplianceStatusData: any = null;

  @property()
  subcategoryData: any = null;

  @property()
  subcategoryPartStatusData: any = null;

  @property()
  subcategoryLateStatusData: any = null;

  @property()
  subcategoryComplianceStatusData: any = null;

  @property()
  locationData: any = null;

  @property()
  locationPartStatusData: any = null;

  @property()
  locationLateStatusData: any = null;

  @property()
  locationComplianceStatusData: any = null;

  @property()
  suspenseCount: number = 0;

  @property({ type: Array })
  selectedItemIds: Array<string> = [];

  @property({ type: Array })
  selectedItems: Array<any> = [];

  @property()
  selectedStatus: string = "";

  @property()
  selectedTab: string = "";

  @property({ type: Number })
  selectedCountryTab: number = -1;

  @property()
  restrictToMapping: string = "";

  @property()
  enableDeleteLatestReport: string = "";

  @property()
  stream: string = this.TAB_STREAM;

  @property()
  myroles: string = "[]";

  @property()
  blocksize: string = "5";

  @property()
  features: string = "[]"

  getFeatures = () => {
    return ['compliances', ...JSON.parse(this.features)]
  }

  selectedFeatures: string[] = ['compliances']

  nextPage: number = 0;

  nextTabRole: string = "";

  nextTabStatus: string = "";

  @property()
  sdate: string = "";

  @property()
  edate: string = "";

  lastupdated: string = "";

  changedOnboardingItemIds: string[] = [];

  selectedCountryIndex: number = 0;

  selectedRegisterIndex: number = -1;

  showReportedLocations: boolean = false;

  @property()
  selectallblock: string = "100";

  graphFilter: string = "";

  recentlyReported: any = {}

  registerFilters: { [key: string]: { [key: string]: boolean } } = {};

  suspenseFlag: boolean = false;

  tablecols: string[] = []

  reportedLocationsVals: any[] = []

  minRiskMitigated: number[] = [];
  minRiskResidual: number[] = [];

  maxRiskMitigated: number[] = [];
  maxRiskResidual: number[] = [];

  finRiskCurrency: string[] = [];

  reportingSuggestions: string[] = [
    "Done",
    "Done on time",
    "Completed"
  ]
  reportingSuggestionsNotApplicable: string[] = [
    "Although legally applicable, the compliance is not relevant for this period"
  ]

  flagAdhoc: boolean = true

  @property()
  reportingLimitDays: number = 90;

  static override styles = css`

    .bg-white {
      background-color: white;
    }

    .proposed-users-table {

      width: 150px;

    }

    .lds-dual-ring1 {
      display: inline-block;
      width: 15px;
      height: 15px;
    }
    .lds-dual-ring1:after {
      content: " ";
      display: block;
      width: 15px;
      height: 15px;
      margin: 0px;
      border-radius: 50%;
      border: 2px solid #fff;
      border-color: #666 #ddd #666 #ddd;
      animation: lds-dual-ring 0.8s linear infinite;
    }
  
    @keyframes lds-dual-ring1 {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }

    sf-i-uploader::part(button-icon) {
      border-width: 0px;      
      border-radius: 5px;
      color: #fff;
      background: #c15c83;
      box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
      border-top: solid 1px rgba(255, 255, 255, 0.3);
      border-left: solid 1px rgba(255, 255, 255, 0.3);
      border-bottom: solid 1px rgba(0, 0, 0, 0.1);
      border-right: solid 1px rgba(0, 0, 0, 0.1);
    }

    #calendar-tab-next span {
      font-size: 80%;
    }

    .justify-evenly {
      justify-content: space-evenly;
    }

    #detail-container {
      z-index: 101;
    }
    #detail-list-container {
      z-index: 100;
    }

    .plain-filter-icon {
      cursor: pointer;
    }

    .pos-fixed {
      display: flex;
      justify-content: center;
      align-items: center;
      position: fixed;
      top: 0px;
      left: 0px;
      width: 100%;
      min-height: 100%;
      z-index: 101;
    }

    .sub-button {
      font-size: 80%;
    }

    .sub-button span {
      font-size: 80%;
    }

    .pos-fixed-scroll {
      display: flex;
      justify-content: center;
      align-items: center;
      position: fixed;
      bottom: 50px;
      right: 50px;
      z-index: 99;
    }

    .cover-slide {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 100%;
      height: 100%;
      background-color: black;
      opacity: 0.4;
    }

    
    .detail-list-container,
    .detail-container,
    .report-summary-container {
      width: 60%;
      height: 400px;
      background-color: #efefef;
      overflow-y: auto;
      border-radius: 10px;
      z-index: 102;
    }

    .sf-i-form-modal-container {
      position: fixed;
      width: 80%;
      height: 80%;
      top: 10%;
      right: 10%;
      background-color: white;
      border: 1px solid #888;
      overflow: scroll;
      z-index: 100
    }

    @media (orientation: portrait) {

      .detail-container,
      .report-summary-container {
        width: 80%;
        height: 400px;
        background-color: #efefef;
        overflow-y: auto;
        border-radius: 10px;
      }

    }
    
    .box-large {
      height: 150px;
      width: 100%;
      background: linear-gradient(-45deg, transparent 10%, #ccc 5%, transparent 60%);
      background-size: 300%;
      background-position-x: 100%;
      animation: shimmer 1.5s infinite linear;
      margin-top: 20px;
      margin-bottom: 20px;
    }


    .box {
      margin-top: 20px;
      height: 10px;
      width: 100%;
      background: linear-gradient(-45deg, transparent 10%, #ccc 5%, transparent 60%);
      background-size: 300%;
      background-position-x: 100%;
      animation: shimmer 1.5s infinite linear;
      margin-bottom: 20px;
    }

    .chosen {
      background-color: #E5FAD4 !important;
    }
  
    @keyframes shimmer {
      to {
         background-position-x: 0%
      }
   }  

   .truncate {
    display: none
   }

    @media (orientation: landscape) {

      .chart-container {
        width: 100%;
        overflow-x: scroll;
        max-height: 60vh;
      }

      .chart-item {
        min-width: 40%;
      }

    }

    @media (orientation: portrait) {

      .chart-container {
        width: 100%;
        overflow-x: scroll;
        max-height: 75vh
      }

      .chart-item {
        width: 100%;
      }

    }


    @media (orientation: portrait) {

      #tab-container {
        position: fixed;
        bottom: 0px;
        left: 0px;
        background-color: #efefef;
        padding-left: 10px;
        padding-right: 10px;
        padding-top: 10px;
        overflow-x: auto;
        width: 100%;
        max-width: 100%;
        justify-content: start;
        box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
        z-index: 101;
      }
      

    }

    @media (orientation: landscape) {

      .mobile-only {
        display: none;
      }

      .desktop-only {
        display: flex;
      }

    }

    .title-byline {
      font-size: 90%;
    }

    @media (orientation: portrait) {

      .mobile-only {
        display: flex;
      }

      .desktop-only {
        display: none;
      }

    }
    
    .SfIEventsC {
      display: flex;
      flex-direction: column;
      align-items: stretch;
      justify-content: space-between;
    }

    .td-dark {
      background-color: #e9e9e9;
    }

    .td-dark-selected {
      background-color: #e3e0c8;
    }

    .td-light {
      background-color: #f6f6f6;
    }
    .td-light-selected {
      background-color: #f5f2d9;
    }

    .invisible {
      visibility: hidden;
    }

    .scroll-x {
      overflow-x: auto;
    }

    .mw-140 {
      max-width: 140%
    }
    
    .no-shrink {
      flex-shrink: 0;
    }

    .p-10 {
      padding: 10px;
    }

    .cursor {
      cursor: pointer;
    }

    .commentbox {
      padding: 10px;
      border: solid 1px gray;
      border-radius: 10px;
    }

    .reporterbox {
      width: 90%;
      margin-right: 10%;
    }

    .approverbox {
      width: 90%;
      margin-left: 5%;
    }

    .pr-5 {
      padding-right: 5px;
    }

    .pt-5 {
      padding-top: 5px;
    }

    .pb-5 {
      padding-bottom: 5px;
    }

    .pb-20 {
      padding-bottom: 20px;
    }

    .m-20 {
      margin: 20px;
    }

    .m-10 {
      margin: 10px;
    }

    .text-start {
      text-align: start;
    }

    .text-center {
      text-align: center;
    }

    .mb-0 {
      margin-bottom: 0px;
    }

    .mt-0 {
      margin-top: 0px;
    }

    .pl-0-imp {
      padding-left: 0px !important;
    }

    .ml-0 {
      margin-left: 0px;
    }

    .mr-0 {
      margin-right: 0px;
    }

    .mb-100 {
      margin-bottom: 100px;
    }

    .mb-10 {
      margin-bottom: 10px;
    }

    .mb-5 {
      margin-bottom: 5px;
    }

    .mt-5 {
      margin-top: 5px;
    }

    #button-back-add-mapping {
      bottom: 10px;
      z-index: 98;
      position: sticky;
      width: 96%;
      margin-left: 2%;
      margin-right: 2%;
    }

    .fixed-bottom {
      position: fixed;
      bottom: 0px;
      left: 0px;
      width: 100%;
      z-index: 99;
    }

    .div-graph-complete {
      background-color: #50cf01;
      height: 100%;
      width: 0%;
    }

    .div-graph-pending {
      background-color: #ffe505;
      height: 100%;
      width: 100%;
    }

    .badge-success {
      padding-left: 5px;
      padding-right: 5px;
      padding-top: 5px;
      padding-bottom: 2px;
      border-radius: 7px;
      color: white;
      background-color: #50cf01;
    }

    .badge-warning {
      padding-left: 5px;
      padding-right: 5px;
      padding-top: 5px;
      padding-bottom: 2px;
      border-radius: 7px;
      color: black;
      background-color: #ffe505;
    }

    .badge-error {
      padding-left: 5px;
      padding-right: 5px;
      padding-top: 5px;
      padding-bottom: 2px;
      border-radius: 7px;
      color: white;
      background-color: #C80036;
    }

    input:not([type='radio'], [type="file"]) {

    border-width: 0px;      
    border-radius: 5px;
    color: #666;
    background: #efefef;
    box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
    border-top: solid 1px rgba(255, 255, 255, 0.3);
    border-left: solid 1px rgba(255, 255, 255, 0.3);
    border-bottom: solid 1px rgba(0, 0, 0, 0.1);
    border-right: solid 1px rgba(0, 0, 0, 0.1);
    padding: 10px;

    }

    .bg-pending {
      background-color: #ffe505;
    }

    .bg-done {
      background-color: #50cf01;
    }

    .color-pending {
      color: #ffe505;
    }
    .color-pending-approval {
      color: #ffe505;
    }
    .color-not-started {
      color: #888888;
    }
    .color-not-complied {
      color: #C80036;
    }
    .color-partially-complied {
      color: #F79256;
    }
    .color-complied {
      color: #50cf01;
    }
    .color-complied-with-gaps {
      color: #ffe505;
    }
    .color-reported-non-compliance {
      color: #840B0F;
    }
    .color-scheduled {
      color: #888888;
    }
    .color-done {
      color: #50cf01;
    }
    .color-rejected {
      color: #C80036;
    }
    .color-approved {
      color: #50cf01;
    }
    .color-past-due-date {
      color: #ffe505;
    }
    .color-late-executed {
      color: #840B0F;
    }
    .color-late-approved {
      color: #EE2F36;
    }
    .color-late-reported {
      color: #Ef9C66;
    }

    .pr-10 {
      padding-right: 10px;
    }

    .pt-10 {
      padding-top: 10px;
    }

    .pt-20 {
      padding-top: 20px;
    }

    .pb-10 {
      padding-bottom: 10px;
    }

    .bg-left {
      border-top: solid 1px #dcdcdc;
      padding-right: 5px;
    }

    .bg-left-no-border {
      padding-right: 5px;
    }

    .m-0 {
      margin: 0px;
    }

    .mt-10 {
      margin-top: 10px;
    }

    .mt-5 {
      margin-top: 5px;
    }

    .ml-5 {
      margin-left: 5px;
    }
    
    .ml-10 {
      margin-left: 10px;
    }

    .ml-10-m-0 {
      margin-left: 10px;
    }

    .mt-20 {
      margin-top: 20px;
    }

    .ml-20 {
      margin-left: 20px;
    }

    .ml-20-m-0 {
      margin-left: 20px;
    }

    .mr-20 {
      margin-right: 20px;
    }

    .mb-20 {
      margin-bottom: 20px;
    }

    .flex-grow {
      flex-grow: 1;
    }

    .flex-wrap {
      flex-wrap: wrap;
    }

    .left-sticky {
      left: 0px;
      position: sticky;
      z-index: 100;
    }

    .link {
      text-decoration: underline;
      cursor: pointer;
    }

    .accordian-head {
      cursor: pointer;
    }

    .button-submit {
      font-weight: 800;
      font-size: 110%;
    }

    .mr-10 {
      margin-right: 10px;
    }

    .pl-5 {
      padding-left: 5px;
    }

    .pl-10 {
      padding-left: 10px;
    }

    .pr-10 {
      padding-right: 10px;
    }

    .pl-20 {
      padding-left: 20px;
    }

    .pr-20 {
      padding-right: 20px;
    }

    .gone {
      display: none
    }

    .loader-element {
      position: fixed;
      right: 30px;
      top: 30px;
      margin-left: 5px;
      z-index: 102
    }

    #row-unmapped-graph {
      width: 300px;
      height: 10px;
    }

    #stream-container {
      padding: 0%;
    }

    #custom-container {
      padding: 0%;
    }

    #adhoc-container {
      padding: 0%;
    }

    #upcoming-container {
      padding: 0%;
    }

    .container-mapping-event {
      overflow-x: auto;
    }

    #this-container {
      padding: 2%;
    }

    #past-container {
      padding: 2%;
    }

    .stream-event-list {
      margin-left: 0px;
      padding: 10px;
    }

    .stream-events-container {
      overflow-x: auto;
      width: 100%
    }
    .stream-event-list-container {
      width: 200px;
    }

    .stream-event-selected {
      padding-left: 20px;
      padding-right: 10px;
      padding-top: 5px;
      padding-bottom: 5px;
    }
    
    .stream-event-not-selected {
      padding-left: 20px;
      padding-right: 10px;
      padding-top: 5px;
      padding-bottom: 5px;
      color: #aaa;
      font-size: 80%;
    }

    .stream-event-not-selected-hidden {
      padding-left: 20px;
      padding-right: 10px;
      padding-top: 5px;
      padding-bottom: 5px;
      color: #aaa;
      line-height: 0.05;
    }

    .stream-month-selected {
      padding: 10px;
      text-align: center;
    }

    .stream-month-not-selected {
      padding: 10px;
      text-align: center;
    }

    .calendar-left-col {
      width: 30%;
    }

    @media (orientation: portrait) {

      .calendar-right-data {
        width: 100%;
      }
      
      .ml-10-m-0 {
        margin-left: 0px;
      }
      
      .ml-20-m-0 {
        margin-left: 0px;
      }

    }

    @media (orientation: landscape) {

      .calendar-right-data {
        width: 70%;
      }

    }
    

    .day-item {
      width: 14%;
      margin-bottom: 5px;
      text-align: center;
    }

    .date-item {
      font-size: 80%;
      color: #333;
    }

    .date-item-before {
      font-size: 80%;
      color: #999;
    }

    .dot {
      height: 4px;
      border-radius: 3px;
    }

    .title-item {
      padding: 5px;
      margin-bottom: 20px;
    }

    .title-item-date {
      padding-right: 5px;
      margin-bottom: 20px;
    }

    .calendar-item {
      padding: 8px;
      width: 90%;
      margin-bottom: 20px;
    }

    .muted {
      color: gray;
    }

    .td-head {
      text-transform: capitalize;
    }

    .tab-button {
      padding: 10px;
      padding-left: 15px;
      padding-right: 15px;
      font-size: 105%;
      margin-left: 5px;
      margin-right: 5px;
    }
    .tab-button-small {
      padding: 5px;
      padding-left: 7px;
      padding-right: 7px;
      font-size: 95%;
      margin-left: 5px;
      margin-right: 5px;
    }

    .td-body {
      padding: 5px;
    }

    .td-dark {
      background-color: #e9e9e9;
    }

    .td-highlight {
      background-color: black;
      color: white;
    }

    .td-light {
      background-color: #f6f6f6;
    }

    td {
      white-space: nowrap;
    }

    .w-100 {
      width: 100%;
    }

    .m-w-200 {
      min-width: 200px;
    }

    .w-90 {
      width: 90%;
    }

    .fw-100 {
      font-weight: 100;
    }

    .fw-200 {
      font-weight: 200;
    }

    .fw-300 {
      font-weight: 300;
    }

    .fw-600 {
      font-weight: 600;
    }

    .align-start {
      align-items: flex-start;
    }

    .align-stretch {
      align-items: stretch;
    }

    .align-baseline {
      align-items: baseline;
    }

    .align-end {
      align-items: flex-end;
    }

    .align-center {
      align-items: center;
    }

    .align-self-start {
      align-self: flex-start;
    }
    
    .lds-text {
      position: absolute;
      left: 0px;
      top: 0px;
      margin-top: 2px;
      margin-left: 2px;
      width: 50px;
      height: 50px;
      color: gray;
    }

    .lds-text-c {
      display: flex;
      width: 100%;
      height: 100%;
      justify-content: center;
      align-items: center;
      margin-top: 40px;
      font-size: 90%;
    }

    .lds-dual-ring {
      display: inline-block;
      width: 50px;
      height: 50px;
    }
    .lds-dual-ring:after {
      content: " ";
      display: block;
      width: 50px;
      height: 50px;
      margin: 0px;
      border-radius: 50%;
      border: 2px solid #fff;
      border-color: #888 #ddd #888 #ddd;
      background-color: white;
      animation: lds-dual-ring 0.8s linear infinite;
    }

    .lds-dual-ring-lg {
      display: inline-block;
      width: 30px;
      height: 30px;
    }
    .lds-dual-ring-lg:after {
      content: " ";
      display: block;
      width: 30px;
      height: 30px;
      margin: 0px;
      border-radius: 50%;
      border: 3px solid #fff;
      border-color: #888 #ddd #888 #ddd;
      animation: lds-dual-ring 0.8s linear infinite;
    }

    .div-row-error {
      display: flex;
      justify-content: center;
      position: fixed;
      position: fixed;
      top: 0px;
      right: 0px;
      margin-top: 20px;
      margin-right: 20px;
      display: none;
      align-items:center;
      background-color: white;
      border: dashed 1px red;
      padding: 20px;
      z-index: 102;
    }

    .div-row-error-message {
      color: red;
      padding: 5px;
      background-color: white;
      text-align: center;
    }

    .div-row-success {
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: fixed;
      top: 0px;
      right: 0px;
      margin-top: 20px;
      margin-right: 20px;
      display: none;
      align-items:stretch;
      background-color: white;
      border: dashed 1px green;
      padding: 20px;
      z-index: 102;
    }

    .div-row-success-message {
      color: green;
      padding: 5px;
      background-color: white;
      text-align: center;
    }

    .div-row-success-message-btn-container {
      background-color: white;
      display: flex;
      flex-direction: row;
      justify-content: end;
      align-items: center;
    }

    .d-flex {
      display: flex;
    }

    .flex-col {
      flex-direction: column;
    }

    .justify-center {
      justify-content: center;
    }

    .justify-between {
      justify-content: space-between;
    }

    .justify-end {
      justify-content: flex-end;
    }

    @keyframes lds-dual-ring {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }  

    .hide {
      display: none;
    }

    .lb {
      width: 5%
    }
    .rb {
      width: 5%
    }

    .main-container {
      width: 90%;
      overflow-x: auto;
    }

    .filter-list-container{
      position: absolute;
      right: 5px;
      background-color: white;
      border: solid 1px #888;
      border-radius: 5px;
      width: max-content;
    }

    .filter-button-container{
      position: relative;
    }

    .max-width-100{
      max-width: 100%
    }
    @media (orientation: landscape) {

      .lb {
        width: 30%
      }
      .rb {
        width: 30%
      }


      .calendar-item {
        width: 20%;
        margin: 2%;
        padding: 8px;
      }

      .main-container {
        width: 40%;
      }

    }

    #button-refresh {
      display: none;
      position: fixed;
      bottom: 10px;
      right: 10px
    }
    #button-background-process {
      cursor: pointer
    }
    
    .small-icon {
      font-size: 98%
    }

    .new-feature{
      display: block;
      width: fit-content;
    }
  `;

  @query('.SfIEventsC')
  _SfIEventsC: any;

  @query('.div-row-error')
  _SfRowError: any;

  @query('.div-row-error-message')
  _SfRowErrorMessage: any;

  @query('.div-row-success')
  _SfRowSuccess: any;

  @query('.div-row-success-message')
  _SfRowSuccessMessage: any;

  @query('.div-row-success-message-btn-container')
  _SfRowSuccessMessageBtnContainer: any;

  @query('.loader-element')
  _SfLoader: any;

  @query('#calendar-container')
  _SfCalendarContainer: any;

  @query('#button-generate')
  _SfButtonGenerate: any;

  @query('.button-search')
  _SfButtonSearch: any;

  @query('.button-save')
  _SfButtonSave: any;

  @query('.button-next')
  _SfButtonNext: any;

  @query('.button-prev')
  _SfButtonPrev: any;

  @query('.input-search')
  _SfInputSearch: any;

  @query('#button-sync-chosen-project')
  _SfButtonSyncChosenProject: any;

  @query('#button-map-chosen-project')
  _SfButtonMapChosenProject: any;

  @query('#button-back-chosen-project')
  _SfButtonBackChosenProject: any;

  @query('#button-back-calendar-mapping')
  _SfButtonBackCalendarMapping: any;

  @query('#button-back-sync-mapping')
  _SfButtonBackSyncMapping: any;

  @query('#button-back-chosen-mapping')
  _SfButtonBackChosenMapping: any;

  @query('#title-chosen-project')
  _SfTitleChosenProject: any;

  @query('#title-chosen-mapping')
  _SfTitleChosenMapping: any;

  @query('#container-chosen-project')
  _SfContainerChosenProject: any;

  @query('#container-project-select')
  _SfContainerProjectSelect: any;

  @query('#container-project-actions')
  _SfContainerProjectActions: any;

  @query('#stream-container')
  _SfStreamContainer: any;

  @query('#upcoming-container')
  _SfUpcomingContainer: any;

  @query('#detail-container')
  _SfDetailContainer: any;

  @query('#detail-list-container')
  _SfDetailListContainer: any;

  @query('#report-summary-container')
  _SfReportSummaryContainer: any;

  @query('#this-container')
  _SfThisContainer: any;

  @query('#past-container')
  _SfPastContainer: any;

  @query('#custom-container')
  _SfCustomContainer: any;

  @query('#adhoc-container')
  _SfAdhocContainer: any;

  @query('#find-container')
  _SfFindContainer: any;

  @query('#register-container')
  _SfRegisterContainer: any;

  @query('#mapping-container')
  _SfMappingContainer: any;

  @query('#stream-event-status')
  _SfStreamEventStatus: any;

  @query('#tab-container')
  _SfTabContainer: any;

  @query('#mapping-tab-container')
  _SfMappingTabContainer: any;

  @query('#role-tab-container')
  _SfRoleTabContainer: any;

  @query('#status-tab-container')
  _SfStatusTabContainer: any;

  @query('#onboarding-tab-container')
  _SfOnboardingTabContainer: any;

  @query('#onboarding-status-container')
  _SfOnboardingStatusContainer: any;

  @query('#rcm-container')
  _SfRcmContainer: any;

  @query('#rcm-container-list')
  _SfRcmContainerList: any;

  @query('#rcm-tab-container')
  _SfRcmTabContainer: any;

  @query('#statutes-list-container')
  _SfOnboardingStatutesListContainer: any;

  @query('#rcm-compliance-container')
  _SfRcmComplianceContainer: any;

  @query('#rcm-projects-container')
  _SfRcmProjectsContainer: any;

  @query('#rcm-date-container')
  _SfRcmDateContainer: any;

  @query('#rcm-confirm-container')
  _SfRcmConfirmContainer: any;

  @query('#rcm-jobs-container')
  _SfRcmJobsContainer: any;

  @query('#statutes-container')
  _SfOnboardingStatutesContainer: any;

  @query('#compliances-list-container')
  _SfOnboardingCompliancesListContainer: any;

  @query('#compliances-container')
  _SfOnboardingCompliancesContainer: any;

  @query('#entities-list-container')
  _SfOnboardingEntitiesListContainer: any;

  @query('#entities-container')
  _SfOnboardingEntitiesContainer: any;

  @query('#functions-container')
  _SfOnboardingFunctionsContainer: any;

  @query('#functions-list-container')
  _SfOnboardingFunctionsListContainer: any;

  @query('#countries-container')
  _SfOnboardingCountriesContainer: any;

  @query('#countries-list-container')
  _SfOnboardingCountriesListContainer: any;

  @query('#locations-list-container')
  _SfOnboardingLocationsListContainer: any;

  @query('#locations-container')
  _SfOnboardingLocationsContainer: any;

  @query('#tags-list-container')
  _SfOnboardingTagsListContainer: any;

  @query('#tags-container')
  _SfOnboardingTagsContainer: any;

  @query('#reporters-list-container')
  _SfOnboardingReportersListContainer: any;

  @query('#reporters-container')
  _SfOnboardingReportersContainer: any;

  @query('#approvers-container')
  _SfOnboardingApproversContainer: any;

  @query('#functionheads-container')
  _SfOnboardingFunctionHeadsContainer: any;

  @query('#makercheckers-container')
  _SfOnboardingMakerCheckersContainer: any;

  @query('#docs-container')
  _SfOnboardingDocsContainer: any;

  @query('#auditors-container')
  _SfOnboardingAuditorsContainer: any;

  @query('#extensions-container')
  _SfOnboardingExtensionsContainer: any;

  @query('#viewers-container')
  _SfOnboardingViewersContainer: any;

  @query('#approvers-list-container')
  _SfOnboardingApproversListContainer: any;

  @query('#makercheckers-list-container')
  _SfOnboardingMakerCheckersListContainer: any;

  @query('#docs-list-container')
  _SfOnboardingDocsListContainer: any;

  @query('#functionheads-list-container')
  _SfOnboardingFunctionHeadsListContainer: any;

  @query('#auditors-list-container')
  _SfOnboardingAuditorsListContainer: any;

  @query('#viewers-list-container')
  _SfOnboardingViewersListContainer: any;

  @query('#duedates-list-container')
  _SfOnboardingDuedatesListContainer: any;

  @query('#extensions-list-container')
  _SfOnboardingExtensionsListContainer: any;

  @query('#duedates-container')
  _SfOnboardingDuedatesContainer: any;

  @query('#alertschedules-list-container')
  _SfOnboardingAlertSchedulesListContainer: any;

  @query('#alertschedules-container')
  _SfOnboardingAlertSchedulesContainer: any;

  @query('#activations-list-container')
  _SfOnboardingActivationListContainer: any;

  @query('#activations-container')
  _SfOnboardingActivationsContainer: any;

  @query('#invalidations-list-container')
  _SfOnboardingInvalidationListContainer: any;

  @query('#invalidations-container')
  _SfOnboardingInvalidationsContainer: any;

  @query('#triggers-container')
  _SfOnboardingTriggersContainer: any;

  @query('#triggers-list-container')
  _SfOnboardingTriggersListContainer: any;

  @query('#internalcontrols-list-container')
  _SfOnboardingInternalControlsListContainer: any;

  @query('#internalcontrols-container')
  _SfOnboardingInternalControlsContainer: any;

  @query('#reportedlocations-list-container')
  _SfOnboardingReportedLocationsListContainer: any;

  @query('#reportedlocations-container')
  _SfOnboardingReportedLocationsContainer: any;

  @query('#signoff-container')
  _SfOnboardingSignoffContainer: any;

  @query('#calendar-list-container')
  _SfOnboardingCalendarListContainer: any;

  @query('#calendar-container')
  _SfOnboardingCalendarContainer: any;

  @query('#suspense-container')
  _SfOnboardingSuspenseContainer: any;

  @query('#gov-locations-container')
  _SfOnboardingGovLocationsContainer: any;

  @query('#gov-users-container')
  _SfOnboardingGovUsersContainer: any;

  @query('#onboarding-tab-group-0')
  _SfOnboardingTabGroup0: any;

  @query('#onboarding-tab-group-1')
  _SfOnboardingTabGroup1: any;

  @query('#onboarding-tab-group-2')
  _SfOnboardingTabGroup2: any;

  @query('#onboarding-tab-group-3')
  _SfOnboardingTabGroup3: any;

  @query('#onboarding-tab-group-button-0')
  _SfOnboardingTabGroupButton0: any;

  @query('#onboarding-tab-group-button-1')
  _SfOnboardingTabGroupButton1: any;

  @query('#onboarding-tab-group-button-2')
  _SfOnboardingTabGroupButton2: any;

  @query('#onboarding-tab-group-button-3')
  _SfOnboardingTabGroupButton3: any;

  @query('#onboarding-tab-group-button-4')
  _SfOnboardingTabGroupButton4: any;

  @queryAssignedElements({ slot: 'project' })
  _SfProject: any;

  @queryAssignedElements({ slot: 'uploader' })
  _SfUploader: any;

  @queryAssignedElements({ slot: 'reporting' })
  _SfReporting: any;

  isSelectedLegend = (value: number): any => {
    return this.chartSelectedLegend.includes(value);
  }
  removeFromSelectedLegend = (value: number) => {
    const index = this.chartSelectedLegend.indexOf(value);
    if (index > -1) { // only splice array when item is found
      this.chartSelectedLegend.splice(index, 1); // 2nd parameter means remove one item only
    }
  }

  clearSelectedLegend = () => {
    this.chartSelectedLegend = [];
    if (this.chart != null) {
      this.chart.data.datasets[0].data.forEach((_d: any, i: any) => {
        //console.log(d);
        this.chart.getDatasetMeta(0).data[i].hidden = false;
        this.chart.update();
      })
    }
    if (this.chart2 != null && this.chart3 != null && this.chart4 != null) {
      if (this.barCharDataSet2Arr.length > 0 && this.barCharDataSet3Arr.length > 0 && this.barCharDataSet4Arr.length > 0) {
        do {
          this.chart2.data.datasets = this.barCharDataSet2Arr.pop();
          this.chart3.data.datasets = this.barCharDataSet3Arr.pop();
          this.chart4.data.datasets = this.barCharDataSet4Arr.pop();
        } while (this.barCharDataSet2Arr.length > 0)

      } else {
        if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) {
          this.barCharDataSet2.pop();
          this.barCharDataSet3.pop();
          this.barCharDataSet4.pop();
        }
      }
    }
    this.selectedFilters = null;
  }

  clearSelectedGraphParam = () => {

    //console.log('clickonbar clearing graph param', this.chart, this.chart2, this.chart3);

    this.graphParam = "";
    if (this.chart != null) {
      this.chart.update();
    }

    if (this.chart2 != null && this.chart3 != null && this.chart4 != null) {
      if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) {
        this.chart2.data.datasets = this.barCharDataSet2.pop();
        this.chart3.data.datasets = this.barCharDataSet3.pop();
        this.chart4.data.datasets = this.barCharDataSet4.pop();
      }
    } else {
      if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) {
        this.barCharDataSet2.pop();
        this.barCharDataSet3.pop();
        this.barCharDataSet4.pop();
      }
    }
    console.log('calling processGraphFilter 1')
    this.processGraphFilter(this.graphFilter);
    this.selectedFilters = null;
  }

  getEventField = (field: string) => {

    for (var i = 0; i < this.getEventFields().length; i++) {

      if (this.getEventFields()[i].field == field) {
        return this.getEventFields()[i];
      }

    }

  }

  getParentFieldFromDepedencies = (field: string) => {

    for (var i = 0; i < this.getEventFieldDependencies().length; i++) {

      if (this.getEventFieldDependencies()[i].type == "foreignkey" && this.getEventFieldDependencies()[i].child == field) {
        return this.getEventFieldDependencies()[i].parent;
      }

    }

    return null;

  }

  getEventTexts = (field: string, selectedId: Array<string>, row: any) => {

    console.log('get event texts', field, selectedId, row);

    if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-select") {

      var selectedIds = "";
      selectedIds += '[';
      for (var i = 0; i < selectedId.length; i++) {
        selectedIds += ('&quot;' + selectedId[i] + '&quot;');
        if (i < selectedId.length - 1) {
          selectedIds += ',';
        }
      }
      selectedIds += ']';

      return '<sf-i-select apiId="' + this.getEventField(field).apiId + '" name="Select" label="Select" mode="text" selectedId="' + selectedIds + '"></sf-i-select>'

    }

    if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-sub-select") {

      const parentField = this.getParentFieldFromDepedencies(field);

      //console.log('parentfield', parentField);

      var selectedIds = "";
      selectedIds += '[';
      for (var i = 0; i < selectedId.length; i++) {
        selectedIds += ('&quot;' + selectedId[i] + '&quot;');
        if (i < selectedId.length - 1) {
          selectedIds += ',';
        }
      }
      selectedIds += ']';

      const filterId = JSON.parse(row[parentField])[0];

      //console.log('<sf-i-sub-select apiId="'+this.getEventField(field).apiId+'" name="Select" label="Select" mode="text" selectedId="'+selectedIds+'" filterId="'+filterId+'"></sf-i-sub-select>');

      return '<sf-i-sub-select apiId="' + this.getEventField(field).apiId + '" name="Select" label="Select" mode="text" selectedId="' + selectedIds + '" filterId="' + filterId + '"></sf-i-sub-select>'

    }

    if (this.getEventField(field) != null && this.getEventField(field).type == "sf-i-form") {

      //console.log('<sf-i-form name="Select" apiId="'+this.getEventField(field).apiId+'" selectedId="'+selectedId[0]+'" projectField="'+this.getEventField(field).projectField+'" mode="text"></sf-i-form>');

      return '<sf-i-form name="Select" apiId="' + this.getEventField(field).apiId + '" selectedId="' + selectedId[0] + '" projectField="' + this.getEventField(field).projectField + '" mode="text"></sf-i-form>'
    }



    return "";
  }

  clearTabs = () => {
    (this._SfCalendarContainer as HTMLDivElement).style.display = 'none';
    (this._SfStreamContainer as HTMLDivElement).style.display = 'none';
    (this._SfUpcomingContainer as HTMLDivElement).style.display = 'none';
    (this._SfThisContainer as HTMLDivElement).style.display = 'none';
    (this._SfPastContainer as HTMLDivElement).style.display = 'none';
    (this._SfCustomContainer as HTMLDivElement).style.display = 'none';
    (this._SfAdhocContainer as HTMLDivElement).style.display = 'none';
    (this._SfFindContainer as HTMLDivElement).style.display = 'none';
    (this._SfRegisterContainer as HTMLDivElement).style.display = 'none';
  }

  enableCalendar = () => {
    this.clearTabs();
    (this._SfCalendarContainer as HTMLDivElement).style.display = 'flex';
  }

  enableStream = () => {
    this.clearTabs();
    (this._SfStreamContainer as HTMLDivElement).style.display = 'flex';
  }

  enableUpcoming() {
    this.clearTabs();
    (this._SfUpcomingContainer as HTMLDivElement).style.display = 'flex';
  }

  enableThis() {
    this.clearTabs();
    (this._SfThisContainer as HTMLDivElement).style.display = 'flex';
  }

  enablePast() {
    this.clearTabs();
    (this._SfPastContainer as HTMLDivElement).style.display = 'flex';
  }

  enableCustom() {
    this.clearTabs();
    (this._SfCustomContainer as HTMLDivElement).style.display = 'flex';
  }

  enableFind() {
    this.clearTabs();
    (this._SfFindContainer as HTMLDivElement).style.display = 'flex';
  }

  enableAdhoc() {
    this.clearTabs();
    (this._SfAdhocContainer as HTMLDivElement).style.display = 'flex';
  }

  enableRegisters() {
    this.clearTabs();
    (this._SfRegisterContainer as HTMLDivElement).style.display = 'flex';
  }

  prepareXhrPresigned = async (data: any, url: string, loaderElement: any, loaderText: string = '') => {


    if (loaderElement != null) {
      loaderElement.innerHTML = '<div class="lds-dual-ring"></div>';
      loaderElement.innerHTML += ('<div class="lds-text"><div class="lds-text-c">' + loaderText + '</div></div>');
    }
    return await Util.callApiPresigned(url, data);

  }

  prepareXhrPresignedGet = async (url: string, loaderElement: any, loaderText: string = '') => {


    if (loaderElement != null) {
      loaderElement.innerHTML = '<div class="lds-dual-ring"></div>';
      loaderElement.innerHTML += ('<div class="lds-text"><div class="lds-text-c">' + loaderText + '</div></div>');
    }
    return await Util.callApiPresignedGet(url);

  }

  prepareXhrPresignedDelete = async (url: string, loaderElement: any, loaderText: string = '') => {


    if (loaderElement != null) {
      loaderElement.innerHTML = '<div class="lds-dual-ring"></div>';
      loaderElement.innerHTML += ('<div class="lds-text"><div class="lds-text-c">' + loaderText + '</div></div>');
    }
    return await Util.callApiPresignedDelete(url);

  }


  prepareXhr = async (data: any, url: string, loaderElement: any, authorization: any, loaderText: string = '') => {


    if (loaderElement != null) {
      loaderElement.innerHTML = '<div class="lds-dual-ring"></div>';
      loaderElement.innerHTML += ('<div class="lds-text"><div class="lds-text-c">' + loaderText + '</div></div>');
    }
    return await Util.callApi(url, data, authorization);

  }

  clearMessages = () => {
    this._SfRowError.style.display = 'none';
    this._SfRowErrorMessage.innerHTML = '';
    this._SfRowSuccess.style.display = 'none';
    this._SfRowSuccessMessage.innerHTML = '';
    this._SfRowSuccessMessageBtnContainer.innerHTML = '';
  }

  setError = (msg: string) => {
    this._SfRowError.style.display = 'flex';
    this._SfRowErrorMessage.innerHTML = msg;
    this._SfRowSuccess.style.display = 'none';
    this._SfRowSuccessMessage.innerHTML = '';
    this._SfRowSuccessMessageBtnContainer.innerHTML = '';
  }

  setSuccess = (msg: string) => {
    this._SfRowError.style.display = 'none';
    this._SfRowErrorMessage.innerHTML = '';
    this._SfRowSuccess.style.display = 'flex';
    this._SfRowSuccessMessage.innerHTML = msg;
    this._SfRowSuccessMessageBtnContainer.innerHTML = '';
  }

  setSuccessBtn = (msg: string, btnCaptions: string[], btnCallbacks: Function[]) => {
    this._SfRowError.style.display = 'none';
    this._SfRowErrorMessage.innerHTML = '';
    this._SfRowSuccess.style.display = 'flex';
    this._SfRowSuccessMessage.innerHTML = msg;
    let btnHtml = ''
    for (let [i, caption] of btnCaptions.entries()) {
      btnHtml += '<button part="successmsgbtn" id="successbtn-' + i + '" class="d-flex align-center mt-10' + ((i > 0) ? ' ml-10' : '') + '">' + caption + '</button>'
    }
    this._SfRowSuccessMessageBtnContainer.innerHTML = btnHtml
    for (let [i, callback] of btnCallbacks.entries()) {
      let btn = this._SfRowSuccessMessageBtnContainer.querySelector('#successbtn-' + i) as HTMLButtonElement
      btn.addEventListener('click', () => { callback() })
    }
  }

  getLastDayOfLastMonth = (month: number, year: number) => {
    const date = new Date(year, month, 0);
    return date.getDate()
  }

  getLastDayOfMonth = (month: number, year: number): number => {
    const date = new Date(year, month + 1, 0);
    return date.getDate()
  }

  getFirstDateOfLastWeek = (startDate: Date): Date => {

    const sd = new Date(startDate.getTime());
    var first = sd.getDate() - sd.getDay();
    var firstday = new Date(sd.setDate(first));
    for (var i = 0; i < 7; i++) {
      firstday.setDate(firstday.getDate() - 1);
    }
    return firstday;

  }

  getFirstDayOfLastMonth(yourDate: Date) {
    var d = new Date(yourDate);
    d.setDate(1);
    d.setMonth(d.getMonth() - 1);
    return d;
  }

  getFirstDateOfWeek = (startDate: Date): Date => {

    const sd = new Date(startDate.getTime());
    var first = sd.getDate() - sd.getDay();
    var firstday = new Date(sd.setDate(first));
    return firstday;

  }

  getBlanks = (month: number, year: number) => {

    const date = new Date(("0" + (month + 1)).slice(-2) + '/01/' + year);
    const day = date.getDay();
    return day;

  }

  getMonthStatus = (month: number, year: number) => {

    //html += '<div class="d-flex align-baseline flex-grow flex-wrap">';

    // const currMonth = new Date().getMonth();
    // const currDate = new Date().getDate();

    //console.log('currmonth', currMonth, 'currdate', currDate);

    var approved = 0;
    var pendingApproval = 0;
    var rejected = 0;
    var notStarted = 0;
    var total = 0;

    for (var i = 0; i < this.getLastDayOfMonth(month, year); i++) {

      const mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2);

      if (month === 1 && i === (this.getLastDayOfMonth(month, year) - 1)) {
        //console.log('getLastDayOfMonth', month, this.getLastDayOfMonth(month, year), mmdd);
      }

      if (this.events[mmdd] != null) {

        for (var j = 0; j < this.events[mmdd].length; j++) {

          total++;

          const partStatus = this.getCompletenessStatus(this.events[mmdd][j]);

          if (partStatus == "approved") {
            approved++
          }
          if (partStatus == "not-started") {
            notStarted++
          }
          if (partStatus == "pending-approval") {
            pendingApproval++
          }
          if (partStatus == "rejected") {
            rejected++
          }

        }

      }
    }

    //console.log('month-status', approved, pendingApproval, rejected, notStarted, total);

    var percApproved = (approved * 100) / total;
    var percPendingApproval = (pendingApproval * 100) / total;
    var percRejected = (rejected * 100) / total;
    var percNotStarted = (notStarted * 100) / total;

    return { percNotStarted: percNotStarted, percPendingApproval: percPendingApproval, percApproved: percApproved, percRejected: percRejected };

  }

  insertDates = (month: number, year: number) => {

    var html = "";

    html += '<div part="bg-calendar" class="d-flex align-baseline flex-grow flex-wrap p-10">';

    const dateNumber = this.getLastDayOfLastMonth(month, year);

    for (var i = 0; i < this.getBlanks(month, year); i++) {

      html += '<div class="day-item date-item-before fw-100">';
      html += dateNumber - (this.getBlanks(month, year) - i - 1);
      html += '</div>';

    }

    const currMonth = new Date().getMonth();
    const currDate = new Date().getDate();

    //console.log('currmonth', currMonth, 'currdate', currDate);

    for (i = 0; i < this.getLastDayOfMonth(month, year); i++) {

      const mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2);

      var partName = "";

      if (this.events[mmdd] != null) {
        partName = "event-calendar-day-with-event";
        html += '<div part="' + partName + '" class="day-item date-item fw-600">';

        if (month === currMonth && (i + 1) === currDate) {

          html += '<div part="event-calendar-day-today">'
          html += (i + 1);
          html += '</div>'

        } else {

          html += '<div>'
          html += (i + 1);
          html += '</div>'

        }

        var approved = 0;
        var pendingApproval = 0;
        var rejected = 0;
        var notStarted = 0;
        var total = 0;

        for (var j = 0; j < this.events[mmdd].length; j++) {
          total++;

          const partStatus = this.getCompletenessStatus(this.events[mmdd][j]);

          if (partStatus == "approved") {
            approved++;
          }

          if (partStatus == "pending-approval") {
            pendingApproval++;
          }

          if (partStatus == "rejected") {
            rejected++;
          }

          if (partStatus == "not-started") {
            notStarted++;
          }

        }

        var percApproved = (approved * 100) / total;
        var percPendingApproval = (pendingApproval * 100) / total;
        var percNotStarted = (notStarted * 100) / total;
        var percRejected = (rejected * 100) / total;

        //console.log('percentages', mmdd, percApproved, percPendingApproval, percRejected, percNotStarted)

        html += '<div class="d-flex justify-center">'
        //html += '<div part="event-date-indicator-primary" class="dot"></div>'
        html += '<div class="dot" style="width: ' + (percApproved / 2) + '%; background-color: ' + this.COLOR_APPROVED + '"></div>'
        html += '<div class="dot" style="width: ' + (percPendingApproval / 2) + '%; background-color: ' + this.COLOR_PENDING_APPROVAL + '"></div>'
        html += '<div class="dot" style="width: ' + (percRejected / 2) + '%; background-color: ' + this.COLOR_REJECTED + '"></div>'
        html += '<div class="dot" style="width: ' + (percNotStarted / 2) + '%; background-color: ' + this.COLOR_NOT_STARTED + '"></div>'
        html += '</div>'
        html += '</div>';
      } else {
        partName = "event-calendar-day-without-event";
        html += '<div part="' + partName + '" class="day-item date-item fw-100">';
        // html += '<div>'
        //   html += (i + 1);
        // html += '</div>'
        if (month === currMonth && (i + 1) === currDate) {

          html += '<div part="event-calendar-day-today">'
          html += (i + 1);
          html += '</div>'

        } else {

          html += '<div>'
          html += (i + 1);
          html += '</div>'

        }
        html += '</div>';
      }

    }

    for (i = 0; i < 42 - (this.getBlanks(month, year) + this.getLastDayOfMonth(month, year)); i++) {
      html += '<div class="day-item date-item-before fw-100">';
      html += (i + 1);
      html += '</div>';
    }

    html += '</div>';

    return html;

  }

  insertDayNames = () => {

    var html = "";

    html += '<div part="bg-calendar" class="d-flex align-center flex-grow p-10">';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'S';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'M';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'T';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'W';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'T';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'F';
    html += '</div>';

    html += '<div part="calendar-day-name" class="day-item fw-100">';
    html += 'S';
    html += '</div>';

    html += '</div>';

    return html;

  }

  // getYearFromMonthAndCalendarStart = (mm: string) => {

  //   var yyyy = "";

  //   var currMonth = new Date().getMonth() + 1;
  //   console.log('CurrentMonth', currMonth, "MM", mm);
  //   if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
  //     //console.log('getpastduedate returning', 0);
  //     yyyy = parseInt(this.calendarStartYYYY) + "";
  //   } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
  //     //console.log('getpastduedate returning', 1);
  //     yyyy = (parseInt(this.calendarStartYYYY) - 1) + "";
  //   } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
  //     //console.log('getpastduedate returning', 2);
  //     yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
  //   } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
  //     //console.log('getpastduedate returning', 3);
  //     yyyy = (parseInt(this.calendarStartYYYY)) + "";
  //   }

  //   return yyyy;

  // }
  getYearFromMonthAndCalendarStart = (mm: string) => {

    var yyyy = "";
    if (parseInt(mm) < parseInt(this.calendarStartMM)) {
      yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    } else {
      yyyy = parseInt(this.calendarStartYYYY) + "";
    }

    return yyyy;

  }

  getAboutToExpire = (event: any) => {

    // console.log('about to expire', mmdd, event.duedate)

    let dateArr = event.duedate.split('/')
    const dd = dateArr[0];
    const mm = dateArr[1];

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    var date = new Date();
    date.setMonth(parseInt(mm) - 1);
    date.setDate(parseInt(dd));
    date.setFullYear(parseInt(yyyy));
    const tsDoc = date.getTime();

    const tsCurr = new Date().getTime();

    // console.log('about to expire', mmdd, date, tsDoc, tsCurr)

    if ((tsDoc - tsCurr) < (30 * 24 * 60 * 60 * 1000)) { // less than 60 days
      //console.log('late executed', true)
      return true;
    }
    // console.log('about to expire', tsDoc - tsCurr, (30 * 24 * 60 * 60 * 1000), event.duedate)
    return false;

  }

  getPastDueDate = (mmdd: string) => {

    const dd = mmdd.substring(3, 5);
    const mm = mmdd.substring(0, 2);

    //console.log('getpastduedate', mmdd, dd, mm);

    // var yyyy = "";

    // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    //   //console.log('getpastduedate returning', 0);
    //   yyyy = parseInt(this.calendarStartYYYY) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    //   //console.log('getpastduedate returning', 1);
    //   yyyy = (parseInt(this.calendarStartYYYY) - 1) + "";
    // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   //console.log('getpastduedate returning', 2);
    //   yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   //console.log('getpastduedate returning', 3);
    //   yyyy = (parseInt(this.calendarStartYYYY)) + "";
    // }

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    var date = new Date();
    date.setMonth(parseInt(mm) - 1);
    date.setDate(parseInt(dd));
    date.setFullYear(parseInt(yyyy));

    var currDate = new Date();

    if (currDate.getTime() > date.getTime()) {

      //console.log('getpastduedate returning true', yyyy);
      return true;
    }

    return false;

  }

  getLateExecuted = (mmdd: string, event: any) => {

    //console.log('late executed', mmdd, event.dateofcompletion)

    const tsDoc = new Date(parseInt(event.dateofcompletion)).getTime();

    const dd = mmdd.substring(3, 5);
    const mm = mmdd.substring(0, 2);

    // var yyyy = "";

    // var currMonth = new Date().getMonth() + 1;

    // // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    // //   yyyy = new Date().getFullYear() + "";
    // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() - 1) + "";
    // // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() + 1) + "";
    // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() + 1) + "";
    // // }

    // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    //   yyyy = parseInt(this.calendarStartYYYY) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) - 1) + "";
    // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    // }

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    var date = new Date();
    date.setMonth(parseInt(mm) - 1);
    date.setDate(parseInt(dd));
    date.setFullYear(parseInt(yyyy));

    const tsCurr = date.getTime();

    //console.log('late executed', mmdd, tsDoc, tsCurr)

    if (tsDoc > tsCurr) {
      //console.log('late executed', true)
      return true;
    }

    return false;

  }

  getLateReported = (mmdd: string, event: any) => {

    const dd = mmdd.substring(3, 5);
    const mm = mmdd.substring(0, 2);

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    var date = new Date();
    date.setMonth(parseInt(mm) - 1);
    date.setDate(parseInt(dd));
    date.setFullYear(parseInt(yyyy));

    const tsCurr = date.getTime();

    for (var i = event.comments.length - 1; i >= 0; i--) {
      const comment = event.comments[i];
      const tsComment = new Date(comment.timestamp);
      const authorComment = comment.author;
      if (authorComment == "Reporter" && tsComment.getTime() > tsCurr) {
        return true;
      }
    }

    return false;

  }

  getLateApproved = (mmdd: string, event: any) => {

    const dd = mmdd.substring(3, 5);
    const mm = mmdd.substring(0, 2);

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    var date = new Date();
    date.setMonth(parseInt(mm) - 1);
    date.setDate(parseInt(dd));
    date.setFullYear(parseInt(yyyy));

    const tsCurr = date.getTime();

    for (var i = event.comments.length - 1; i >= 0; i--) {
      const comment = event.comments[i];
      const tsComment = new Date(comment.timestamp);
      const authorComment = comment.author;
      if (authorComment == "Approver" && tsComment.getTime() > tsCurr) {
        return true;
      }
    }

    return false;

    // //console.log('get late approved', event.obligationtitle, event.lastupdated, mmdd, event.lastupdated);

    // const tsLastUpdated = new Date((event.lastupdated)).getTime();

    // //console.log('get late approved', tsLastUpdated);

    // const dd = mmdd.substring(3, 5);
    // const mm = mmdd.substring(0, 2);

    // var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    // var date = new Date();
    // date.setMonth(parseInt(mm) - 1);
    // date.setDate(parseInt(dd));
    // date.setFullYear(parseInt(yyyy));

    // const tsCurr = date.getTime();

    // //console.log('get late approved', tsCurr);

    // if(tsLastUpdated > tsCurr) {
    //   //console.log('late approved', true)
    //   return true;
    // }

    // return false;

  }

  updateGraphStats = (arr: Array<string>, arrData: any, arrPartData: any, arrLateData: any, arrComplianceData: any, partStatus: string, lateStatus: string, complianceStatus: string) => {

    for (var i = 0; i < arr.length; i++) {
      if (arrData == null) {
        arrData = {};
      }
      const name = arr[i].split(';')[0].trim().replace(/ *\([^)]*\) */g, "")
      if (arrData[name] == null) {
        arrData[name] = 1;
      } else {
        arrData[name]++;
      }
      // if(name.toLowerCase().indexOf('na - corp sec') >= 0) {
      //   console.log('arrData[corpsec]', name, arrData[name]);
      // }
    }

    for (var i = 0; i < arr.length; i++) {

      if (arrLateData == null) {
        arrLateData = {};
      }

      if (arrPartData == null) {
        arrPartData = {};
      }

      if (arrComplianceData == null) {
        arrComplianceData = {};
      }

      const name = arr[i].split(';')[0].trim().replace(/ *\([^)]*\) */g, "")

      if (arrLateData[name] == null) {
        arrLateData[name] = {};
      }

      if (arrPartData[name] == null) {
        arrPartData[name] = {};
      }

      if (arrComplianceData[name] == null) {
        arrComplianceData[name] = {};
      }

      if (arrPartData[name]["not-started"] == null) {
        arrPartData[name]["not-started"] = 0;
      }
      if (arrPartData[name]["pending-approval"] == null) {
        arrPartData[name]["pending-approval"] = 0;
      }
      if (arrPartData[name]["rejected"] == null) {
        arrPartData[name]["rejected"] = 0;
      }
      if (arrPartData[name]["approved"] == null) {
        arrPartData[name]["approved"] = 0;
      }

      arrPartData[name][partStatus]++;

      if (arrLateData[name]["late-executed"] == null) {
        arrLateData[name]["late-executed"] = 0;
      }
      if (arrLateData[name]["late-reported"] == null) {
        arrLateData[name]["late-reported"] = 0;
      }
      if (arrLateData[name]["late-approved"] == null) {
        arrLateData[name]["late-approved"] = 0;
      }
      if (arrLateData[name]["past-due-date"] == null) {
        arrLateData[name]["past-due-date"] = 0;
      }
      if (arrLateData[name]["in-time"] == null) {
        arrLateData[name]["in-time"] = 0;
      }

      arrLateData[name][lateStatus]++;

      if (arrComplianceData[name]["scheduled"] == null) {
        arrComplianceData[name]["scheduled"] = 0;
      }
      if (arrComplianceData[name]["not-complied"] == null) {
        arrComplianceData[name]["not-complied"] = 0;
      }
      if (arrComplianceData[name]["partially-complied"] == null) {
        arrComplianceData[name]["partially-complied"] = 0;
      }
      if (arrComplianceData[name]["complied"] == null) {
        arrComplianceData[name]["complied"] = 0;
      }
      if (arrComplianceData[name]["complied-with-gaps"] == null) {
        arrComplianceData[name]["complied-with-gaps"] = 0;
      }
      if (arrComplianceData[name]["reported-non-compliance"] == null) {
        arrComplianceData[name]["reported-non-compliance"] = 0;
      }

      arrComplianceData[name][complianceStatus]++;

    }

    return { arrData: arrData, arrPartData: arrPartData, arrLateData: arrLateData, arrComplianceData: arrComplianceData }
  }

  updateJurisdictionStats = (jurisdictions: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(jurisdictions, this.jurisdictionData, this.jurisdictionPartStatusData, this.jurisdictionLateStatusData, this.jurisdictionComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.jurisdictionData = result.arrData;
    this.jurisdictionLateStatusData = result.arrLateData;
    this.jurisdictionPartStatusData = result.arrPartData;
    this.jurisdictionComplianceStatusData = result.arrComplianceData;

  }

  updateSubcategoryStats = (subcategories: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(subcategories, this.subcategoryData, this.subcategoryPartStatusData, this.subcategoryLateStatusData, this.subcategoryComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.subcategoryData = result.arrData;
    this.subcategoryLateStatusData = result.arrLateData;
    this.subcategoryPartStatusData = result.arrPartData;
    this.subcategoryComplianceStatusData = result.arrComplianceData;

  }

  updateFrequencyStats = (frequencies: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(frequencies, this.frequencyData, this.frequencyPartStatusData, this.frequencyLateStatusData, this.frequencyComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.frequencyData = result.arrData;
    this.frequencyLateStatusData = result.arrLateData;
    this.frequencyPartStatusData = result.arrPartData;
    this.frequencyComplianceStatusData = result.arrComplianceData;

  }

  updateLocationStats = (location: string, partStatus: string, lateStatus: string, complianceStatus: string) => {

    //console.log('location', location);

    if (this.locationData == null) {
      this.locationData = {};
    }

    const locationName = location.replace(/ *\([^)]*\) */g, "")

    if (this.locationData[locationName] == null) {
      this.locationData[locationName] = 1;
    } else {
      this.locationData[locationName]++;
    }

    if (this.locationLateStatusData == null) {
      this.locationLateStatusData = {};
    }

    if (this.locationPartStatusData == null) {
      this.locationPartStatusData = {};
    }

    if (this.locationComplianceStatusData == null) {
      this.locationComplianceStatusData = {};
    }

    if (this.locationLateStatusData[locationName] == null) {
      this.locationLateStatusData[locationName] = {};
    }

    if (this.locationPartStatusData[locationName] == null) {
      this.locationPartStatusData[locationName] = {};
    }

    if (this.locationComplianceStatusData[locationName] == null) {
      this.locationComplianceStatusData[locationName] = {};
    }

    if (this.locationPartStatusData[locationName]["not-started"] == null) {
      this.locationPartStatusData[locationName]["not-started"] = 0;
    }
    if (this.locationPartStatusData[locationName]["pending-approval"] == null) {
      this.locationPartStatusData[locationName]["pending-approval"] = 0;
    }
    if (this.locationPartStatusData[locationName]["rejected"] == null) {
      this.locationPartStatusData[locationName]["rejected"] = 0;
    }
    if (this.locationPartStatusData[locationName]["approved"] == null) {
      this.locationPartStatusData[locationName]["approved"] = 0;
    }

    this.locationPartStatusData[locationName][partStatus]++;

    if (this.locationLateStatusData[locationName]["late-reported"] == null) {
      this.locationLateStatusData[locationName]["late-reported"] = 0;
    }
    if (this.locationLateStatusData[locationName]["late-executed"] == null) {
      this.locationLateStatusData[locationName]["late-executed"] = 0;
    }
    if (this.locationLateStatusData[locationName]["late-approved"] == null) {
      this.locationLateStatusData[locationName]["late-approved"] = 0;
    }
    if (this.locationLateStatusData[locationName]["past-due-date"] == null) {
      this.locationLateStatusData[locationName]["past-due-date"] = 0;
    }
    if (this.locationLateStatusData[locationName]["in-time"] == null) {
      this.locationLateStatusData[locationName]["in-time"] = 0;
    }

    this.locationLateStatusData[locationName][lateStatus]++;

    if (this.locationComplianceStatusData[locationName]["not-complied"] == null) {
      this.locationComplianceStatusData[locationName]["not-complied"] = 0;
    }
    if (this.locationComplianceStatusData[locationName]["complied"] == null) {
      this.locationComplianceStatusData[locationName]["complied"] = 0;
    }
    if (this.locationComplianceStatusData[locationName]["partially-complied"] == null) {
      this.locationComplianceStatusData[locationName]["partially-complied"] = 0;
    }
    if (this.locationComplianceStatusData[locationName]["scheduled"] == null) {
      this.locationComplianceStatusData[locationName]["scheduled"] = 0;
    }

    this.locationComplianceStatusData[locationName][complianceStatus]++;

  }

  updateFunctionStats = (functions: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(functions, this.functionData, this.functionPartStatusData, this.functionLateStatusData, this.functionComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.functionData = result.arrData;
    this.functionLateStatusData = result.arrLateData;
    this.functionPartStatusData = result.arrPartData;
    this.functionComplianceStatusData = result.arrComplianceData;

  }

  updateReporterStats = (reporters: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(reporters, this.reporterData, this.reporterPartStatusData, this.reporterLateStatusData, this.reporterComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.reporterData = result.arrData;
    this.reporterLateStatusData = result.arrLateData;
    this.reporterPartStatusData = result.arrPartData;
    this.reporterComplianceStatusData = result.arrComplianceData;

  }

  updateRiskAreaStats = (riskAreas: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {


    const result = this.updateGraphStats(riskAreas, this.riskAreasData, this.riskAreasPartStatusData, this.riskAreasLateStatusData, this.riskAreasComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.riskAreasData = result.arrData;
    this.riskAreasLateStatusData = result.arrLateData;
    this.riskAreasPartStatusData = result.arrPartData;
    this.riskAreasComplianceStatusData = result.arrComplianceData;

  }

  updateRiskSeverityStats = (riskSeverities: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    // console.log('updateRiskSeverityStats', riskSeverities, complianceStatus)

    const result = this.updateGraphStats(riskSeverities, this.riskSeverityData, this.riskSeverityPartStatusData, this.riskSeverityLateStatusData, this.riskSeverityComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.riskSeverityData = result.arrData;
    this.riskSeverityLateStatusData = result.arrLateData;
    this.riskSeverityPartStatusData = result.arrPartData;
    this.riskSeverityComplianceStatusData = result.arrComplianceData;

    //console.log('updateRiskSeverityStats', JSON.stringify(result.arrComplianceData))

  }

  updateObligationTypeStats = (obligationTypes: Array<string>, partStatus: string, lateStatus: string, complianceStatus: string) => {

    const result = this.updateGraphStats(obligationTypes, this.obligationTypeData, this.obligationTypePartStatusData, this.obligationTypeLateStatusData, this.obligationTypeComplianceStatusData, partStatus, lateStatus, complianceStatus);
    this.obligationTypeData = result.arrData;
    this.obligationTypeLateStatusData = result.arrLateData;
    this.obligationTypePartStatusData = result.arrPartData;
    this.obligationTypeComplianceStatusData = result.arrComplianceData;

    //console.log('Updating obligationtype stats', this.obligationTypeLateStatusData);
  }

  getReporterStringFromEvent = (event: any) => {
    let reporterStr = '';
    for (var k = 0; k < event.reporters.length; k++) {
      reporterStr += '<div part="badge-reporter-name" class="graphparamname graphparamname2 mb-20 ml-10">' + (event.reporters[k].split(';')[0]) + '</div>';
    }
    return reporterStr;
  }

  getReporterDetailStringFromEvent = (event: any) => {
    let reporterStr = '';
    for (var k = 0; k < event.reporters.length; k++) {
      reporterStr += '<div part="detail-reporter-name" class="graphparamname mb-20 mr-10">' + (event.reporters[k].split(';')[0]) + '</div>';
    }
    return reporterStr;
  }

  getApproverStringFromEvent = (event: any) => {
    let approverStr = '';
    for (var k = 0; k < event.approvers.length; k++) {
      approverStr += '<div part="badge-approver-name" class="graphparamname graphparamname3 mb-20 ml-10">' + (event.approvers[k].split(';')[0]) + '</div>';
    }
    return approverStr;
  }

  getApproverDetailStringFromEvent = (event: any) => {
    let approverStr = '';
    for (var k = 0; k < event.approvers.length; k++) {
      approverStr += '<div part="detail-approver-name" class="graphparamname mb-20 mr-10">' + (event.approvers[k].split(';')[0]) + '</div>';
    }
    return approverStr;
  }

  renderLatestCompliance = (mmddyyyy: string, event: any) => {

    var lastMax = 0;
    for (var k = 0; k < event.compliances.length; k++) {

      const tsOfEvent = new Date(mmddyyyy).getTime();
      const tsOfCompliance = parseInt(event.compliances[k].complianceid.S);
      if (tsOfCompliance > lastMax && tsOfCompliance <= tsOfEvent) {

        event['specificity'] = JSON.parse(event.compliances[k].data.S)['specificity'];
        event['reference'] = JSON.parse(event.compliances[k].data.S)['reference'];
        event['obligation'] = JSON.parse(event.compliances[k].data.S)['obligation'];
        event['penalty'] = JSON.parse(event.compliances[k].data.S)['penalty'];
        event['authority'] = JSON.parse(event.compliances[k].data.S)['authority'];
        event['frequency'] = JSON.parse(event.compliances[k].data.S)['frequency'];
        event['obligationtype'] = JSON.parse(event.compliances[k].data.S)['obligationtype'];
        event['duedate'] = JSON.parse(event.compliances[k].data.S)['duedate'];
        event['applicability'] = JSON.parse(event.compliances[k].data.S)['applicability'];
        event['form'] = JSON.parse(event.compliances[k].data.S)['form'];
        event['internalcontrols'] = JSON.parse(event.compliances[k].data.S)['internalcontrols'];
        event['firstlineofdefence'] = JSON.parse(event.compliances[k].data.S)['firstlineofdefence'];
        event['risk'] = JSON.parse(event.compliances[k].data.S)['risk'];
        event['riskarea'] = JSON.parse(event.compliances[k].data.S)['riskarea'];

      }

    }
    return event;
  }

  getCompletenessStatus = (event: any) => {

    if (event.comments == null || event.comments.length === 0) {
      return "not-started";
    } else {
      if (event.approved != null && event.approved) {
        return "approved";
      } else {

        if (event.comments[event.comments.length - 1].author == "Reporter") {
          return "pending-approval";
        } else {
          return "rejected";
        }

      }
    }
  }

  getTimelinessStatus = (mmdd: string, event: any, completeness: string) => {
    // if(event.module == "contract"){
    //   if (completeness == "not-started") {
    //     if (this.getPastDueDate(mmdd)) {
    //       return "past-due-date";
    //     } else {
    //       return "in-time"
    //     }
    //   } else if (completeness == "pending-approval" || completeness == "rejected") {

    //   }
    // }
    if (completeness == "not-started") {

      if (this.getPastDueDate(mmdd)) {
        return "past-due-date";
      } else {
        return "in-time"
      }

    } else if (completeness == "pending-approval" || completeness == "rejected") {

      if (this.getLateExecuted(mmdd, event)) {
        return "late-executed";
      } else if (this.getLateReported(mmdd, event)) {
        return "late-reported";
      } else if (this.getPastDueDate(mmdd)) {
        return "past-due-date";
      } else {
        return "in-time";
      }

    } else {

      if (this.getLateExecuted(mmdd, event)) {
        return "late-executed";
      } else if (this.getLateReported(mmdd, event)) {
        return "late-reported";
      } else if (this.getLateApproved(mmdd, event)) {
        return "late-approved";
      } else {
        return "in-time";
      }

    }

  }

  getComplianceStatus = (completeness: string, timeliness: string, percentage?: string, event: any = {}) => {
    if (event.module == "contract") {
      console.log('compliance status', event.terminated, completeness, timeliness)
      if (event.terminated) {
        return "terminated"
      }
      if (completeness == "not-started") {

        if (timeliness == "in-time") {
          if (this.getAboutToExpire(event)) {
            console.log('returning aboutt to expire')
            return "about-to-expire";
          } else {
            return "active";
          }
        } else {
          return "expired";
        }

      } else if (completeness == "pending-approval") {

        if (timeliness == "in-time") {
          if (this.getAboutToExpire(event)) {
            return "about-to-expire";
          } else {
            return "active";
          }
        } else {
          return "expired";
        }

      } else if (completeness == "rejected") {

        if (timeliness == "in-time") {
          if (this.getAboutToExpire(event)) {
            return "about-to-expire";
          } else {
            return "active";
          }
        } else {
          return "expired";
        }

      } else {

        if (timeliness == "in-time" || timeliness == "late-reported" || timeliness == "late-approved") {
          return "complied";
        } else {
          return "expired";
        }
      }
    }
    if (completeness == "not-started") {

      if (timeliness == "in-time") {
        return "scheduled";
      } else {
        return "not-complied";
      }

    } else if (completeness == "pending-approval") {

      if (timeliness == "in-time") {
        return "scheduled";
      } else if (timeliness == "past-due-date" || timeliness == "late-executed") {
        return "not-complied";
      } else {
        return "partially-complied";
      }

    } else if (completeness == "rejected") {

      if (timeliness == "in-time") {
        return "scheduled";
      } else {
        return "not-complied";
      }

    } else {

      if (timeliness == "in-time" || timeliness == "late-reported" || timeliness == "late-approved") {
        if (percentage != null && parseInt(percentage) == 0) {
          console.log('reported non compliance')
          return "reported-non-compliance"
        } else if (percentage != null && parseInt(percentage) < 100) {
          return "complied-with-gaps"
        } else {
          return "complied";
        }
      } else {
        return "not-complied";
      }

    }

  }

  numcalled: number = 0;

  updateStats = (event: any, partStatus: string, lateStatus: string, complianceStatus: string) => {
    if (event['riskarea'] != null) {
      this.updateRiskAreaStats(event['riskarea'], partStatus, lateStatus, complianceStatus);
    }
    if (event['risk'] != null) {
      this.updateRiskSeverityStats(event['risk'], partStatus, lateStatus, complianceStatus);
    }
    if (event['functions'] != null) {
      this.updateFunctionStats(event['functions'], partStatus, lateStatus, complianceStatus)
    }
    if (event['obligationtype'] != null) {
      this.updateObligationTypeStats(event['obligationtype'], partStatus, lateStatus, complianceStatus)
    }
    if (event['jurisdiction'] != null) {
      this.updateJurisdictionStats(event['jurisdiction'], partStatus, lateStatus, complianceStatus)
    }
    if (event['frequency'] != null) {
      this.updateFrequencyStats(event['frequency'], partStatus, lateStatus, complianceStatus)
    }
    //console.log('updateLocationStats', event['locationname'], event.duedate, event.id);
    if (event['locationname'] != null) {
      this.updateLocationStats(event['locationname'], partStatus, lateStatus, complianceStatus)
    }
    if (event['subcategory'] != null) {
      this.updateSubcategoryStats(event['subcategory'], partStatus, lateStatus, complianceStatus)
    }

  }

  renderCalendarGraphs = (showGraph: boolean, parametersTitle: string, showBackgroundButton: boolean) => {

    //console.log('flowGraph', this.flowGraph);

    var html = '';

    html += '<div class="mb-20 stream-event-list" part="stream-event-list-charts">';
    html += '<div class="align-center d-flex flex-wrap align-start justify-between mb-10 w-100-m-0" part="duration-title-container"><h4 part="duration-title" class="m-0">' + parametersTitle + '</h4>'
    if (this.getFeatures().length > 1) {
      html += '<div class="filter-button-container"><button part="button-icon" id="filter-button" class="material-symbols-outlined">category</button>'
      html += '<div id="filter-list-container" class="filter-list-container hide flex-col justify-between align-start p-10" part="filter-list-container" anchor="filter-button">'
      html += '<div id="filter-label-container" class="filter-label-container d-flex justify-between align-center" part="filter-label-container"><label class="filter-label"  part="filter-label">Filters</label><button id="button-submit-features" part="button-icon-small" class="material-icons invisible">check</button></div>'
      // html += `<div class="filter-input-container d-flex"><input class="input-select-feature-all" type="checkbox" ${this.selectedFeatures.length >= (this.getFeatures().length) ? 'checked' : ''} id="input-select-feature-all"  part="input-select-feature" name="all"></input><label for="input-select-feature-all" class="input-select-feature-label-all" id="input-select-feature-label-all"
      //  part="input-select-feature-label">all</label></div>`
      // html += `<div class="filter-input-container d-flex"><input class="input-select-feature-compliances" type="checkbox" ${this.selectedFeatures.indexOf('compliances') >= 0 ? 'checked' : ''} id="input-select-feature-compliances"  part="input-select-feature" name="compliances"></input><label for="input-select-feature-compliances" class="input-select-feature-label"  part="input-select-feature-label">compliances</label></div>`
      for (let [index, feature] of this.getFeatures().entries()) {
        console.log('rendering features', feature, this.selectedFeatures);
        html += `<div class="filter-input-container d-flex"><input class="input-select-feature" type="radio" ${this.selectedFeatures.indexOf(feature) >= 0 ? 'checked' : ''} id="input-select-feature-${index}" name="features" part="input-select-feature" value="${feature}"></input><label for="input-select-feature-${index}" id="input-select-feature-label-${index}" class="input-select-feature-label"  part="input-select-feature-label">${feature}</label></div>`
      }
      html += '</div></div>'
    }
    html += '<button id="button-refresh" part="button-duration-title" class="align-center d-flex justify-center"><h4 part="duration-title">' + parametersTitle + '</h4><span part="duration-title-icon" class="material-icons ml-10">refresh</span></div>';
    if (showBackgroundButton) {
      html += '<div class="align-center d-flex flex-wrap align-center mb-10 w-100-m-0" part="last-update-title-container" id="button-background-process"><h6 part="last-update-title" class="align-start d-flex"><div class="lds-dual-ring1"></div>&nbsp;&nbsp;&nbsp;&nbsp;Synchronizing in the background</h6></div>'
    } else {
      html += '<div class="align-center d-flex flex-wrap align-center mb-10 w-100-m-0" part="last-update-title-container"><h6 part="last-update-title" class="align-center d-flex"><span class="material-symbols-outlined">update</span>&nbsp;&nbsp;Last Updated on ' + this.lastupdated + '</h6></div>';
    }
    // html += '<div class="align-center d-flex flex-wrap align-center mb-10 w-100-m-0" part="show-reported-locations-container"><input class="mr-10" type="checkbox" part="input" id="input-show-reported-locations" ' + (this.showReportedLocations ? 'checked' : '' ) +'/><span part="show-reported-locations-title">Show reporting daviations</span></div>';
    if (showGraph) {
      html += '<div part="stream-event-chart-selection" class="mb-20">';
      html += '<div part="td-head" class="mb-5">Select Chart</div>';
      html += '<div class="mb-10 d-flex flex-wrap align-center">';
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("completeness") >= 0) {
        html += '<div part="chart-radio-item"><input type="radio" id="radio-completeness" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_COMPLETENESS) ? 'checked' : '') + '>';
        html += '<label for="radio-completeness" part="input-label" class="mr-10">Completeness</label></div>';
      }

      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("timeliness") >= 0) {
        html += '<div part="chart-radio-item"><input type="radio" id="radio-timeliness" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_TIMELINESS) ? 'checked' : '') + '>';
        html += '<label for="radio-timeliness" part="input-label" class="mr-10">Timeliness</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("compliance") >= 0) {
        html += '<div part="chart-radio-item"><input type="radio" id="radio-compliance" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) ? 'checked' : '') + '>';
        html += '<label for="radio-compliance" part="input-label" class="mr-10">Compliance</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("riskArea") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_RISKAREAS ? '' : 'hide') + '"><input type="radio" id="radio-risk" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_RISKAREAS) ? 'checked' : '') + '>';
        html += '<label for="radio-risk" part="input-label" class="mr-10">Risk Areas</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("riskSeverity") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_RISKSEVERITY ? '' : 'hide') + '"><input type="radio" id="radio-riskseverity" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_RISKSEVERITY) ? 'checked' : '') + '>';
        html += '<label for="radio-riskseverity" part="input-label" class="mr-10">Risk Severity</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("location") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_LOCATION ? '' : 'hide') + '"><input type="radio" id="radio-location" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_LOCATION) ? 'checked' : '') + '>';
        html += '<label for="radio-location" part="input-label" class="mr-10">Location</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("function") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_FUNCTION ? '' : 'hide') + '"><input type="radio" id="radio-function" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_FUNCTION) ? 'checked' : '') + '>';
        html += '<label for="radio-function" part="input-label" class="mr-10">Function</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("obligationType") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_OBLIGATIONTYPE ? '' : 'hide') + '"><input type="radio" id="radio-obligationtype" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_OBLIGATIONTYPE) ? 'checked' : '') + '>';
        html += '<label for="radio-obligationtype" part="input-label" class="mr-10">Obligation Type</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("jurisdiction") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_JURISDICTION ? '' : 'hide') + '"><input type="radio" id="radio-jurisdiction" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_JURISDICTION) ? 'checked' : '') + '>';
        html += '<label for="radio-jurisdiction" part="input-label" class="mr-10">Jurisdiction</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("frequency") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_FREQUENCY ? '' : 'hide') + '"><input type="radio" id="radio-frequency" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_FREQUENCY) ? 'checked' : '') + '>';
        html += '<label for="radio-frequency" part="input-label" class="mr-10">Frequency</label></div>';
      }
      if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].indexOf("subCategory") >= 0) {
        html += '<div part="chart-radio-item" class="chart-radio-item-secondary ' + (this.flowGraph == this.FLOW_GRAPH_SUBCATEGORY ? '' : 'hide') + '"><input type="radio" id="radio-subcategory" name="graph-type" part="radio-graph" ' + ((this.flowGraph == this.FLOW_GRAPH_SUBCATEGORY) ? 'checked' : '') + '>';
        html += '<label for="radio-subcategory" part="input-label">SubCategory</label></div>';
      }

      html += '<button id="graph-radios-expander" class="ml-10" part="calendar-tab-button-not-selected"><span class="material-symbols-outlined">chevron_right</span></button>'

      html += '</div>';
      html += '</div>';


      html += '<div class="chart-container d-flex scroll-x align-start"><div part="chart-item" class="chart-item"><canvas id="myChart"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart4" class="gone"></canvas></div><div part="chart-item chart-item-middle" class="chart-item"><canvas id="myChart2" class="gone"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart3" class="gone"></canvas></div></div>';

      html += '<div part="chart-modal-container" id="chart-modal-container" class="chart-modal-container d-flex flex-col hide">'
      html += '<div part="chart-modal-title-container" class="chart-modal-title-container d-flex justify-between mb-10">'
      html += '<button id="chart-modal-close-hide" part="button-icon" class="material-icons invisible">close</button>'
      html += '<div part="chart-modal-title" id="chart-modal-title"></div>'
      html += '<button id="chart-modal-close" part="button-icon" class="material-icons">close</button>'
      html += '</div>';
      html += '<div part="chart-modal" class="chart-modal d-flex scroll-x align-start"><div part="chart-item" class="chart-item"><canvas id="myChart"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart4" class="gone"></canvas></div><div part="chart-item chart-item-middle" class="chart-item"><canvas id="myChart2" class="gone"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart3" class="gone"></canvas></div></div>';
      html += '<div part="chart-modal-bottom" class="chart-modal-bottom d-flex justify-end mt-10 mb-10">'
      html += '<button id="chart-modal-chart-type" part="button-icon" class="material-symbols-outlined">bar_chart</button>'
      html += '<button id="chart-modal-download" part="button-icon" class="material-icons ml-10">cloud_download</button>'
      html += '</div>';
      html += '</div>';

      html += '<div part="fin-risk-container" class="gone FIN_RISK_HIDE_CLASS mt-20 w-100 align-end ">';
      html += 'FIN_RISK_TABLE'
      // html += `
      //     <!-- Left Label -->
      //     <div class="d-flex align-end" part="financial-risk-title-container">
      //       <span part="financial-risk-title">Financial Risk</span>
      //       <sup part="financial-risk-currency">FIN_RISK_CURRENCY</sup>
      //     </div>

      //     <!-- Lower (Residual / Pending Risk) -->
      //     <div class="d-flex align-end" part="financial-risk-section">
      //       <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Lower</div>
      //       <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
      //         <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MIN</span>
      //         </div>
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
      //         <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MIN</span>
      //         </div>
      //       </div>
      //     </div>

      //     <!-- Upper (Mitigated / Addressed Risk) -->
      //     <div class="d-flex align-end" part="financial-risk-section">
      //       <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Higher</div>
      //       <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
      //         <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MAX</span>
      //         </div>
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
      //         <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MAX</span>
      //         </div>
      //       </div>
      //     </div>
      //   `

      // html += '<div part="" class="mb-5">Financial Risk</div>'
      // html += '<table class="w-100 text-center"><thead><tr><th part="financial-risk-header">Risk Status</th><th part="financial-risk-header" class="financial-risk-header">Minimum Risk</th><th part="financial-risk-header" class="financial-risk-header">Maximum Risk</th></tr></thead><tbody>'
      // html += '<tr><td>Residual</td><td>FIN_RISK_RESIDUAL_MIN</td><td>FIN_RISK_RESIDUAL_MAX</td></tr>'
      // html += '<tr><td>Mitigated</td><td>FIN_RISK_MITIGATED_MIN</td><td>FIN_RISK_MITIGATED_MAX</td></tr></tbody></table>'
      html += '</div>'

      html += '<div id="chart-settings-controls" class="mt-20"></div>'
      html += '<div id="chart-settings"></div>'
    } else {
      html += '<div part="box" class="box"></div>';
    }
    html += '</div>';

    return html;

  }
  renderCalendarStatisticsGraphs = (showGraph: boolean, parametersTitle: string) => {

    //console.log('flowGraph', this.flowGraph);

    var html = '';

    html += '<div class="mb-20 stream-event-list" part="stream-event-list-charts">';
    html += '<div class="align-center justify-between d-flex flex-wrap mb-10 w-100-m-0" part="duration-title-container"><h4 part="duration-title">' + parametersTitle + '</h4>'
    if (this.getFeatures().length > 1) {
      html += '<div class="filter-button-container"><button part="button-icon" id="filter-button" class="material-symbols-outlined">category</button>'
      html += '<div id="filter-list-container" class="filter-list-container hide flex-col justify-between align-start p-10" part="filter-list-container" anchor="filter-button">'
      html += '<div id="filter-label-container" class="filter-label-container d-flex justify-between align-center" part="filter-label-container"><label class="filter-label"  part="filter-label">Filters</label><button id="button-submit-features" part="button-icon-small" class="material-icons invisible">check</button></div>'
      // html += `<div class="filter-input-container d-flex"><input class="input-select-feature-all" type="checkbox" ${this.selectedFeatures.length >= (this.getFeatures().length) ? 'checked' : ''} id="input-select-feature-all"  part="input-select-feature" name="all"></input><label for="input-select-feature-all" class="input-select-feature-label-all" id="input-select-feature-label-all"
      //  part="input-select-feature-label">all</label></div>`
      // html += `<div class="filter-input-container d-flex"><input class="input-select-feature-compliances" type="checkbox" ${this.selectedFeatures.indexOf('compliances') >= 0 ? 'checked' : ''} id="input-select-feature-compliances"  part="input-select-feature" name="compliances"></input><label for="input-select-feature-compliances" class="input-select-feature-label"  part="input-select-feature-label">compliances</label></div>`
      for (let [index, feature] of this.getFeatures().entries()) {
        console.log('rendering features statistics', feature, this.selectedFeatures);
        html += `<div class="filter-input-container d-flex"><input class="input-select-feature" type="radio" ${this.selectedFeatures.indexOf(feature) >= 0 ? 'checked' : ''} id="input-select-feature-${index}" name="features" part="input-select-feature" value="${feature}"></input><label for="input-select-feature-${index}" id="input-select-feature-label-${index}" class="input-select-feature-label"  part="input-select-feature-label">${feature}</label></div>`
      }
      html += '</div></div>'
    }
    html += '<button id="button-refresh" part="button-duration-title" class="align-center d-flex justify-center"><h4 part="duration-title">' + parametersTitle + '</h4><span part="duration-title-icon" class="material-icons ml-10">refresh</span></button></div>';
    html += '<div class="align-center d-flex flex-wrap mb-10 w-100-m-0" part="last-update-title-container"><h6 part="last-update-title" class="align-center d-flex"><span class="material-symbols-outlined">update</span>&nbsp;&nbsp;Last Updated on ' + this.lastupdated + '</h6></div>';
    if (showGraph) {
      html += '<div class="chart-container d-flex scroll-x align-start"><div part="chart-item" class="chart-item"><canvas id="myChart"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart2" class="gone"></canvas></div><div part="chart-item chart-item-middle" class="chart-item"><canvas id="myChart3" class="gone"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart4" class="gone"></canvas></div></div>';
      html += '<div part="fin-risk-container" class="gone FIN_RISK_HIDE_CLASS mt-20 w-100 align-end ">';
      html += 'FIN_RISK_TABLE'
      // html += `
      //     <!-- Left Label -->
      //     <div class="d-flex align-end" part="financial-risk-title-container">
      //       <span part="financial-risk-title">Financial Risk</span>
      //       <sup part="financial-risk-currency">FIN_RISK_CURRENCY</sup>
      //     </div>

      //     <!-- Lower (Residual / Pending Risk) -->
      //     <div class="d-flex align-end" part="financial-risk-section">
      //       <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Lower</div>
      //       <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
      //         <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MIN</span>
      //         </div>
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
      //         <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MIN</span>
      //         </div>
      //       </div>
      //     </div>

      //     <!-- Upper (Mitigated / Addressed Risk) -->
      //     <div class="d-flex align-end" part="financial-risk-section">
      //       <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Higher</div>
      //       <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
      //         <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MAX</span>
      //         </div>
      //         <div part="financial-risk-table-col" class="d-flex flex-col align-center">
      //         <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
      //         <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MAX</span>
      //         </div>
      //       </div>
      //     </div>
      //   `

      // html += '<div part="" class="mb-5">Financial Risk</div>'
      // html += '<table class="w-100 text-center"><thead><tr><th part="financial-risk-header">Risk Status</th><th part="financial-risk-header" class="financial-risk-header">Minimum Risk</th><th part="financial-risk-header" class="financial-risk-header">Maximum Risk</th></tr></thead><tbody>'
      // html += '<tr><td>Residual</td><td>FIN_RISK_RESIDUAL_MIN</td><td>FIN_RISK_RESIDUAL_MAX</td></tr>'
      // html += '<tr><td>Mitigated</td><td>FIN_RISK_MITIGATED_MIN</td><td>FIN_RISK_MITIGATED_MAX</td></tr></tbody></table>'
      html += '</div>'

      html += '<div id="chart-settings-controls" class="mt-20"></div>'
      html += '<div id="chart-settings"></div>'
    } else {
      html += '<div part="box" class="box"></div>';
    }
    html += '</div>';

    return html;

  }

  renderCalendarContainerDivStart = (index: number) => {

    var html = '';

    html += '<div id="stream-event-' + index + '" part="stream-event-list" class="stream-event-list">';

    return html;

  }

  renderCalendarContainerDivEnd = () => {

    var html = '';
    html += '</div>';

    return html;

  }

  renderCalendarEventSummary = () => {

    var html = '';

    html += '<div id="stream-event-summary" part="stream-event-total" class="d-flex flex-wrap">';
    html += '<div part="badge-dashboard" class="mr-10 mb-10 no-shrink"><span>Total:</span>&nbsp;<span id="graph-total">DASHBOARD_TOTAL</span></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-0" class="chip stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-icons color-not-started">schedule</span>&nbsp;&nbsp;<span>Not Started:</span>&nbsp;<span id="graph-not-started">DASHBOARD_NOT_STARTED</span></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-1" class="chip stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-symbols-outlined color-pending">pending</span>&nbsp;&nbsp;<span>Pending Approval:</span>&nbsp;<span id="graph-pending-approval">DASHBOARD_PENDING_APPROVAL</span></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-2" class="chip stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-symbols-outlined color-rejected">block</span>&nbsp;&nbsp;<span>Rejected:</span>&nbsp;<span id="graph-rejected">DASHBOARD_REJECTED</span></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-3" class="chip stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-symbols-outlined color-done">check_circle</span>&nbsp;&nbsp;<span>Approved:</span>&nbsp;<span id="graph-approved">DASHBOARD_APPROVED</span></div>';
    html += `<div part="${this.suspenseFlag ? "badge-dashboard-selected" : "badge-dashboard-not-selected"}" id="chip-suspense" class="mr-10 mb-10 d-flex align-center no-shrink DASHBOARD_SUSPENSE_CLASS"><span class="material-symbols-outlined color-not-started">question_mark</span>&nbsp;&nbsp;<span>Suspense:</span>&nbsp;<span id="graph-total">DASHBOARD_SUSPENSE</span></div>`;

    html += '<div part="badge-dashboard" id="chip-timeliness-0" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-in-time">schedule</span>&nbsp;&nbsp;<span>In Time:</span>&nbsp;<span id="graph-in-time">DASHBOARD_IN_TIME</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-1" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-past-due-date">timer</span>&nbsp;&nbsp;<span>Past Due Date:</span>&nbsp;<span id="graph-past-due-date">DASHBOARD_PAST_DUE_DATE</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-2" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-reported">report_off</span>&nbsp;&nbsp;<span>Late Reported:</span>&nbsp;<span id="graph-late-reported">DASHBOARD_LATE_REPORTED</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-3" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-approved">remove_done</span>&nbsp;&nbsp;<span>Late Approved:</span>&nbsp;<span id="graph-late-approved">DASHBOARD_LATE_APPROVED</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-4" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-executed">running_with_errors</span>&nbsp;&nbsp;<span>Late Executed:</span>&nbsp;<span id="graph-late-executed">DASHBOARD_LATE_EXECUTED</span></div>';

    if (this.selectedFeatures.indexOf("contracts") >= 0) {
      html += '<div part="badge-dashboard" id="chip-compliance-0" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-scheduled">schedule</span>&nbsp;&nbsp;<span>Active:</span>&nbsp;<span id="graph-active">DASHBOARD_ACTIVE</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-1" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-not-complied">disabled_by_default</span>&nbsp;&nbsp;<span>About To Expire:</span>&nbsp;<span id="graph-about-to-expire">DASHBOARD_ABOUT_TO_EXPIRE</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-2" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-partially-complied">rule</span>&nbsp;&nbsp;<span>Expired:</span>&nbsp;<span id="graph-expired">DASHBOARD_EXPIRED</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-3" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-complied">sweep</span>&nbsp;&nbsp;<span>Terminated:</span>&nbsp;<span id="graph-terminated">DASHBOARD_TERMINATED</span></div>';
      html += '</div>';
    } else {
      html += '<div part="badge-dashboard" id="chip-compliance-0" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-scheduled">schedule</span>&nbsp;&nbsp;<span>Scheduled:</span>&nbsp;<span id="graph-scheduled">DASHBOARD_SCHEDULED</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-1" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-not-complied">disabled_by_default</span>&nbsp;&nbsp;<span>Not Complied:</span>&nbsp;<span id="graph-not-complied">DASHBOARD_NOT_COMPLIED</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-2" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-partially-complied">rule</span>&nbsp;&nbsp;<span>Partially Complied:</span>&nbsp;<span id="graph-partially-complied">DASHBOARD_PARTIALLY_COMPLIED</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-3" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-complied">sweep</span>&nbsp;&nbsp;<span>Complied:</span>&nbsp;<span id="graph-complied">DASHBOARD_COMPLIED</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-4" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-complied-with-gaps">rule</span>&nbsp;&nbsp;<span>Complied With Gaps:</span>&nbsp;<span id="graph-complied-with-gaps">DASHBOARD_COMPLIED_WITH_GAPS</span></div>';
      html += '<div part="badge-dashboard" id="chip-compliance-5" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-reported-non-compliance">rule</span>&nbsp;&nbsp;<span>Reported Non Compliance:</span>&nbsp;<span id="graph-reported-non-compliance">DASHBOARD_REPORTED_NON_COMPLIANCE</span></div>';
      html += '</div>';
    }

    html += '<div id="stream-event-filter" part="stream-event-total" class="d-flex flex-wrap"></div>';

    return html;

  }
  renderCalendarEventSummaryViewer = () => {

    var html = '';

    html += '<div id="stream-event-summary" part="stream-event-total" class="d-flex flex-wrap">';
    html += '<div part="badge-dashboard" class="d-flex flex-col align-start mr-10 mb-10 no-shrink"><div class="d-flex justify-center align-center"><span>Total:</span>&nbsp;<span id="graph-total">DASHBOARD_TOTAL</span></div><div class="d-flex justify-center">DASHBOARD_TOTAL_SUBFILTER</div></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-0" class="chip stat-completeness d-flex flex-col align-start mr-10 mb-10 no-shrink"><div class="d-flex justify-center align-center"><span class="material-icons color-not-started">schedule</span>&nbsp;&nbsp;<span>Not Started:</span>&nbsp;<span id="graph-not-started">DASHBOARD_NOT_STARTED</span></div><div class="d-flex justify-center">DASHBOARD_NOT_STARTED_SUBFILTER</div></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-1" class="chip stat-completeness d-flex flex-col align-start mr-10 mb-10 no-shrink"><div class="d-flex justify-center align-center"><span class="material-symbols-outlined color-pending">pending</span>&nbsp;&nbsp;<span>Pending Approval:</span>&nbsp;<span id="graph-pending-approval">DASHBOARD_PENDING_APPROVAL</span></div><div class="d-flex justify-center">DASHBOARD_PENDING_APPROVAL_SUBFILTER</div></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-2" class="chip stat-completeness d-flex flex-col align-start mr-10 mb-10 no-shrink"><div class="d-flex justify-center align-center"><span class="material-symbols-outlined color-rejected">block</span>&nbsp;&nbsp;<span>Rejected:</span>&nbsp;<span id="graph-rejected">DASHBOARD_REJECTED</span></div><div class="d-flex justify-center">DASHBOARD_REJECTED_SUBFILTER</div></div>';
    html += '<div part="badge-dashboard" id="chip-completeness-3" class="chip stat-completeness d-flex flex-col align-start mr-10 mb-10 no-shrink"><div class="d-flex justify-center align-center"><span class="material-symbols-outlined color-done">check_circle</span>&nbsp;&nbsp;<span>Approved:</span>&nbsp;<span id="graph-approved">DASHBOARD_APPROVED</span></div><div class="d-flex justify-center">DASHBOARD_APPROVED_SUBFILTER</div></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-0" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-in-time">schedule</span>&nbsp;&nbsp;<span>In Time:</span>&nbsp;<span id="graph-in-time">DASHBOARD_IN_TIME</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-1" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-past-due-date">timer</span>&nbsp;&nbsp;<span>Past Due Date:</span>&nbsp;<span id="graph-past-due-date">DASHBOARD_PAST_DUE_DATE</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-2" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-reported">report_off</span>&nbsp;&nbsp;<span>Late Reported:</span>&nbsp;<span id="graph-late-reported">DASHBOARD_LATE_REPORTED</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-3" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-approved">remove_done</span>&nbsp;&nbsp;<span>Late Approved:</span>&nbsp;<span id="graph-late-approved">DASHBOARD_LATE_APPROVED</span></div>';
    html += '<div part="badge-dashboard" id="chip-timeliness-4" class="chip stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-executed">running_with_errors</span>&nbsp;&nbsp;<span>Late Executed:</span>&nbsp;<span id="graph-late-executed">DASHBOARD_LATE_EXECUTED</span></div>';

    html += '<div part="badge-dashboard" id="chip-compliance-0" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-scheduled">schedule</span>&nbsp;&nbsp;<span>Scheduled:</span>&nbsp;<span id="graph-scheduled">DASHBOARD_SCHEDULED</span></div>';
    html += '<div part="badge-dashboard" id="chip-compliance-1" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-not-complied">disabled_by_default</span>&nbsp;&nbsp;<span>Not Complied:</span>&nbsp;<span id="graph-not-complied">DASHBOARD_NOT_COMPLIED</span></div>';
    html += '<div part="badge-dashboard" id="chip-compliance-2" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-icons color-partially-complied">rule</span>&nbsp;&nbsp;<span>Partially Complied:</span>&nbsp;<span id="graph-partially-complied">DASHBOARD_PARTIALLY_COMPLIED</span></div>';
    html += '<div part="badge-dashboard" id="chip-compliance-3" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-complied">sweep</span>&nbsp;&nbsp;<span>Complied:</span>&nbsp;<span id="graph-complied">DASHBOARD_COMPLIED</span></div>';
    html += '<div part="badge-dashboard" id="chip-compliance-4" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-complied-with-gaps">rule</span>&nbsp;&nbsp;<span>Complied With Gaps:</span>&nbsp;<span id="graph-complied-with-gaps">DASHBOARD_COMPLIED_WITH_GAPS</span></div>';
    html += '<div part="badge-dashboard" id="chip-compliance-5" class="chip stat-compliance justify-center align-center mr-10 mb-10 no-shrink compliance-statuses"><span class="material-symbols-outlined color-reported-non-compliance">rule</span>&nbsp;&nbsp;<span>Reported Non Compliance:</span>&nbsp;<span id="graph-reported-non-compliance">DASHBOARD_REPORTED_NON_COMPLIANCE</span></div>';
    html += '</div>';

    html += '<div id="stream-event-filter" part="stream-event-total" class="d-flex flex-wrap"></div>';

    return html;

  }
  renderStatisticsFiltersTableStart = () => {

    var html = '';
    html += '<div class="w-100 scroll-x">'
    html += '<table id="statistics-table" part="statistics-table" class="statistics-table w-100"><tbody>';

    return html;

  }

  renderStatisticsFiltersTableRow = (index: number, filterUser: boolean = false, isLocation: boolean = false) => {

    var html = '';
    html += '<tr class="tablerow">'
    html += '<td part="td-body" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head" class="pl-0-imp w-100 d-flex align-center">FILTER_CRITERIA_NAME</div><div part="td-head' + (isLocation ? '' : '-click') + '" id="filter-' + index + '">DASHBOARD_FILTER_NAME</div>'
    if (filterUser) {
      html += '<div part="td-head" class="pl-0-imp w-100 d-flex align-center">Last Access</div><div>DASHBOARD_LAST_ACTIVE</div><div part="td-head" class="pl-0-imp w-100 d-flex align-center">Last Action</div><div>DASHBOARD_LAST_ACTION</div>'
    }
    html += '</div></td>'
    html += '<td part="td-body" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head' + (isLocation ? '' : '-click') + '" id="filter-not-started-' + index + '" class="pl-0-imp w-100 d-flex align-center"><span class="small-icon material-icons color-not-started">schedule</span>&nbsp;&nbsp;Not Started</div><div>DASHBOARD_NOT_STARTED</div></div></td>'
    html += '<td part="td-body" id="filter-pending-approval-' + index + '" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head' + (isLocation ? '' : '-click') + '" class="pl-0-imp w-100 d-flex align-center"><span class="small-icon material-symbols-outlined color-pending">pending</span>&nbsp;&nbsp;Pending Approval</div><div>DASHBOARD_PENDING_APPROVAL</div></div></td>'
    html += '<td part="td-body" id="filter-rejected-' + index + '" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head' + (isLocation ? '' : '-click') + '" class="pl-0-imp w-100 d-flex align-center"><span class="small-icon material-symbols-outlined color-rejected">block</span>&nbsp;&nbsp;Rejected</div><div>DASHBOARD_REJECTED</div></div></td>'
    html += '<td part="td-body" id="filter-approved-' + index + '" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head' + (isLocation ? '' : '-click') + '" class="pl-0-imp w-100 d-flex align-center"><span class="small-icon material-symbols-outlined color-done">check_circle</span>&nbsp;&nbsp;Approved</div><div>DASHBOARD_APPROVED</div></div></td>'
    html += '<td part="td-body" id="filter-total-' + index + '" class="td-body TD_BODY_CLASS"><div class="d-flex align-center flex-wrap"><div part="td-head' + (isLocation ? '' : '-click') + '" class="pl-0-imp w-100 d-flex align-center">Total</div><div>DASHBOARD_TOTAL</div></div></td>'
    html += '</tr>';

    return html;

  }

  renderStatisticsFiltersTableEnd = () => {

    var html = '';
    html += '</tbody></table></div>';

    return html;

  }

  getCalendarRowHide = (events: any, i: number, lastDay: number, month: number, firstDate: any = null, currDate: any = null) => {

    var hide = true;

    if (events != null) {
      hide = false;
    } else if (i === 1) {
      hide = false;
    } else if (i === lastDay) {
      hide = false;
    } else {
      if (firstDate == null) {
        const mmddPrev = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i - 1)).slice(-2);
        const mmddNext = ("0" + (month + 1)).slice(-2) + "/" + ("0" + (i + 1)).slice(-2);
        //console.log('hide', i, hide);
        if ((this.events[mmddPrev] != null || this.events[mmddNext] != null)) {
          hide = false;
        }
      } else {
        const startNextDate = new Date(currDate.getTime());
        startNextDate.setDate(currDate.getDate() + 1);

        const startPrevDate = new Date(currDate.getTime());
        startPrevDate.setDate(currDate.getDate() - 1);

        const mmddNext = ("0" + (startNextDate.getMonth() + 1)).slice(-2) + "/" + ("0" + (startNextDate.getDate())).slice(-2);
        const mmddPrev = ("0" + (startPrevDate.getMonth() + 1)).slice(-2) + "/" + ("0" + (startPrevDate.getDate())).slice(-2);
        //console.log('hide', i, hide, startNextDate, startPrevDate, mmddNext, mmddPrev);
        if ((this.events[mmddPrev] != null || this.events[mmddNext] != null)) {
          hide = false;
        }
      }
    }

    return hide;

  }

  renderCalendarRowDivStart = (i: number, firstDate: any = null, ddmm: string = "") => {

    var html = '';

    html += '<div part="stream-event-selected" class="d-flex stream-event-selected">';
    html += '<div part="stream-event-selected-date">' + (firstDate != null ? ddmm : ("0" + i).slice(-2)) + ' |</div>';
    html += '<div class="stream-event-list-container flex-grow">'

    return html;

  }

  renderCalendarRowDivEnd = () => {

    var html = '';

    html += '</div>'
    html += '</div>';

    return html;

  }

  renderCalendarRowDivItemDivStart = (mmdd: string, event: any, itemNumber: number, partStatus: string, bgStatus: string, fromDrilldown: boolean) => {

    var html = '';

    var remarks = "";
    var occurrenceDate = "";

    const arrMmdd = mmdd.split("/");
    const ddmm = arrMmdd[1] + "/" + arrMmdd[0];

    if (event.triggers != null && event.triggers.length > 0 && event.triggers != "[]") {

      const arrTriggers = JSON.parse(event.triggers);
      for (var i = 0; i < arrTriggers.length; i++) {
        const targetDates = arrTriggers[i].targetDates;
        for (var j = 0; j < targetDates.length; j++) {
          // console.log('comparing', targetDates[j], ddmm);
          if (targetDates[j].indexOf(ddmm) >= 0) {
            remarks = arrTriggers[i].remarks;
            occurrenceDate = arrTriggers[i].occurrenceDate;
            // console.log('remarks', mmdd)
          }
        }
      }

    }

    let lastUpdated: string = '';

    // console.log('lastUpdated', event.lastupdated);
    if (event.lastupdated != null && event.lastupdated.length > 0) {
      lastUpdated = Util.getDateTimeStrings(new Date(event.lastupdated).getTime());

    }

    html += '<div class="stream-events-container flex-grow" part="' + bgStatus + '">';
    html += '<div class="hidden-tags hide">' + JSON.stringify(event['tags']) + '</div>'
    html += '<div class="hidden-title hide"><table><thead><th part="badge-filtered"><i>not filtered</i></th></thead></table></div>'
    // html += '<div part="stream-events-event-title" class="stream-events-event-title d-flex align-center pl-5 pb-5">' + '<input id="button-select-' + mmdd.replace('/', '-') + '-' + itemNumber + '-' + (((event.makercheckers != null && (event.makercheckers).length > 0)) ? '1' : '0') + '-' + (((event.docs != null && (event.docs).length > 0)) ? '1' : '0') + '-' + event.entityid.replace(/-/g, '_') + '-' + event.locationid.replace(/-/g, '_') + '-' + event.id.replace(/-/g, '_') + '-' + event.duedate.split('/')[1] + '-' + event.duedate.split('/')[0] + '-' + event.duedate.split('/')[2] + '-' + partStatus.replace(/-/g, '_') + '-' + ((event.module ?? false) ? event.module : 'compliance') + '-' + ((event.isbulk == null || event.isbulk == false) ? "" : "bulk") + (((event.reportformat != null && event.reportformat.length > 0) || (event.isbulk != null && event.isbulk == true) || (event.customreporting != null)) ? "reportformat" : "") + '" class="button-select mr-10 ' + (((event.reportformat != null && event.reportformat.length > 0) || (event.isbulk != null && event.isbulk == true) || (event.customreporting != null)) ? 'hide' : '') + '" type="checkbox"/>' + (event.isbulk != null && event.isbulk == true ? '<div class="lds-dual-ring1 bulk-loader mr-10"></div>' : '') + '<sf-i-elastic-text exportparts="highlight,highlight-count" class="stream-event-title' + (event.isbulk == null || event.isbulk == false ? ' button-event-title' : '') + '" id="stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + itemNumber + '-' + ((event.module ?? false) ? event.module : 'compliance') + '" text="' + event['obligationtitle'] + '" minLength="' + (event.concise == null ? "100" : "60") + '"></sf-i-elastic-text>' + event.concise == null ? ('') : ('<div part="stream-event-location" class="stream-event-location ml-5">' + event.locationname.replace(/ *\([^)]*\) */g, "") + '</div><div part="stream-event-risk-' + event.risk[0].toLowerCase().replace(/ /g, '-') + '" class="stream-event-risk ml-5">' + event.risk[0] + '</div>') + (((event.reportformat != null && event.reportformat.length > 0) || (event.customreporting != null)) ? '' : ('<button id="button-list-reporting-' + mmdd.replace('/', '-') + '-' + itemNumber + '" part="button-list-reporting" class="material-icons ml-10 button-list-reporting">edit_note</button>')) + ((event.concise == null && lastUpdated.length > 0) ? ('&nbsp;&nbsp;<div part="event-last-updated-time" class="d-flex align-center">' + lastUpdated + '</div>') : "") + '</div>';

    const isBulk = event.isbulk === true;
    const hasReportFormat = event.reportformat?.length > 0;
    const hasCustomReporting = event.customreporting != null;
    const hasMakerCheckers = event.makercheckers?.length > 0;
    const hasDocs = event.docs?.length > 0;
    const moduleType = event.module ?? 'compliance';
    const partStatusSanitized = partStatus.replace(/-/g, '_');
    const entityIdSanitized = event.entityid.replace(/-/g, '_');
    const locationIdSanitized = (event.locationid ?? "").replace(/-/g, '_');
    const eventIdSanitized = event.id.replace(/-/g, '_');
    const mmddSanitized = mmdd.replace(/\//g, '-');
    const dueDateParts = event.duedate.split('/');
    const isReportedLocation = event.reportedlocationsflag == true
    const isSuspense = event.suspense == true
    const isReviewed = event.review == true
    const showCheckbox = !(hasReportFormat || isBulk || hasCustomReporting || isReportedLocation);
    // const showReportingButton = !hasReportFormat && !hasCustomReporting && event.reporters == null;
    const showReportingButton = !hasReportFormat && !hasCustomReporting && event.concise != null && !isReportedLocation && !fromDrilldown;
    const showLocationRisk = event.concise != null;
    const configHome = Util.getProjectConfigHome();
    const showReview = event.concise != null && configHome.features != null && configHome.features.indexOf("understood") >= 0;
    const showLastUpdated = event.concise == null && lastUpdated.length > 0;
    // console.log('showReportingButton', showReportingButton)
    // console.log('isReportedLocation', isReportedLocation, 'showCheckbox', showCheckbox, 'showReportingButton', showReportingButton, 'showLocationRisk', showLocationRisk, 'showLastUpdated', showLastUpdated);
    html += `
      <div part="stream-events-event-title" class="stream-events-event-title d-flex align-center pl-5 pb-5">
        <input 
          id="button-select-${mmddSanitized}-${itemNumber}-${hasMakerCheckers ? '1' : '0'}-${hasDocs ? '1' : '0'}-${entityIdSanitized}-${locationIdSanitized}-${eventIdSanitized}-${dueDateParts[1]}-${dueDateParts[0]}-${dueDateParts[2]}-${partStatusSanitized}-${moduleType}-${isBulk ? 'bulk' : ''}${(hasReportFormat || isBulk || hasCustomReporting) ? 'reportformat' : ''}${(isReportedLocation) ? 'reportedlocations' : ''}" 
          class="button-select mr-10 ${showCheckbox ? '' : 'hide'}" 
          type="checkbox"
        />
        ${isBulk ? '<div class="lds-dual-ring1 bulk-loader mr-10"></div>' : ''}
        ${(isReportedLocation && !isSuspense) ? '<div class="material-symbols-outlined mr-10">arrow_or_edge</div>' : ''}
        <sf-i-elastic-text exportparts="highlight,highlight-count" 
          class="stream-event-title${!isBulk ? ' button-event-title' : ''}" 
          id="stream-event-title-${mmddSanitized}-${itemNumber}-${moduleType}-${(isReportedLocation) ? 'reportedlocations' : ''}" 
          text="${event.obligationtitle.replace(/\\n/g, '')}" 
          minLength="${event.concise == null ? '100' : '60'}">
        </sf-i-elastic-text>
        ${showLocationRisk ? `
          <div part="stream-event-location" class="stream-event-location ml-5">
            ${event.locationname.replace(/ *\([^)]*\) */g, "")}
          </div>
          <div part="stream-event-risk-${event.risk[0].toLowerCase().replace(/ /g, '-')}" class="stream-event-risk ml-5">
            ${event.risk[0]}
          </div>
          <div part="stream-event-risk-${event.risk[0].toLowerCase().replace(/ /g, '-')}" class="stream-event-subfrequency ml-5">
            ${event.subfrequency[0]}
          </div>
        ` : ''}
        ${showReportingButton ? `
          <button 
            id="button-list-reporting-${mmddSanitized}-${itemNumber}-${(isReportedLocation) ? 'reportedlocations' : ''}" 
            part="button-list-reporting" 
            class="material-icons ml-10 button-list-reporting">
            edit_note
          </button>
        ` : ''}
        ${showReview ? `
          ${isReviewed ? `<button 
            id="input-checkbox-review-${mmddSanitized}-${itemNumber}" 
            part="button-icon-reviewed" 
            class="material-symbols-outlined d-flex align-center ml-10 button-icon-review">
            flag_check
          </button>` : `<button 
            id="input-checkbox-review-${mmddSanitized}-${itemNumber}" 
            part="button-icon-review" 
            class="d-flex align-center ml-10 button-icon-review">
            <span class="material-symbols-outlined" title="Mark as reviewed">flag</span>&nbsp;&nbsp;Mark Understood
          </button>`}
        ` : ''}

        ${showLastUpdated ? `
          &nbsp;&nbsp;<div part="event-last-updated-time" class="d-flex align-center">
            ${lastUpdated}
          </div>
        ` : ''}
        
      </div>
    `;
    //   ${this.finRiskCurrency == event['localcurrency'] ? `<div part="event-min" class="ml-10 d-flex align-center">${event['minlocal'] ?? ""}</div>` : `<div part="event-min" class="ml-10 d-flex align-center">${event['minglobal'] ?? ""}</div>`}
    // ${this.finRiskCurrency == event['localcurrency'] ? `<div part="event-min" class="ml-10 d-flex align-center">${((event['maxlocal'] < event['minlocal']) ? event['minlocal'] : event['maxlocal']) ?? ""}</div>` : `<div part="event-min" class="ml-10 d-flex align-center">${((event['maxglobal'] < event['minglobal']) ? event['minglobal'] : event['maxglobal']) ?? ""}</div>`}
    if (event.concise == null && remarks.length > 0) {
      html += '<div part="stream-events-event-subtitle" class="stream-events-event-subtitle">' + remarks + ', occurred on ' + occurrenceDate + '</div>';
    }
    // console.log('returning divstarthtml', html);
    return html;

  }

  renderCalendarRowDivItemDivEnd = () => {

    var html = '';
    html += '</div>';

    return html;

  }

  renderCalendarBlankRowDiv = (hide: boolean, slice: number, i: number, firstDate: any = null, ddmm: string = "") => {

    var html = '';

    //console.log('hidedecision', ddmm, hide);

    if (!hide) {
      html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected">';
      html += '<div>' + (firstDate != null ? ddmm : ("0" + i).slice(-2)) + '</div>';
      html += '</div>';
      slice = 2;
    } else {
      if (i % slice === 0) {
        html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected-hidden">';
        //html += '<div>'+("0" + i).slice(-2)+' |</div>';
        html += '<div>.</div>';
        html += '</div>';
        slice += 3;
      }
    }

    return { html: html, slice: slice };

  }

  renderCalendarRowDivItemDivTableHead = (event: any, partStatus: string) => {

    var html = '';

    html += '<table class="stream-events-container-table" part="' + partStatus + '">';
    html += '<thead>';
    if (event.reportedlocationsflag != true) {
      html += '<th part="td-head">';
      // if(event.isbulk == null || event.isbulk == false) html += 'Open'
      html += 'Open'
      html += '</th>';
    }
    html += '<th part="td-head">';
    html += 'Status'
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Location'
    html += '</th>'
    if (event.entityname != null) {
      html += '<th part="td-head">';
      html += 'Entity'
      html += '</th>'
    }
    if (event.countryname != null) {
      html += '<th part="td-head">';
      html += 'Country'
      html += '</th>'
    }
    if (event.functions != null) {
      html += '<th part="td-head">';
      html += 'Function'
      html += '</th>'
    }
    if (event.risk != null) {
      html += '<th part="td-head">';
      html += 'Risk'
      html += '</th>'
    }
    for (var k = 0; k < Object.keys(event).length; k++) {
      if (this.getEventPreviewFields().includes(Object.keys(event)[k])) {
        html += '<th part="td-head" class="bg-left-no-border">';
        html += Object.keys(event)[k];
      }
    }

    //console.log('listing docs',event.documents )
    if (event.documents != null && (event.documents).length > 0) {
      html += '<th part="td-head">';
      html += 'Docs'
      html += '</th>';
    }
    if (event.comments != null && (event.comments).length > 0) {
      html += '<th part="td-head">';
      html += 'Comments'
      html += '</th>';
    }
    // console.log('rendering last updated', event.lastupdated)
    if (event.lastupdated != null && (event.lastupdated).length > 0) {
      html += '<th part="td-head">';
      html += 'Updated'
      html += '</th>';
    }
    if (event.makercheckers != null && (event.makercheckers).length > 0) {
      html += '<th part="td-head">';
      html += ''
      html += '</th>'
    }
    if (event.docs != null && (event.docs).length > 0) {
      html += '<th part="td-head">';
      html += ''
      html += '</th>'
    }
    if (event.obligationtype != null && (event.obligationtype[0].toLowerCase() == "quality indicator confirmatory"
      || event.obligationtype[0].toLowerCase() == "quality indicator percentage")) {
      if (event.comments != null && (event.comments).length > 0) {
        html += '<th part="td-head">';
        html += ''
        html += '</th>'
      }
    }
    html += '</thead>';

    // console.log('event.obligationtype', event.obligationtype[0].toLowerCase());

    return html;

  }

  renderCalendarRowDivItemDivTableBody = (event: any, partStatus: string, lateStatus: string, complianceStatus: string, mmdd: string, i: number, j: number) => {

    var html = '';

    html += '<tbody>';
    if (event.reportedlocationsflag != true) {
      html += '<td id="td-expand-' + i + '" part="td-body">';
      if (event.isbulk == null || !event.isbulk) {
        html += '<button id="button-unmapped-expand-' + mmdd.replace('/', '-') + '-' + j + '-' + ((event.module ?? false) ? event.module : 'compliance') + '" part="button-icon-small" class="material-icons button-expand mr-10">open_in_new</button>'
      } else {
        html += '<div class="lds-dual-ring1 bulk-loader"></div>';
      }
    }
    html += '</td>';
    html += '<td part="td-body">';
    html += this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i);
    html += '</td>';
    if (event["locationname"] != null) {
      html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + event["locationname"].replace(/ *\([^)]*\) */g, "") + '" minLength="10"></sf-i-elastic-text></td>';
    }
    if (event["entityname"] != null) {
      html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + event["entityname"].replace(/ *\([^)]*\) */g, "") + '" minLength="10"></sf-i-elastic-text></td>';
    }
    if (event["countryname"] != null) {
      html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + event["countryname"].replace(/ *\([^)]*\) */g, "") + '" minLength="10"></sf-i-elastic-text></td>';
    }
    if (event["functions"] != null) {
      var functions = '';
      for (const element of event["functions"]) {
        functions += (element.split(';')[0].replace(/ *\([^)]*\) */g, "") + ",");
      }
      functions = functions.replace(/,\s*$/, "");
      html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + functions + '" minLength="10"></sf-i-elastic-text></td>';
    }
    if (event["risk"] != null) {
      html += '<td part="td-body"><div part="nc-stream-event-risk-' + event["risk"][0].toLowerCase().replace(/ /g, '-') + '">' + event["risk"][0] + '</div></td>';
    }
    for (var k = 0; k < Object.keys(event).length; k++) {
      if (this.getEventPreviewFields().includes(Object.keys(event)[k])) {

        html += '<td part="td-body">';
        if (event[Object.keys(event)[k]].indexOf("[") >= 0) {
          html += this.getEventTexts(Object.keys(event)[k], JSON.parse(event[Object.keys(event)[k]]), event);
        } else {
          html += ' <sf-i-elastic-text exportparts="highlight,highlight-count" text="' + event[Object.keys(event)[k]].replace(/"/g, "") + '" minLength="20"></sf-i-elastic-text>';
        }
        html += '</td>';

      }
    }
    if (event["countryname"] != null && event.documents != null && event.documents != null && (event.documents).length > 0) {
      html += '<td part="td-body">';
      html += '<span class="material-icons muted">description</span>'
      html += (event.documents).length
      html += '</td>';
    }
    if (event["countryname"] != null && event.comments != null && event.comments != null && (event.comments).length > 0) {
      html += '<td part="td-body">';
      html += '<span class="material-icons muted">forum</span>'
      html += (event.comments).length
      html += '</td>';
    }
    if (event.lastupdated != null && event.lastupdated != null && (event.lastupdated).length > 0) {
      html += '<td part="td-body">';
      html += Util.timeSince(new Date(event.lastupdated).getTime())
      html += '</td>';
    }
    if (event.makercheckers != null && (event.makercheckers).length > 0) {
      html += '<td part="td-body">';
      html += '<span class="material-symbols-outlined muted">done_all</span>'
      html += '</td>';
    }
    if (event["countryname"] != null && event.docs != null && (event.docs).length > 0) {
      html += '<th part="td-body">';
      html += '<span class="material-symbols-outlined muted">scan_delete</span>'
      html += '</th>'
    }
    if (event.obligationtype != null && (event.obligationtype[0].toLowerCase() == "quality indicator confirmatory"
      || event.obligationtype[0].toLowerCase() == "quality indicator percentage")) {
      if (event.comments != null && (event.comments).length > 0) {
        html += '<td part="td-body">';
        for (var n = (event.comments.length - 1); n >= 0; n--) {

          if (event.comments[n].author == "Reporter") {
            const reportedValue = ((event.comments[n].comment).replace(/ *\([^)]*\) */g, "").trim());
            console.log((event.comments[n].comment).replace(/ *\([^)]*\) */g, "").trim(), reportedValue, event.comments[n]);
            let badge: string = "";
            if (event.obligationtype[0].toLowerCase() == "quality indicator percentage") {
              if (parseInt(reportedValue) > 98) {
                badge = "badge-success";
              } else if (parseInt(reportedValue) > 90) {
                badge = "badge-warning";
              } else {
                badge = "badge-error";
              }

            } else {

              if (reportedValue.toLowerCase() == "yes") {
                badge = "badge-success";
              } else {
                badge = "badge-error";
              }

            }
            html += ('<span class="' + badge + '">' + reportedValue + '</span>');
            break;
          }

        }

        html += '</td>'
      }
    }
    html += '</tbody>';
    html += '</table>';

    return html;

  }

  renderStatusHtml = (partStatus: string, lateStatus: string, complianceStatus: string, i: number) => {

    var html = '';

    html += (complianceStatus == "scheduled" ? '<span class="material-symbols-outlined color-scheduled color-scheduled-item color-scheduled-item-' + i + '" title="Compliance - Scheduled">schedule</span>' : '');
    html += (complianceStatus == "not-complied" ? '<span class="material-symbols-outlined color-not-complied color-not-complied-item color-not-complied-item-' + i + '" title="Compliance - Not Complied">disabled_by_default</span>' : '');
    html += (complianceStatus == "partially-complied" ? '<span class="material-symbols-outlined color-partially-complied color-partially-complied-item color-partially-complied-item-' + i + '"  title="Compliance - Partially Complied">rule</span>' : '');
    html += (complianceStatus == "complied" ? '<span class="material-symbols-outlined color-complied color-complied-item color-complied-item-' + i + '"  title="Compliance - Complied">sweep</span>' : '');
    html += (complianceStatus == "complied-with-gaps" ? '<span class="material-symbols-outlined color-complied-with-gaps color-complied-with-gaps-item color-complied-with-gaps-item-' + i + '"  title="Compliance - Complied with Gaps">rule</span>' : '');
    html += (complianceStatus == "reported-non-compliance" ? '<span class="material-symbols-outlined color-reported-non-compliance color-reported-non-compliance-item color-reported-non-compliance-item-' + i + '"  title="Compliance - Reported Non-Compliance">rule</span>' : '');

    html += (partStatus == "not-started" ? '<span class="material-symbols-outlined color-not-started color-not-started-item color-not-started-item-' + i + '"  title="Completeness - Not Started">schedule</span>' : '');
    html += (partStatus == "pending-approval" ? '<span class="material-symbols-outlined color-pending color-pending-item color-pending-item-' + i + '" title="Completeness - Pending Approval">pending</span>' : '');
    html += (partStatus == "rejected" ? '<span class="material-symbols-outlined color-rejected color-rejected-item color-rejected-item-' + i + '" title="Completeness - Rejected">block</span>' : '');
    html += (partStatus == "approved" ? '<span class="material-symbols-outlined color-done color-done-item color-done-item-' + i + '" title="Completeness - Approved">check_circle</span>' : '');

    html += (lateStatus == "in-time" ? '<span class="material-symbols-outlined color-in-time color-in-time-item color-in-time-item-' + i + '" title="Timeliness - In Time">schedule</span>' : '');
    html += (lateStatus == "past-due-date" ? '<span class="material-symbols-outlined color-past-due-date color-past-due-date-item color-past-due-date-item-' + i + '" title="Timeliness - Past Due Date">timer</span>' : '');
    html += (lateStatus == "late-reported" ? '<span class="material-symbols-outlined color-late-reported color-late-reported-item color-late-reported-item-' + i + '" title="Timeliness - Late Reported">report_off</span>' : '');
    html += (lateStatus == "late-approved" ? '<span class="material-symbols-outlined color-late-approved color-late-approved-item color-late-approved-item-' + i + '" title="Timeliness - Late Approved">remove_done</span>' : '');
    html += (lateStatus == "late-executed" ? '<span class="material-symbols-outlined color-late-executed color-late-executed-item color-late-executed-item-' + i + '" title="Timeliness - Late Executed">running_with_errors</span>' : '');

    html.trim().replace(/ \s*$/, "");

    return html;
  }

  renderStatusString = (partStatus: string, lateStatus: string, complianceStatus: string) => {

    var str: string = '';

    str += (partStatus == "not-started" ? 'not-started ' : '');
    str += (partStatus == "pending-approval" ? 'pending-approval ' : '');
    str += (partStatus == "rejected" ? 'rejected ' : '');
    str += (partStatus == "approved" ? 'approved ' : '');

    str += (lateStatus == "in-time" ? 'in-time ' : '');
    str += (lateStatus == "past-due-date" ? 'past-due-date ' : '');
    str += (lateStatus == "late-reported" ? 'late-reported ' : '');
    str += (lateStatus == "late-approved" ? 'late-approved ' : '');
    str += (lateStatus == "late-executed" ? 'late-executed ' : '');

    str += (complianceStatus == "scheduled" ? 'scheduled ' : '');
    str += (complianceStatus == "complied" ? 'complied ' : '');
    str += (complianceStatus == "not-complied" ? 'not-complied ' : '');
    str += (complianceStatus == "partially-complied" ? 'partially-complied ' : '');

    return str.trim();
  }

  getGraphParam = (event: any) => {
    let graphParam = '';

    //console.log('getGraphParam', this.flowGraph, event);

    if (Array.isArray(event[this.flowGraph])) {
      graphParam = event[this.flowGraph].toString().replace(/ *\([^)]*\) */g, "").replace(/,/g, ' • ');
    } else {
      // console.log('event[this.flowGraph]', event[this.flowGraph], event, this.flowGraph)
      graphParam = (event[this.flowGraph] ?? "").replace(/ *\([^)]*\) */g, "").replace(/,/g, ' • ');
    }
    return graphParam;
  }

  renderCalendarAnnotations = (event: any, mmdd: string, j: number, fromDrilldown: boolean) => {

    var html = '';
    // console.log('rendering Annotations', event.module, event.completenessstatus)
    html += '<div class="hidden-filtername hide"><table><thead><th part="badge-filter-name" class="filtername"></th></thead></table></div>'
    // if(event.concise == null && event.approvers != null){
    let reporterStr = event.concise == null ? this.getReporterStringFromEvent(event) : "";
    let approverStr = event.concise == null ? this.getApproverStringFromEvent(event) : "";

    let graphParam = this.getGraphParam(event);
    // console.log("graphParam", graphParam.split(';')[0]);
    let subfrequencyStr = ""
    if (event.concise == null && event["risk"] != null && event["subfrequency"] != null) {
      subfrequencyStr += '<div part="stream-event-risk-' + event["risk"][0].toLowerCase().replace(/ /g, '-') + '" class="mb-20 ml-10">' + event["subfrequency"][0] + '</div>';
    }
    const configHome = Util.getProjectConfigHome();
    const configFlag = configHome.features != null && configHome.features.indexOf("understood") >= 0
    html += '<div class="d-flex align-center event-user-labels-container"><div part="badge-filter-name" class="graphparamname graphparamname1 mb-20' + (event.concise == null ? "" : ' hide') + '">' + graphParam.split(';')[0] + '</div>' + reporterStr + approverStr + subfrequencyStr + (((event.module == "compliances" || event.module == null) && event.concise == null && ((event.reportformat == null || event.reportformat.length == 0) && (event.customreporting == null) && (event.reportedlocationsflag != true)) && !fromDrilldown) ? ('<button id="button-list-reporting-' + mmdd.replace('/', '-') + '-' + j + '-" part="button-list-reporting" class="material-icons ml-10 mb-20 button-list-reporting">edit_note</button>') : '') + (((event.module == "compliances" || event.module == null) && event.concise == null && configFlag) ? (event.review ? ('<button id="input-checkbox-review-' + mmdd.replace('/', '-') + '-' + j + '" part="button-icon-reviewed" class="material-symbols-outlined d-flex align-center mb-20 ml-10 button-icon-review">flag_check</button>') : ('<button id="input-checkbox-review-' + mmdd.replace('/', '-') + '-' + j + '" part="button-icon-review" class="d-flex align-center mb-20 ml-10 button-icon-review"><span class="material-symbols-outlined" title="Mark as reviewed">flag</span>&nbsp;&nbsp;Mark Understood</button>')) : '') + ((event.module == "rcmresource" && event.completenessstatus == "approved") ? '<button id="button-renew-' + mmdd.replace('/', '-') + '-' + j + '" part="button-icon-small" class="d-flex align-center mb-20 ml-10 button-icon button-renew"><span class="material-symbols-outlined" title="Renew">replay</span>&nbsp;&nbsp;Renew</button>' : '') + '</div>';
    // }

    return html;

  }

  //(firstDay, endDay, 1, lastDay, true, 0, (firstDate.getMonth()), period, firstDate,"From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), showBackgroundButton)
  renderEvents = (_firstDay: any, _endDay: any, iInit: number, iLast: number, showGraph: boolean, index: number, month: number, period: string, firstDate: any = null, parametersTitle: string, showBackgroundButton: boolean, fromDrilldown: boolean = false) => {
    var total = 0, notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0, inTime = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0, lateReported = 0, scheduled = 0, partiallyComplied = 0, notComplied = 0, complied = 0, compliedWithGaps = 0, reportedNonCompliance = 0, active = 0, aboutToExpire = 0, expired = 0, terminated = 0;
    var html = '';
    this.selectedItemIds = [];
    this.selectedItems = [];
    this.selectedStatus = "";
    var csvCols = "", htmlCols = "", htmlSummaryCols = "";
    var csvValues = "", htmlValues = "", htmlSummaryValues = "";
    var slice = 2;
    this.eventsInWindow = [];

    var lastDay = iLast;

    this.minRiskMitigated = [];
    this.minRiskResidual = [];
    this.maxRiskMitigated = [];
    this.maxRiskResidual = [];
    this.finRiskCurrency = [];

    if (!fromDrilldown) {
      this.clearGraphData();
      console.log('this.clearSelectedGraphParam(); 1', this.graphFilter);
      this.clearSelectedGraphParam();
      this.clearSelectedLegend();
      html += this.renderCalendarGraphs(showGraph, parametersTitle, showBackgroundButton);
    }
    html += this.renderCalendarContainerDivStart(index)
    html += `<div id="stream-event-uploader" part="stream-event-uploader" class="d-flex justify-end hide"><span for="external-reporting-file-uploader" part="stream-event-uploader-label">Upload External reporting file (.xlsx only)</span><input id="external-reporting-file-uploader" type="file" accept=".xlsx"/></div>`
    html += this.renderCalendarEventSummary();

    if (this.selectedFeatures.indexOf('contracts') >= 0) {
      csvCols += 'Id,ReferenceNo.,Type,Country,Entity,Location,Party1,Party2,Party3,Reporter,Approver,Functionhead,DueDate,Status,ReportParameter'
      htmlCols += '<tr><th class="td-thin">Id</th><th class="td-thin">Reference No.</th><th class="td-thin">Type</th><th class="td-thin">Country</th><th class="td-thin">Entity</th><th class="td-thin">Location</th><th class="td-thin">Party 1</th><th class="td-thin">Party 2</th><th class="td-wide">Party 3</th><th class="td-thin">DueDate</th><th class="td-wide">Status</th><th class="td-wide">ReportParameter</th></tr>'

    } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
      csvCols += 'Id,ReferenceNo.,Type,Country,Entity,Location,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter'
      htmlCols += '<tr><th class="td-thin">Id</th><th class="td-thin">Reference No.</th><th class="td-thin">Type</th><th class="td-thin">Country</th><th class="td-thin">Entity</th><th class="td-thin">Location</th><th class="td-thin">State</th><th class="td-thin">Jurisdiction</th><th class="td-thin">Category</th><th class="td-thin">Subcategory</th><th class="td-wide">Statute</th><th class="td-thin">ObligationType</th><th class="td-thin">RiskSeverity</th><th class="td-wide">RiskAreas</th><th class="td-thin">Frequency</th><th class="td-thin">SubFrequency</th><th class="td-thin">DueDate</th><th class="td-wide">Status</th><th class="td-wide">ReportParameter</th></tr>'
    } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
      csvCols += 'Id,Name,Url,Country,Entity,Location,Reporter,Approver,Functionhead,LastCheckedDate,DueDate,Terminated,Status,ReportParameter'
      htmlCols += '<tr><th class="td-thin">Id</th><th class="td-thin">Name</th><th class="td-thin">Url</th><th class="td-thin">Country</th><th class="td-thin">Entity</th><th class="td-thin">Location</th><th class="td-thin">LastCheckedDate</th><th class="td-thin">DueDate</th><th class="td-thin">Terminated</th><th class="td-wide">Status</th><th class="td-wide">ReportParameter</th></tr>'
    } else {
      csvCols += 'Id,Country,Entity,Location,Function,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,Reference,ObligationType,ObligationTitle,Obligation,Penalty,RiskSeverity,Frequency,SubFrequency,DueDate,Status,ReportParameter,ReporterComments,DateOfCompletion,DateOfReporting,CompletionPercentage,ApproverStatus,ApproverComments,ApprovalDate'
      htmlCols += '<tr><th class="td-thin">Id</th><th class="td-thin">Country</th><th class="td-thin">State</th><th class="td-thin">Jurisdiction</th><th class="td-thin">Category</th><th class="td-thin">Subcategory</th><th class="td-wide">Statute</th><th class="td-thin">Reference</th><th class="td-thin">ObligationType</th><th class="td-wide">ObligationTitle</th><th class="td-wide">Obligation</th><th class="td-wide">Penalty</th><th class="td-thin">RiskSeverity</th><th class="td-thin">Frequency</th><th class="td-thin">SubFrequency</th><th class="td-thin">DueDate</th><th class="td-wide">Status</th><th class="td-wide">ReportParameter</th><th class="td-wide">ReporterComments</th><th class="td-thin">DateOfCompletion</th><th class="td-thin">DateOfReporting</th><th class="td-this">CompletionPercentage</th><th class="td-thin">ApproverStatus</th><th class="td-wide">ApproverComments</th><th class="td-wide">ApprovalDate</th></tr>'
    }

    if (this.selectedFeatures.indexOf('contracts') >= 0) {
      htmlSummaryCols += '<tr><th class="td-thin">Id</th><th class="td-wide">Reference No.</th><th class="td-wide">Status</th><th class="td-wide">Documents</th></tr>'
    } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
      htmlSummaryCols += '<tr><th class="td-thin">Id</th><th class="td-wide">Reference No.</th><th class="td-wide">Status</th><th class="td-wide">Documents</th></tr>'
    } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
      htmlSummaryCols += '<tr><th class="td-thin">Id</th><th class="td-wide">Name</th><th class="td-wide">Status</th><th class="td-wide">Url</th></tr>'
    } else {
      htmlSummaryCols += '<tr><th class="td-thin">Id</th><th class="td-wide">ObligationTitle</th><th class="td-wide">Status</th><th class="td-wide">Documents</th></tr>'
    }

    // let tempMinRiskMitigatedLocal = 0;
    // let tempMinRiskResidualLocal = 0;
    // let tempMaxRiskMitigatedLocal = 0;
    // let tempMaxRiskResidualLocal = 0;
    // let tempMinRiskMitigatedGlobal = 0;
    // let tempMinRiskResidualGlobal = 0;
    // let tempMaxRiskMitigatedGlobal = 0;
    // let tempMaxRiskResidualGlobal = 0;
    this.finRiskCurrency = []
    this.minRiskMitigated = [];
    this.minRiskResidual = [];
    this.maxRiskMitigated = [];
    this.maxRiskResidual = [];

    // let flagGlobal = false;
    for (var i = iInit; i <= iLast; i++) {

      let mmdd: string = "";

      if (firstDate == null) {
        mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
      } else {
        const currDate = new Date(firstDate.getTime());
        currDate.setDate(firstDate.getDate() + (i));
        mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
      }

      //console.log('mmdd', mmdd);
      // console.log('mmddevent', mmdd, this.events[mmdd], firstDate);

      var hide;
      if (firstDate == null) {
        hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, null);
      } else {
        const currDate = new Date(firstDate.getTime());
        currDate.setDate(firstDate.getDate() + (i - 1));
        hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, currDate);
      }

      if (this.events[mmdd] != null) {


        html += this.renderCalendarRowDivStart(i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]);

        for (var j = 0; j < (this.events[mmdd] as Array<any>).length; j++) {

          total++;
          this.events[mmdd][j]['mmdd'] = mmdd
          this.eventsInWindow.push(this.events[mmdd][j]);


          var partStatus = "";
          var lateStatus = "";
          var complianceStatus = "";
          var bgStatus = "event-status-"

          // const tempEvents1 = JSON.parse(JSON.stringify(this.events));
          // //console.log('eventlog1', tempEvents1['06/30'][7].comments, mmdd, j);

          partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(this.events[mmdd][j])));
          this.events[mmdd][j].completenessstatus = partStatus;
          lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(this.events[mmdd][j])), partStatus);
          complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(this.events[mmdd][j])).percentage, JSON.parse(JSON.stringify(this.events[mmdd][j])));
          // console.log("agreement partStatus", partStatus, lateStatus, complianceStatus);
          if (this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
            bgStatus += lateStatus
          } else if (this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
            bgStatus += complianceStatus
          } else {
            bgStatus += partStatus
          }

          // const tempEvents2 = JSON.parse(JSON.stringify(this.events));
          // //console.log('eventlog2', tempEvents2['06/30'][7].comments, mmdd, j);
          if (this.events[mmdd][j]['localcurrency'] != null && this.events[mmdd][j]['localcurrency'] != "" && (this.finRiskCurrency.indexOf(this.events[mmdd][j]['localcurrency']) < 0)) {
            this.finRiskCurrency.push(this.events[mmdd][j]['localcurrency']);
            this.minRiskMitigated.push(0);
            this.minRiskResidual.push(0);
            this.maxRiskMitigated.push(0);
            this.maxRiskResidual.push(0);
          }
          let indexCurrency = this.finRiskCurrency.indexOf(this.events[mmdd][j]['localcurrency']);

          let minLocal = parseInt(this.events[mmdd][j]['minlocal'] == null || this.events[mmdd][j]['minlocal'] == "" ? "0" : this.events[mmdd][j]['minlocal'])
          let maxLocal = parseInt(this.events[mmdd][j]['maxlocal'] == null || this.events[mmdd][j]['maxlocal'] == "" ? "0" : this.events[mmdd][j]['maxlocal'])
          if (partStatus == "approved") {
            this.minRiskMitigated[indexCurrency] = this.minRiskMitigated[indexCurrency] + minLocal
            this.maxRiskMitigated[indexCurrency] = this.maxRiskMitigated[indexCurrency] + maxLocal
          } else {
            this.minRiskResidual[indexCurrency] = this.minRiskResidual[indexCurrency] + minLocal
            this.maxRiskResidual[indexCurrency] = this.maxRiskResidual[indexCurrency] + maxLocal
          }
          // let minGlobal = parseInt(this.events[mmdd][j]['minglobal'] == null || this.events[mmdd][j]['minglobal'] == "" ? "0" : this.events[mmdd][j]['minglobal'])
          // let maxGlobal = parseInt(this.events[mmdd][j]['maxglobal'] == null || this.events[mmdd][j]['maxglobal'] == "" ? "0" : this.events[mmdd][j]['maxglobal'])
          // if (partStatus == "approved") {
          //   tempMinRiskMitigatedLocal = tempMinRiskMitigatedLocal + minLocal
          //   tempMaxRiskMitigatedLocal = tempMaxRiskMitigatedLocal + maxLocal
          //   tempMinRiskMitigatedGlobal = tempMinRiskMitigatedGlobal + minGlobal
          //   tempMaxRiskMitigatedGlobal = tempMaxRiskMitigatedGlobal + maxGlobal
          // } else {
          //   tempMinRiskResidualLocal = tempMinRiskResidualLocal + minLocal
          //   tempMaxRiskResidualLocal = tempMaxRiskResidualLocal + maxLocal
          //   tempMinRiskResidualGlobal = tempMinRiskResidualGlobal + minGlobal
          //   tempMaxRiskResidualGlobal = tempMaxRiskResidualGlobal + maxGlobal
          // }

          notStarted = notStarted + (partStatus == "not-started" ? 1 : 0);
          pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0);
          rejected = rejected + (partStatus == "rejected" ? 1 : 0);
          approved = approved + (partStatus == "approved" ? 1 : 0);
          inTime = inTime + (lateStatus == "in-time" ? 1 : 0);
          pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0);
          lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0);
          lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0);
          lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0);
          scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0);
          partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0);
          notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0);
          complied = complied + (complianceStatus == "complied" ? 1 : 0);
          compliedWithGaps = compliedWithGaps + (complianceStatus == "complied-with-gaps" ? 1 : 0);
          reportedNonCompliance = reportedNonCompliance + (complianceStatus == "reported-non-compliance" ? 1 : 0);
          active = active + (complianceStatus == "active" ? 1 : 0);
          aboutToExpire = aboutToExpire + (complianceStatus == "about-to-expire" ? 1 : 0);
          expired = expired + (complianceStatus == "expired" ? 1 : 0);
          terminated = terminated + (complianceStatus == "terminated" ? 1 : 0);

          this.events[mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus;
          this.events[mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus;
          if (this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] != null) {
            this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE + "obj"] = this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE];
          }
          this.events[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus;

          this.updateStats(this.events[mmdd][j], partStatus, lateStatus, complianceStatus);
          // if (this.events[mmdd][j]["documents"] != null && !fromDrilldown) {
          if (this.events[mmdd][j]["documents"] != null) {
            if (this.selectedFeatures.indexOf('contracts') >= 0) {
              //Id,ReferenceNo.,Type,Country,Entity,Location,Party1,Party2,Party3,Reporter,Approver,Functionhead,DueDate,Status,ReportParameter
              csvValues += ('"' + (this.events[mmdd][j]["id"] + '",'));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "").replace(/\n/g, ' ') + '",'));
              csvValues += ('"' + ((this.events[mmdd][j]["contracttypename"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["party1"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["party2"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["party3"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "").replace(/\n/g, ' ') + '",'));
              csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "").replace(/\n/g, ' ') + '",'));
              csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "").replace(/\n/g, ' ') + '",'));
              csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "").replace(/\n/g, ' ') + '",'));
              csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",'));
              csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]).replace(/\n/g, ' ') + '"\n'));

              //Id,RefNo,Type,Country,Entity,Location,Party1,Party2,Party3,DueDate,Status,ReportParameter
              htmlValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["id"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["obligationtitle"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["contracttypename"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["party1"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["party2"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["party3"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["duedate"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide text-center status-format">' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + this.getGraphParam(this.events[mmdd][j]) + '</td>'
                + '</tr>');
            } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
              //Id,ReferenceNo.,Type,Country,Entity,Location,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter
              csvValues += ('"' + (this.events[mmdd][j]["id"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["licensetypename"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.statute?.state ?? "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["jurisdiction"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.complianceobj?.category ?? "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["subcategory"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events?.[mmdd]?.[j]?.statute?.name ?? "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtype"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["risk"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["riskarea"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["frequency"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (((this.events?.[mmdd]?.[j]?.complianceobj?.subfrequency ?? "") + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]).replace(/\n/g, ' ') + '"\n'));

              //Id,ReferenceNo.,Type,Country,Entity,Location,State,Jurisdiction,Category,Subcategory,Statute,ObligationType,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter
              htmlValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["id"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["obligationtitle"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["licensetypename"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events?.[mmdd]?.[j]?.statute?.state ?? "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["jurisdiction"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + (this.events?.[mmdd]?.[j]?.complianceobj?.category ?? "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["subcategory"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + (this.events?.[mmdd]?.[j]?.statute?.name ?? "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["obligationtype"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["risk"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["riskarea"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["frequency"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + ((this.events?.[mmdd]?.[j]?.complianceobj?.subfrequency ?? "") + "").replace(/"/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["duedate"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide text-center status-format">' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + this.getGraphParam(this.events[mmdd][j]) + '</td>'
                + '</tr>');
            } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
              //Id,Name,Url,Country,Entity,Location,Reporter,Approver,Functionhead,LastCheckedDate,DueDate,Terminated,Status,ReportParameter
              csvValues += ('"' + (this.events[mmdd][j]["id"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["url"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["lastcheckeddate"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["terminated"] ? "Yes" : "No").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]).replace(/\n/g, ' ') + '"\n'));

              //Id,Name,Url,Country,Entity,Location,LastCheckedDate,DueDate,Terminated,Status,ReportParameter
              htmlValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["id"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["obligationtitle"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["url"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["lastcheckeddate"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["duedate"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + (this.events[mmdd][j]["terminated"] ? "Yes" : "No") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide text-center status-format">' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + this.getGraphParam(this.events[mmdd][j]) + '</td>'
                + '</tr>');
            } else {
              //Id,Country,Entity,Location,Function,Reporter,Approver,Functionhead,State
              csvValues += ('"' + (this.events[mmdd][j]["id"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["countryname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["entityname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["locationname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["functions"] ?? [])[0] ?? "").split(';')[0] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((((this.events[mmdd][j]["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["state"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["jurisdiction"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["category"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["subcategory"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.events[mmdd][j]["statute"] + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["reference"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["applicability"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtype"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligationtitle"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["obligation"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["firstlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["secondlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["thirdlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["internalcontrols"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["penalty"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["form"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["additionalurls"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["definition"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["authority"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["risk"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              // csvValues += ('"' + ((this.events[mmdd][j]["riskarea"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["frequency"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["subfrequency"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + ((this.events[mmdd][j]["duedate"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.renderStatusString(partStatus, lateStatus, complianceStatus) + '",').replace(/\n/g, ' '));
              csvValues += ('"' + (this.getGraphParam(this.events[mmdd][j]).replace(/\n/g, ' ') + '",'));
              let reporterComments = []
              let reportedTime = ""
              let approverComments = []
              let approvedTime = ""
              let dateOfCompletion = ""
              for (let comment of this.events[mmdd][j]['comments']) {
                if (comment.author == "Reporter") {
                  reporterComments.push(comment.comment)
                  reportedTime = Util.getDateTimeStrings(new Date(comment.timestamp).getTime())
                } else if (comment.author == "Approver") {
                  approverComments.push(comment.comment)
                  approvedTime = Util.getDateTimeStrings(new Date(comment.timestamp).getTime())
                }
              }
              if (this.events[mmdd][j]['dateofcompletion'] != "") {
                dateOfCompletion = Util.getDateTimeStrings(new Date(parseInt(this.events[mmdd][j]['dateofcompletion'])).getTime())
              }
              csvValues += ('"' + (reporterComments.join(' ').replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (dateOfCompletion.replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (reportedTime.replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (((this.events[mmdd][j]['percentage']) ?? "").replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (((this.events[mmdd][j]['approved']) ?? false).toString().replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (approverComments.join(' ').replace(/"/g, '\"') + '",'));
              csvValues += ('"' + (approvedTime.replace(/"/g, '\"') + '"\n'));


              // csvValues += (period + ',' 
              //   + this.renderStatusString(partStatus, lateStatus, complianceStatus) + ',' 
              //   + this.events[mmdd][j]["id"] + ',' 
              //   + this.events[mmdd][j]["obligationtitle"] + ',' 
              //   + this.events[mmdd][j]["obligation"] + ',' 
              //   + this.events[mmdd][j]["duedate"]
              //   + '\n');

              htmlValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["id"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["country"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["state"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["jurisdiction"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["category"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["subcategory"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["statute"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["reference"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["applicability"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["obligationtype"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["obligationtitle"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["obligation"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["firstlineofdefence"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["secondlineofdefence"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["thirdlineofdefence"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["internalcontrols"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["penalty"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["form"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["additionalurls"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["definition"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["authority"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["risk"] + '</td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">' + this.events[mmdd][j]["riskarea"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["frequency"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["subfrequency"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + this.events[mmdd][j]["duedate"] + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide text-center status-format">' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + this.getGraphParam(this.events[mmdd][j]) + '</td>'

                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + (reporterComments.join('<br />')) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + dateOfCompletion + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + reportedTime + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + ((this.events[mmdd][j]['percentage']) ?? "") + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + ((this.events[mmdd][j]['approved']) ?? false).toString() + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide status-format">' + (approverComments.join(' ')) + '</td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin">' + approvedTime + '</td>'
                + '</tr>');
            }
            if (this.selectedFeatures.indexOf('contracts') >= 0) {
              htmlSummaryValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["id"] + '" minLength="10"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["obligationtitle"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">');

              for (let document of this.events[mmdd][j].contractdocuments ?? []) {
                htmlSummaryValues += `<sf-i-uploader class="summary-report-doc" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": document.key, "ext": document.ext }]).replace(/"/g, '&quot;')}" projectid="${this.projectId} " extract="no" mode="view" maximize="yes" hidepreview="yes"></sf-i-uploader><br />`
              }
              htmlSummaryValues += '</td></tr>'
            } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
              htmlSummaryValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["id"] + '" minLength="10"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["obligationtitle"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">');

              for (let document of this.events[mmdd][j].licensedocuments ?? []) {
                htmlSummaryValues += `<sf-i-uploader class="summary-report-doc" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": document.key, "ext": document.ext }]).replace(/"/g, '&quot;')}" projectid="${this.projectId} " extract="no" mode="view" maximize="yes" hidepreview="yes"></sf-i-uploader><br />`
              }
              htmlSummaryValues += '</td></tr>'
            } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
              htmlSummaryValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["id"] + '" minLength="10"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["obligationtitle"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["url"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td></tr>')
            } else {
              htmlSummaryValues += ('<tr><td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-thin"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["id"] + '" minLength="10"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["obligationtitle"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                // + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.events[mmdd][j]["obligation"] + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.renderStatusString(partStatus, lateStatus, complianceStatus) + '" minLength="100" lineSize="4"></sf-i-elastic-text></td>'
                + '<td class="' + (total % 2 === 0 ? 'td-odd' : 'td-even') + ' td-wide">');

              for (let document of this.events[mmdd][j].documents) {
                htmlSummaryValues += `<sf-i-uploader class="summary-report-doc" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": document.key, "ext": document.ext }]).replace(/"/g, '&quot;')}" projectid="${this.projectId} " extract="no" mode="view" maximize="yes" hidepreview="yes"></sf-i-uploader><br />`
              }
              // htmlSummaryValues += this.renderCalendarAnnotations(this.events[mmdd][j]);
              htmlSummaryValues += '</td></tr>'
            }
          }

          html += this.renderCalendarRowDivItemDivStart(mmdd, this.events[mmdd][j], j, partStatus, bgStatus, fromDrilldown);
          // if (this.events[mmdd][j]["countryname"] != null) {
          if (this.events[mmdd][j]["concise"] == null) {
            html += this.renderCalendarRowDivItemDivTableHead(this.events[mmdd][j], partStatus);
            html += this.renderCalendarRowDivItemDivTableBody(this.events[mmdd][j], partStatus, lateStatus, complianceStatus, mmdd, i, j);
          }
          html += this.renderCalendarAnnotations(this.events[mmdd][j], mmdd, j, fromDrilldown);
          html += '<div class="list-reporting-container d-flex flex-col hide" part="list-reporting-container" id="list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j + '"></div>'
          html += this.renderCalendarRowDivItemDivEnd();

        }

        html += this.renderCalendarRowDivEnd();

      } else {

        const result: any = this.renderCalendarBlankRowDiv(hide, slice, i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]);
        //console.log('result', result);
        html += result.html;
        slice = result.slice;

      }

    }

    html += this.renderCalendarContainerDivEnd();

    // if (flagGlobal) {
    //   this.minRiskMitigated = tempMinRiskMitigatedGlobal
    //   this.maxRiskMitigated = tempMaxRiskMitigatedGlobal
    //   this.minRiskResidual = tempMinRiskResidualGlobal
    //   this.maxRiskResidual = tempMaxRiskResidualGlobal
    // } else {
    //   this.minRiskMitigated = tempMinRiskMitigatedLocal
    //   this.maxRiskMitigated = tempMaxRiskMitigatedLocal
    //   this.minRiskResidual = tempMinRiskResidualLocal
    //   this.maxRiskResidual = tempMaxRiskResidualLocal
    // }

    let showFinRisk = false
    if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('notices') && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0 && this.finRiskCurrency.length > 0 && (this.minRiskResidual.length > 0 || this.minRiskMitigated.length > 0 || this.maxRiskResidual.length > 0 || this.maxRiskMitigated.length > 0)) {
      showFinRisk = true
    }
    //console.log('final risk severities', this.riskSeverityData);

    //this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear();
    this.period = period;


    this.csvDataCompliances = csvCols + "\n" + csvValues;
    this.htmlDataCompliances = '<table>' + htmlCols + htmlValues + '</table>';
    this.htmlDataSummary = '<table class="w-100">' + htmlSummaryCols + htmlSummaryValues + '</table>';

    //console.log('renderevents htmlcols', this.htmlDataCompliances);

    //console.log('progress', this.period, total, notStarted, approved)

    html = html.replace("DASHBOARD_TOTAL", total + "");
    html = html.replace("DASHBOARD_SUSPENSE_CLASS", (this.suspenseCount > 0) ? "" : " hide");
    html = html.replace("DASHBOARD_SUSPENSE", this.suspenseCount + "");
    html = html.replace("DASHBOARD_NOT_STARTED", notStarted + "");
    html = html.replace("DASHBOARD_APPROVED", approved + "");
    html = html.replace("DASHBOARD_PENDING_APPROVAL", pendingApproval + "");
    html = html.replace("DASHBOARD_REJECTED", rejected + "");
    html = html.replace("DASHBOARD_IN_TIME", inTime + "");
    html = html.replace("DASHBOARD_PAST_DUE_DATE", pastDueDate + "");
    html = html.replace("DASHBOARD_LATE_REPORTED", lateReported + "")
    html = html.replace("DASHBOARD_LATE_EXECUTED", lateExecuted + "");
    html = html.replace("DASHBOARD_LATE_APPROVED", lateApproved + "");
    html = html.replace("DASHBOARD_SCHEDULED", scheduled + "");
    html = html.replace("DASHBOARD_NOT_COMPLIED", notComplied + "");
    html = html.replace("DASHBOARD_PARTIALLY_COMPLIED", partiallyComplied + "");
    html = html.replace("DASHBOARD_COMPLIED", complied + "");
    html = html.replace("DASHBOARD_COMPLIED_WITH_GAPS", compliedWithGaps + "");
    html = html.replace("DASHBOARD_REPORTED_NON_COMPLIANCE", reportedNonCompliance + "");
    html = html.replace("DASHBOARD_ACTIVE", active + "");
    html = html.replace("DASHBOARD_ABOUT_TO_EXPIRE", aboutToExpire + "");
    html = html.replace("DASHBOARD_EXPIRED", expired + "");
    html = html.replace("DASHBOARD_TERMINATED", terminated + "");
    console.log('financial risk values', this.minRiskResidual, this.maxRiskResidual, this.minRiskMitigated, this.maxRiskMitigated);

    console.log('FinancialRisk :', this.finRiskCurrency, this.minRiskResidual, this.maxRiskResidual, this.minRiskMitigated, this.maxRiskMitigated);
    let finRiskTableHtml = `<div class="d-flex align-start justify-start w-100">
                              <div class="d-flex align-end" part="financial-risk-title-container">
                                <span part="financial-risk-title">Financial Risk</span>
                              </div>
                              <div class="d-flex flex-col align-start" part="financial-risk-table-container">`
    let finRiskTemplatehtml = `
          <div class="d-flex align-start justify-start w-100" part="financial-risk-table-row">
          <!-- Left Label -->
          <div class="d-flex align-end" part="financial-risk-title-container">
            <sup part="financial-risk-currency">FIN_RISK_CURRENCY</sup>
          </div>

          <!-- Lower (Residual / Pending Risk) -->
          <div class="d-flex align-end" part="financial-risk-section">
            <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Lower</div>
            <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
              <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MIN</span>
              </div>
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
              <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MIN</span>
              </div>
            </div>
          </div>

          <!-- Upper (Mitigated / Addressed Risk) -->
          <div class="d-flex align-end" part="financial-risk-section">
            <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Higher</div>
            <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
              <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MAX</span>
              </div>
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
              <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MAX</span>
              </div>
            </div>
          </div>
          </div>
        `
    for (let [indexCurrency, currency] of this.finRiskCurrency.entries()) {
      let finRiskCurrencyHtml = finRiskTemplatehtml.replace(/FIN_RISK_CURRENCY/g, currency)
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_MITIGATED_MIN/g, this.formatIndianNumber(this.minRiskMitigated[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_MITIGATED_MAX/g, this.formatIndianNumber(this.maxRiskMitigated[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_RESIDUAL_MIN/g, this.formatIndianNumber(this.minRiskResidual[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_RESIDUAL_MAX/g, this.formatIndianNumber(this.maxRiskResidual[indexCurrency]))

      finRiskTableHtml += finRiskCurrencyHtml
    }
    finRiskTableHtml += '</div></div>'
    html = html.replace("FIN_RISK_TABLE", finRiskTableHtml);
    // html = html.replace("FIN_RISK_CURRENCY", this.finRiskCurrency);
    // html = html.replace("FIN_RISK_RESIDUAL_MIN", this.formatIndianNumber(this.minRiskResidual));
    // html = html.replace("FIN_RISK_RESIDUAL_MAX", this.formatIndianNumber(this.maxRiskResidual));
    // html = html.replace("FIN_RISK_MITIGATED_MIN", this.formatIndianNumber(this.minRiskMitigated));
    // html = html.replace("FIN_RISK_MITIGATED_MAX", this.formatIndianNumber(this.maxRiskMitigated));
    html = html.replace("gone FIN_RISK_HIDE_CLASS", showFinRisk ? "d-flex" : "gone");

    if (this.selectedFeatures.indexOf("contracts") >= 0) {
      this.csvDataStats = 'Period,Total,Not Started,Approved,Pending Approval,Rejected,Past Due Date,Late Reported,Late Executed,Late Approved,Active,About To Expire,Expired,Terminated\n';
      this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + pendingApproval + "," + rejected + "," + pastDueDate + "," + lateReported + "," + lateExecuted + "," + lateApproved + "," + active + "," + aboutToExpire + "," + expired + "," + terminated;
    } else {
      this.csvDataStats = 'Period,Total,Not Started,Approved,Pending Approval,Rejected,Past Due Date,Late Reported,Late Executed,Late Approved,Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance\n';
      this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + pendingApproval + "," + rejected + "," + pastDueDate + "," + lateReported + "," + lateExecuted + "," + lateApproved + "," + scheduled + "," + notComplied + "," + partiallyComplied + "," + complied + "," + compliedWithGaps + "," + reportedNonCompliance;
    }

    if (!fromDrilldown) {
      this.htmlDataStats = 'Completeness<br /><br /><table class="w-100"><tr><th class="w-14">Total</th><th class="w-14">Not Started</th><th class="w-14">Approved</th><th class="w-14">Pending Approval</th><th class="w-14">Rejected</th><tr>';
      this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">' + total + '</td><td class="w-14 text-center td-odd">' + notStarted + '</td><td class="w-14 text-center td-odd">' + approved + '</td><td class="w-14 text-center td-odd">' + pendingApproval + '</td><td class="w-14 text-center td-odd">' + rejected + '</td></table>'

      this.htmlDataStats += '<br /><br />Timeliness<br /><br /><table class="mt-20 w-100"><tr><th class="w-14">Total</th><th class="w-14">In Time</th><th class="w-14">Past Due Date</th><th class="w-14">Late Reported</th><th class="w-14">Late Executed</th><th class="w-14">Late Approved</th><tr>';
      this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">' + total + '</td><td class="w-14 text-center td-odd">' + (total - (pastDueDate + lateApproved + lateExecuted)) + '</td><td class="w-14 text-center td-odd">' + pastDueDate + '</td><td class="w-14 text-center td-odd">' + lateReported + '</td><td class="w-14 text-center td-odd">' + lateExecuted + '</td><td class="w-14 text-center td-odd">' + lateApproved + '</td><tr></table>'
      if (this.selectedFeatures.indexOf("contracts") >= 0) {
        this.htmlDataStats += '<br /><br />Compliance<br /><br /><table class="w-100"><tr><th class="w-14">Total</th><th class="w-14">Active</th><th class="w-14">About To Expire</th><th class="w-14">Expired</th><th class="w-14">Terminated</th><tr>';
        this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">' + total + '</td><td class="w-14 text-center td-odd">' + active + '</td><td class="w-14 text-center td-odd">' + aboutToExpire + '</td><td class="w-14 text-center td-odd">' + expired + '</td><td class="w-14 text-center td-odd">' + terminated + '</td><tr></table>'
      } else {
        this.htmlDataStats += '<br /><br />Compliance<br /><br /><table class="w-100"><tr><th class="w-14">Total</th><th class="w-14">Scheduled</th><th class="w-14">Not Complied</th><th class="w-14">Partially Complied</th><th class="w-14">Complied</th><th class="w-14">Complied With Gaps</th><th class="w-14">Reported Non Compliance</th><tr>';
        this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">' + total + '</td><td class="w-14 text-center td-odd">' + scheduled + '</td><td class="w-14 text-center td-odd">' + notComplied + '</td><td class="w-14 text-center td-odd">' + partiallyComplied + '</td><td class="w-14 text-center td-odd">' + complied + '</td><td class="w-14 text-center td-odd">' + compliedWithGaps + '</td><td class="w-14 text-center td-odd">' + reportedNonCompliance + '</td><tr></table>'
      }
    }

    return html;

  }

  renderStatistics = (_firstDay: any, _endDay: any, iInit: number, iLast: number, showGraph: boolean, index: number, month: number, period: string, firstDate: any = null, parametersTitle: string) => {
    var total = 0, notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0;
    let subfiltersTotal: any = {}
    let subfiltersNotStarted: any = {}
    let subfiltersPendingApproval: any = {}
    let subfiltersRejected: any = {}
    let subfiltersApproved: any = {}
    let finRiskCurrency = [];
    let finRiskMitigatedMin = [];
    let finRiskMitigatedMax = [];
    let finRiskResidualMin = [];
    let finRiskResidualMax = [];
    var html = '';

    // var lastDay = iLast;
    // var slice = 2;
    this.clearGraphData();
    console.log('this.clearSelectedGraphParam(); 2');
    this.clearSelectedGraphParam();
    this.clearSelectedLegend();

    html += this.renderCalendarStatisticsGraphs(showGraph, parametersTitle);
    html += this.renderCalendarContainerDivStart(index)
    html += this.renderCalendarEventSummaryViewer();
    let filtersTableHtml = ""
    this.statisticsFiltersCsv = []
    if (Object.keys(this.statisticsFiltersData).length > 0 && this.statisticsSelectedFilter != "all") {
      filtersTableHtml += this.renderStatisticsFiltersTableStart()
    }
    console.log('statistics', firstDate, iInit, iLast)
    for (var i = iInit; i <= iLast; i++) {

      let mmdd: string = "";

      if (firstDate == null) {
        mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
      } else {
        const currDate = new Date(firstDate.getTime());
        currDate.setDate(firstDate.getDate() + (i));
        mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
      }


      console.log('mmddevent', mmdd, this.statistics[mmdd], firstDate);

      // var hide;
      // if(firstDate == null) {
      //   hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, null);
      // } else {
      //   const currDate = new Date(firstDate.getTime());
      //   currDate.setDate(firstDate.getDate() + (i - 1));
      //   hide = this.getCalendarRowHide(this.events[mmdd], i, lastDay, month, firstDate, currDate);
      // }      

      if (this.statistics[mmdd] != null) {


        // html += this.renderCalendarRowDivStart(i, firstDate, mmdd.split("/")[1] + "/" + mmdd.split("/")[0]);
        total += this.statistics[mmdd].count;
        console.log('mmdd', mmdd, this.statistics[mmdd].count, total);
        notStarted += this.statistics[mmdd]["not-started"] ?? 0;
        pendingApproval += this.statistics[mmdd]["pending-approval"] ?? 0;
        rejected += this.statistics[mmdd]["rejected"] ?? 0;
        approved += this.statistics[mmdd]["approved"] ?? 0;
        if (Array.isArray(this.statistics[mmdd]['currency'])) {
          for (let [indexCurrSource, currency] of this.statistics[mmdd]['currency'].entries()) {
            if (finRiskCurrency.indexOf(currency) < 0) {
              finRiskCurrency.push(currency)
              finRiskMitigatedMax.push(0)
              finRiskMitigatedMin.push(0)
              finRiskResidualMax.push(0)
              finRiskResidualMin.push(0)
            }
            let indexCurr = finRiskCurrency.indexOf(currency)
            finRiskMitigatedMax[indexCurr] = finRiskMitigatedMax[indexCurr] + (this.statistics[mmdd]['mitigatedmax'][indexCurrSource] ?? 0)

            finRiskMitigatedMin[indexCurr] = finRiskMitigatedMin[indexCurr] + (this.statistics[mmdd]['mitigatedmin'][indexCurrSource] ?? 0)

            finRiskResidualMax[indexCurr] = finRiskResidualMax[indexCurr] + (this.statistics[mmdd]['residualmax'][indexCurrSource] ?? 0)

            finRiskResidualMin[indexCurr] = finRiskResidualMin[indexCurr] + (this.statistics[mmdd]['residualmin'][indexCurrSource] ?? 0)
          }
        }
        for (let subfilter of Object.keys(this.statistics['subfilters'])) {
          if (subfiltersTotal[subfilter] == null) {
            subfiltersTotal[subfilter] = 0
          }
          if (subfiltersNotStarted[subfilter] == null) {
            subfiltersNotStarted[subfilter] = 0
          }
          if (subfiltersPendingApproval[subfilter] == null) {
            subfiltersPendingApproval[subfilter] = 0
          }
          if (subfiltersRejected[subfilter] == null) {
            subfiltersRejected[subfilter] = 0
          }
          if (subfiltersApproved[subfilter] == null) {
            subfiltersApproved[subfilter] = 0
          }
          if (this.statistics['subfilters'][subfilter][mmdd] != null) {


            subfiltersTotal[subfilter] += (this.statistics['subfilters'][subfilter][mmdd].count)


            subfiltersNotStarted[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['not-started'] ?? 0)


            subfiltersPendingApproval[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['pending-approval'] ?? 0)


            subfiltersRejected[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['rejected'] ?? 0)


            subfiltersApproved[subfilter] += (this.statistics['subfilters'][subfilter][mmdd]['approved'] ?? 0)
          }
        }
      }
    }

    let tempObj: any = { 'Criteria': 'all' }

    tempObj['Total'] = total
    tempObj['Not Started'] = notStarted
    tempObj['Pending Approval'] = pendingApproval
    tempObj['Rejected'] = rejected
    tempObj['Approved'] = approved
    this.statisticsFiltersCsv.push(tempObj)
    if (Object.keys(this.statisticsFiltersData).length > 0 && this.statisticsSelectedFilter != "all") {

      let filtercriteria = Object.keys(this.statisticsFiltersData)[0]
      let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[filtercriteria])
      this.statisticsFiltersCsv = []
      finRiskCurrency = [];
      finRiskMitigatedMin = [];
      finRiskMitigatedMax = [];
      finRiskResidualMin = [];
      finRiskResidualMax = [];
      for (let [filterindex, filterval] of sortedFilters.entries()) {
        let filtername = filterval.split(';')[0]
        let filterid = filterval.split(';')[1]
        let filterTotal = 0, filterNotStarted = 0, filterPendingApproval = 0, filterRejected = 0, filterApproved = 0;
        let lastActive = "";
        let lastAction = "";
        let subfiltersFilterTotal: any = {}
        let subfiltersFilterNotStarted: any = {}
        let subfiltersFilterPendingApproval: any = {}
        let subfiltersFilterRejected: any = {}
        let subfiltersFilterApproved: any = {}
        if (this.statisticsFiltersCsv[filtername] == null) {
          this.statisticsFiltersCsv[filtername] = {}
        }
        for (var i = iInit; i <= iLast; i++) {

          let mmdd: string = "";

          if (firstDate == null) {
            mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
          } else {
            const currDate = new Date(firstDate.getTime());
            currDate.setDate(firstDate.getDate() + (i));
            mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
          }
          console.log('mmddFilters', mmdd)
          if (this.statisticsFiltersData[filtercriteria][filterid] != null) {
            if (this.statisticsFiltersData[filtercriteria][filterid]['lasttime'] != null) {
              lastAction = this.statisticsFiltersData[filtercriteria][filterid]['lasttime']['lastaction'] ?? ""
              lastActive = this.statisticsFiltersData[filtercriteria][filterid]['lasttime']['lastactive'] ?? ""
              this.statisticsFiltersCsv[filtername].lastaction = lastAction
              this.statisticsFiltersCsv[filtername].lastactive = lastActive
            }
            if (this.statisticsFiltersData[filtercriteria][filterid][mmdd] != null) {
              filterTotal += this.statisticsFiltersData[filtercriteria][filterid][mmdd].count
              filterNotStarted += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['not-started'] ?? 0
              filterPendingApproval += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['pending-approval'] ?? 0
              filterRejected += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['rejected'] ?? 0
              filterApproved += this.statisticsFiltersData[filtercriteria][filterid][mmdd]['approved'] ?? 0

              if (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['currency'] != null) {
                for (let [indexCurrSource, currency] of this.statisticsFiltersData[filtercriteria][filterid][mmdd]['currency'].entries()) {

                  if (finRiskCurrency.indexOf(currency) < 0) {
                    finRiskCurrency.push(currency)
                    finRiskMitigatedMax.push(0)
                    finRiskMitigatedMin.push(0)
                    finRiskResidualMax.push(0)
                    finRiskResidualMin.push(0)
                  }
                  let indexCurr = finRiskCurrency.indexOf(currency)

                  finRiskMitigatedMax[indexCurr] = finRiskMitigatedMax[indexCurr] + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['mitigatedmax'][indexCurrSource] ?? 0)


                  finRiskMitigatedMin[indexCurr] = finRiskMitigatedMin[indexCurr] + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['mitigatedmin'][indexCurrSource] ?? 0)

                  finRiskResidualMax[indexCurr] = finRiskResidualMax[indexCurr] + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['residualmax'][indexCurrSource] ?? 0)

                  finRiskResidualMin[indexCurr] = finRiskResidualMin[indexCurr] + (this.statisticsFiltersData[filtercriteria][filterid][mmdd]['residualmin'][indexCurrSource] ?? 0)
                }
              } else {
                console.log('financial risk currency data not found for filter', filtercriteria, filterid, mmdd)
              }

              for (let subfilter of Object.keys(this.statisticsFiltersData[filtercriteria][filterid]['subfilters'])) {
                if (subfiltersFilterTotal[subfilter] == null) {
                  subfiltersFilterTotal[subfilter] = 0
                }
                if (subfiltersFilterNotStarted[subfilter] == null) {
                  subfiltersFilterNotStarted[subfilter] = 0
                }
                if (subfiltersFilterPendingApproval[subfilter] == null) {
                  subfiltersFilterPendingApproval[subfilter] = 0
                }
                if (subfiltersFilterRejected[subfilter] == null) {
                  subfiltersFilterRejected[subfilter] = 0
                }
                if (subfiltersFilterApproved[subfilter] == null) {
                  subfiltersFilterApproved[subfilter] = 0
                }
                if (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd] != null) {

                  subfiltersFilterTotal[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd].count)
                  console.log('subfilterTotal', subfiltersFilterTotal);

                  subfiltersFilterNotStarted[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['not-started'] ?? 0)

                  subfiltersFilterPendingApproval[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['pending-approval'] ?? 0)

                  subfiltersFilterRejected[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['rejected'] ?? 0)

                  subfiltersFilterApproved[subfilter] += (this.statisticsFiltersData[filtercriteria][filterid]['subfilters'][subfilter][mmdd]['approved'] ?? 0)
                }
              }
            }
          }
        }
        let tempObj: any = { 'Criteria': filtercriteria.replace(/\"/g, ''), 'Name': filtername.replace(/\([^)]*\)/g, "").replace(/\"/g, '') }
        tempObj['Total'] = filterTotal
        tempObj['Not Started'] = filterNotStarted
        tempObj['Pending Approval'] = filterPendingApproval
        tempObj['Rejected'] = filterRejected
        tempObj['Approved'] = filterApproved
        this.statisticsFiltersCsv.push(tempObj)
        filtersTableHtml += this.renderStatisticsFiltersTableRow(filterindex, lastAction != "" || lastActive != "", filtercriteria == "location")
        if (filterindex % 2 == 0) {
          filtersTableHtml = filtersTableHtml.replace(/TD_BODY_CLASS/g, "td-light");
        } else {
          filtersTableHtml = filtersTableHtml.replace(/TD_BODY_CLASS/g, "td-dark");
        }
        filtersTableHtml = filtersTableHtml.replace("FILTER_CRITERIA_NAME", filtercriteria + "");
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_FILTER_NAME", (filtername + "").replace(/\([^)]*\)/g, ""));

        let filterTotalHtml = filterTotal + ""
        let filterNotStartedHtml = filterNotStarted + Util.percentageString(filterNotStarted, filterTotal)
        let filterPendingApprovalHtml = filterPendingApproval + Util.percentageString(filterPendingApproval, filterTotal)
        let filterRejectedHtml = filterRejected + Util.percentageString(filterRejected, filterTotal)
        let filterApprovedHtml = filterApproved + Util.percentageString(filterApproved, filterTotal)
        for (let subfilter of Object.keys(this.statisticsFiltersData[filtercriteria][filterid]['subfilters'])) {
          filterTotalHtml += `<br />${subfilter}: ${subfiltersFilterTotal[subfilter]}${Util.percentageString(subfiltersFilterTotal[subfilter], filterTotal)}`
          filterNotStartedHtml += `<br />${subfilter}: ${subfiltersFilterNotStarted[subfilter]}${Util.percentageString(subfiltersFilterNotStarted[subfilter], filterNotStarted)}`
          filterPendingApprovalHtml += `<br />${subfilter}: ${subfiltersFilterPendingApproval[subfilter]}${Util.percentageString(subfiltersFilterPendingApproval[subfilter], filterPendingApproval)}`
          filterRejectedHtml += `<br />${subfilter}: ${subfiltersFilterRejected[subfilter]}${Util.percentageString(subfiltersFilterRejected[subfilter], filterRejected)}`
          filterApprovedHtml += `<br />${subfilter}: ${subfiltersFilterApproved[subfilter]}${Util.percentageString(subfiltersFilterApproved[subfilter], filterApproved)}`
        }
        console.log('subfilterstotal', subfiltersFilterTotal)
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_TOTAL", filterTotalHtml);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_NOT_STARTED", filterNotStartedHtml);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_APPROVED", filterApprovedHtml);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_PENDING_APPROVAL", filterPendingApprovalHtml);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_REJECTED", filterRejectedHtml);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_LAST_ACTION", lastAction);
        filtersTableHtml = filtersTableHtml.replace("DASHBOARD_LAST_ACTIVE", lastActive);
      }
      filtersTableHtml += this.renderStatisticsFiltersTableEnd()
    }


    html += filtersTableHtml
    html += this.renderCalendarContainerDivEnd();
    //console.log('final risk severities', this.riskSeverityData);

    //this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear();
    this.period = period;
    //console.log('renderevents htmlcols', this.htmlDataCompliances);

    console.log('progress', this.period, total, notStarted, approved, this.statistics)

    let totalHtml = ""
    let notStartedHtml = ""
    let pendingApprovalHtml = ""
    let rejectedHtml = ""
    let approvedHtml = ""
    for (let subfilter of Object.keys(this.statistics['subfilters'])) {
      totalHtml += `<br />${subfilter}: ${subfiltersTotal[subfilter]}${Util.percentageString(subfiltersTotal[subfilter], total)}`
      notStartedHtml += `<br />${subfilter}: ${subfiltersNotStarted[subfilter]}${Util.percentageString(subfiltersNotStarted[subfilter], notStarted)}`
      pendingApprovalHtml += `<br />${subfilter}: ${subfiltersPendingApproval[subfilter]}${Util.percentageString(subfiltersPendingApproval[subfilter], pendingApproval)}`
      rejectedHtml += `<br />${subfilter}: ${subfiltersRejected[subfilter]}${Util.percentageString(subfiltersRejected[subfilter], rejected)}`
      approvedHtml += `<br />${subfilter}: ${subfiltersApproved[subfilter]}${Util.percentageString(subfiltersApproved[subfilter], approved)}`
    }

    let showFinRisk = false
    if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('notices') < 0 && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0 && finRiskCurrency.length > 0 && (finRiskResidualMin.length > 0 || finRiskMitigatedMin.length > 0 || finRiskResidualMax.length > 0 || finRiskMitigatedMax.length > 0)) {
      showFinRisk = true
    }
    html = html.replace("DASHBOARD_TOTAL", total + "");
    html = html.replace("DASHBOARD_TOTAL_SUBFILTER", totalHtml.replace('<br />', ''));
    html = html.replace("DASHBOARD_NOT_STARTED", notStarted + "");
    html = html.replace("DASHBOARD_NOT_STARTED_SUBFILTER", notStartedHtml.replace('<br />', ''));
    html = html.replace("DASHBOARD_APPROVED", approved + "");
    html = html.replace("DASHBOARD_APPROVED_SUBFILTER", approvedHtml.replace('<br />', ''));
    html = html.replace("DASHBOARD_PENDING_APPROVAL", pendingApproval + "");
    html = html.replace("DASHBOARD_PENDING_APPROVAL_SUBFILTER", pendingApprovalHtml.replace('<br />', ''));
    html = html.replace("DASHBOARD_REJECTED", rejected + "");
    html = html.replace("DASHBOARD_REJECTED_SUBFILTER", rejectedHtml.replace('<br />', ''));

    console.log('FinancialRisk :', finRiskCurrency, finRiskResidualMin, finRiskResidualMax, finRiskMitigatedMin, finRiskMitigatedMax);
    let finRiskTableHtml = `<div class="d-flex align-start justify-start w-100">
                              <div class="d-flex align-end" part="financial-risk-title-container">
                                <span part="financial-risk-title">Financial Risk</span>
                              </div>
                              <div class="d-flex flex-col align-start" part="financial-risk-table-container">`
    let finRiskTemplatehtml = `
          <div class="d-flex align-start justify-start w-100" part="financial-risk-table-row">
          <!-- Left Label -->
          <div class="d-flex align-end" part="financial-risk-title-container">
            <sup part="financial-risk-currency">FIN_RISK_CURRENCY</sup>
          </div>

          <!-- Lower (Residual / Pending Risk) -->
          <div class="d-flex align-end" part="financial-risk-section">
            <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Lower</div>
            <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
              <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MIN</span>
              </div>
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
              <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MIN</span>
              </div>
            </div>
          </div>

          <!-- Upper (Mitigated / Addressed Risk) -->
          <div class="d-flex align-end" part="financial-risk-section">
            <div part="financial-risk-section-label" style="font-weight:700;font-size:15px;color:#000;">Higher</div>
            <div part="financial-risk-table-container" class="d-flex align-center" style="gap:8px;">
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Addressed</span>
              <span part="financial-risk-table-table-row-value-addressed" style="font-weight:700;font-size:16px;color:#27ae60;">FIN_RISK_MITIGATED_MAX</span>
              </div>
              <div part="financial-risk-table-col" class="d-flex flex-col align-center">
              <span part="financial-risk-table-row-label" style="color:#555;font-weight:500;font-size:13px;">Pending</span>
              <span part="financial-risk-table-table-row-value-residual" style="font-weight:700;font-size:16px;color:#a0005a;">FIN_RISK_RESIDUAL_MAX</span>
              </div>
            </div>
          </div>
          </div>
        `


    for (let [indexCurrency, currency] of finRiskCurrency.entries()) {
      let finRiskCurrencyHtml = finRiskTemplatehtml.replace(/FIN_RISK_CURRENCY/g, currency)
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_MITIGATED_MIN/g, this.formatIndianNumber(finRiskMitigatedMin[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_MITIGATED_MAX/g, this.formatIndianNumber(finRiskMitigatedMax[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_RESIDUAL_MIN/g, this.formatIndianNumber(finRiskResidualMin[indexCurrency]))
      finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/FIN_RISK_RESIDUAL_MAX/g, this.formatIndianNumber(finRiskResidualMax[indexCurrency]))
      // if (indexCurrency > 0) {
      //   finRiskCurrencyHtml = finRiskCurrencyHtml.replace(/Financial Risk/g, '')
      // }
      finRiskTableHtml += finRiskCurrencyHtml
      // finRiskTableHtml += '<div class="d-flex w-100">' + finRiskCurrencyHtml + '</div>'
    }
    finRiskTableHtml += '</div></div>'
    html = html.replace("FIN_RISK_TABLE", finRiskTableHtml);
    // html = html.replace("FIN_RISK_CURRENCY", finRiskCurrency);
    // html = html.replace("FIN_RISK_RESIDUAL_MIN", this.formatIndianNumber(finRiskResidualMin));
    // html = html.replace("FIN_RISK_RESIDUAL_MAX", this.formatIndianNumber(finRiskResidualMax));
    // html = html.replace("FIN_RISK_MITIGATED_MIN", this.formatIndianNumber(finRiskMitigatedMin));
    // html = html.replace("FIN_RISK_MITIGATED_MAX", this.formatIndianNumber(finRiskMitigatedMax));
    html = html.replace("gone FIN_RISK_HIDE_CLASS", showFinRisk ? "d-flex" : "gone");

    this.htmlDataStats = 'Completeness<br /><br /><table class="w-100"><tr><th class="w-14">Total</th><th class="w-14">Not Started</th><th class="w-14">Approved</th><th class="w-14">Pending Approval</th><th class="w-14">Rejected</th><tr>';
    this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">' + total + totalHtml + '</td><td class="w-14 text-center td-odd">' + notStarted + notStartedHtml + '</td><td class="w-14 text-center td-odd">' + approved + approvedHtml + '</td><td class="w-14 text-center td-odd">' + pendingApproval + pendingApprovalHtml + '</td><td class="w-14 text-center td-odd">' + rejected + rejectedHtml + '</td></table>'
    if (Object.keys(this.statisticsFiltersData).length > 0) {
      this.htmlDataStats += '<br /><br />Report<br /><br />'
      this.htmlDataStats += filtersTableHtml
    }

    return html;
  }
  renderReporting = (event: any, mmddyyyy: any) => {

    let html = '';
    let completeness = this.getCompletenessStatus(event);
    let docs = event['documents'] == null ? [] : event['documents'];
    let approved = event['approved'] == null ? false : event['approved'];
    let dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion'];
    let percentage = event['percentage'] == null ? '100' : event['percentage'];
    let makercheckers = event['makercheckers'] == null ? [] : event['makercheckers'];
    let docsOptional = event['docs'] == null ? [] : event['docs'];
    let uploadGuidance = event['uploadguidance'] ?? 0
    this.reportedLocationsVals = (event['reportedlocations'] != null) ? (Util.isJSONParsable(event['reportedlocations']) ? JSON.parse(event['reportedlocations']) : [event['reportedlocations']]) : ['']
    console.log('reportedLocations found', this.reportedLocationsVals)
    console.log('rendering reporting', event, percentage, this.reportedLocationsVals)
    if (this.selectedItemIds.length > 0) {
      html += `<div class="d-flex justify-between ">
        <h4 class="m-0 bulk-upload-label" part="bulk-upload-label">${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected</h4>
      </div>`
    }
    if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) {
      if (event.comments.length > 0) {

        html += '<div class="d-flex justify-between m-20" part="list-report-results-title-container">';
        html += '<h3 part="results-title" class="m-0"><br />Approve Compliance</h3>';
        html += '</div>';
        html += '<div class="m-20" part="report-container">';
        html += '<div class="d-flex justify-between align-center">'
        html += '<button class="invisible" part="button">Save</button>'
        html += '<button id="button-uploader-submit-approve" class="button-submit" part="button">Save</button>'
        html += '</div>'

        if (this.myRole != this.TAB_FUNCTION_HEAD && docs.length > 0 && event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') {
          html += '<div class="m-20">';
          html += '<label part="input-label">Supporting Documents</label>';
          html += '<slot name="uploader"></slot>';
          html += '<div part="uploader-analysis-message" class="uploader-analysis-message mt-20">The analysis is running in the background. You can proceed further.</div>'
          html += '</div>';
        }

        html += '<div class="d-flex m-20 flex-col">';
        html += '<label part="input-label">Approver Comments*</label>';
        html += ('<input id="input-approver-comments" type="text" part="input" value="' + (event.approvercomments ?? "") + '"/><br />');
        if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') {
          html += '<label part="input-label">Date of Completion*</label>';
          html += '<input id="input-approver-doc" part="input" type="date" value="' + (dateOfCompletion == "" ? dateOfCompletion : new Date(parseInt(dateOfCompletion)).toISOString().substring(0, 10)) + '" disabled/><br />';
          html += '<div class="d-flex justify-start align-center flex-wrap max-width-100">';
          html += '<div class="d-flex flex-col flex-grow">';
          html += '<label part="input-label">Completion Percentage</label>';
          html += '<input id="input-reporter-percentage" part="input" type="number" value="' + percentage + '" max="100" min="0" step="1" disabled/><br />';
          html += '</div>'
          html += '<div class="d-flex flex-col flex-grow max-width-100">';
          html += '<div id="reporting-entity-container-0" class="reporting-entity-container d-flex flex-col flex-grow ml-20-m-0 hide max-width-100">';
          html += '<label part="input-label">Entity</label>';
          html += '<select id="input-reporter-entity-0" part="input" disabled></select>';
          html += '</div>'
          html += '<div id="reporting-location-container-0" class="reporting-location-container d-flex flex-col flex-grow ml-20-m-0 hide max-width-100">';
          html += '<label part="input-label">Location</label>';
          html += '<select id="input-reporter-location-0"  class="input-reporter-location" part="input" disabled></select>';
          html += '</div>'
          if (this.reportedLocationsVals.length > 1) {
            let indexLocation = 1;
            while (indexLocation < this.reportedLocationsVals.length) {
              html += '<div class="d-flex justify-start align-end flex-wrap max-width-100">';
              html += '<div id="reporting-entity-container-' + indexLocation + '" class="reporting-entity-container d-flex flex-col ml-20-m-0 hide max-width-100">';
              html += '<label part="input-label">Entity</label>';
              html += '<select id="input-reporter-entity-' + indexLocation + '" part="input"></select>';
              html += '</div>'
              html += '<div id="reporting-location-container-' + indexLocation + '" class="reporting-location-container d-flex flex-col flex-grow ml-20-m-0 hide max-width-100">';
              html += '<label part="input-label">Location</label>';
              html += '<select id="input-reporter-location-' + indexLocation + '"  class="input-reporter-location" part="input"></select>';
              html += '</div>'
              html += '<button id="button-reporter-location-add-' + indexLocation + '" part="button-icon-small" class="button-reporter-location-add material-icons ml-10 hide">remove</button><br /></div>'
              indexLocation++
            }
          }
          html += '</div>'
          html += '</div>'

        }
        html += '<div>'
        html += '<label part="input-label">Approve?*</label><br />';
        html += '<div class="mt-5">'
        html += '<input id="input-approve-yes" name="radio-approved" type="radio"/> Yes';
        html += '<input id="input-approve-no" name="radio-approved" type="radio" checked/> No';
        html += '</div>'
        if (event['reportformat'] != null && event['reportformat'].length > 0) {
          html += '<div id="report-format-container" class="report-format-container" part="report-format-container"><div class="box"></div></div>'
        } else if (event['customreporting'] != null && event['customreporting'].length > 0) {
          html += '<div id="report-format-container" class="report-format-container" part="report-format-container"><div class="box"></div></div>'
        }
        html += '</div>';
        html += '</div>';
        html += '</div>';

      }

    }

    if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {

      html += '<div class="d-flex justify-between m-20" part="list-report-results-title-container">';
      html += '<h3 part="results-title" class="m-0"><br />Report Compliance</h3>';
      html += '</div>';

      var showSubmissionSection = true;
      var showGoogleFormLink = false;

      if (event['form'] != null && event['form'].length > 5) {

        if (event['form'].indexOf('docs.google.com/forms') >= 0) {
          showSubmissionSection = false;
          if (!approved) {
            showGoogleFormLink = true;

          }
        }

      }

      if (showGoogleFormLink) {
        html += ('<div part="detail-summary-form" class="mt-20 pl-20 pr-20"><button part="button" onclick="window.open(\'' + event['form'] + (this.projectId + '_' + event.entityid + '_' + event.locationid + '_' + event['id'] + '_' + mmddyyyy) + '\',\'_blank\')">Submit Via Link</button></div>');
      }

      if (showSubmissionSection) {

        html += '<div class="m-20" part="report-container">';
        html += '<div class="d-flex justify-between align-center">'
        html += '<button class="invisible" part="button">Save</button>'
        html += '<button id="button-uploader-submit-report" class="button-submit" part="button">Save</button>'
        html += '</div>'

        html += '<div class="d-flex m-20 flex-col">';
        html += '<label part="input-label">Reporter Comments*</label>';
        html += '<input id="input-reporter-comments" type="text" part="input" value="' + (event.reportercomments ?? "") + '"/>'
        if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') {
          html += '<div part="reporting-suggestions-container" id="reporting-suggestions-container" class="mt-10 d-flex align-center">'
          for (let reportingSuggestion of this.reportingSuggestions) {
            html += `<div part="reporting-suggestion" class="reporting-suggestion mr-10">${reportingSuggestion}</div>`
          }
          html += '<button id="reporting-suggestions-more" part="button-icon" class="reporting-suggestion-more material-icons mr-10">chevron_right</button>'
          for (let reportingSuggestion of this.reportingSuggestionsNotApplicable) {
            html += `<div part="reporting-suggestion" class="reporting-suggestion hide mr-10">${reportingSuggestion}</div>`
          }
          html += '</div>';
          html += '<br />';

          html += '<label part="input-label">Date of Completion*</label>';
          html += '<input id="input-reporter-doc" part="input" type="date" value="' + (dateOfCompletion == "" ? dateOfCompletion : new Date(parseInt(dateOfCompletion)).toISOString().substring(0, 10)) + '" max="' + (new Date().toISOString().substring(0, 10)) + '"/><br />';
          html += '<div class="d-flex justify-start align-start flex-wrap">';
          html += '<div class="d-flex flex-col flex-grow max-width-100">';
          html += '<label part="input-label">Completion Percentage*</label>';
          html += '<input id="input-reporter-percentage" part="input" type="number" value="' + percentage + '" max="100" min="0" step="1"/>';
          html += '</div>'
          html += '<div class="d-flex flex-col max-width-100">';
          html += '<div class="d-flex justify-start align-end flex-wrap max-width-100">';
          html += '<div id="reporting-entity-container-0" class="reporting-entity-container d-flex flex-col ml-20-m-0 hide max-width-100">';
          html += '<label part="input-label">Entity</label>';
          html += '<select id="input-reporter-entity-0" part="input"></select>';
          html += '</div>'
          html += '<div id="reporting-location-container-0" class="reporting-location-container d-flex flex-col flex-grow ml-20-m-0 hide max-width-100">';
          html += '<label part="input-label">Location</label>';
          html += '<select id="input-reporter-location-0"  class="input-reporter-location" part="input"></select>';
          html += '</div>'
          html += '<button id="button-reporter-location-add-0" part="button-icon-small" class="button-reporter-location-add material-icons ml-10 hide">remove</button><br /></div>'
          if (this.reportedLocationsVals.length > 1) {
            let indexLocation = 1;
            while (indexLocation < this.reportedLocationsVals.length) {
              html += '<div class="d-flex justify-start align-end flex-wrap max-width-100">';
              html += '<div id="reporting-entity-container-' + indexLocation + '" class="reporting-entity-container d-flex flex-col ml-20-m-0 hide max-width-100">';
              html += '<label part="input-label">Entity</label>';
              html += '<select id="input-reporter-entity-' + indexLocation + '" part="input"></select>';
              html += '</div>'
              html += '<div id="reporting-location-container-' + indexLocation + '" class="reporting-location-container d-flex flex-col flex-grow ml-20-m-0 hide max-width-100">';
              html += '<label part="input-label">Location</label>';
              html += '<select id="input-reporter-location-' + indexLocation + '"  class="input-reporter-location" part="input"></select>';
              html += '</div>'
              html += '<button id="button-reporter-location-add-' + indexLocation + '" part="button-icon-small" class="button-reporter-location-add material-icons ml-10 hide">remove</button><br /></div>'
              indexLocation++
            }
          }
          html += '</div>'
          html += '</div>'
          html += '<div class="d-flex justify-end align-end mt-10" class="input-report-location-add-container">';
          html += '<button id="button-reporter-location-add-0" part="button-icon-small" class="button-reporter-location-add material-icons ml-10-m-0 hide">add</button><br /></div>'

          html += '<div part="input-reporter-percentage-message" class="input-reporter-percentage-message mb-20">For reporting full non-compliance, choose 0%. For reporting compliance with gaps, choose the appropriate % value.</div><br />'

          // if(docsOptional.length === 0) {
          html += '<label id="input-label-docs" part="input-label">Supporting Documents' + ((docsOptional.length > 0) ? '' : '*') + '</label>';


          html += '<slot name="uploader"></slot>';
          if (uploadGuidance == 1) {
            html += '<div id="upload-guidance-button" part="upload-guidance-button" class="d-flex button-icon-small align-center align-self-start mt-10"><span class="material-symbols-outlined">help</span>&nbsp;<span>Get Help</span></div>'
          } else if (uploadGuidance != 0) {
            html += '<div part="upload-guidance-content">'
            html += '<div part="detail-head" class="mb-5"><strong>Upload Guidance</strong></div>'
            html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event['uploadguidance'] + "").replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="150"></sf-i-elastic-text>';
            html += '</div>'
          }
          html += '<div id="uploader-optional-warning" part="uploader-optional-warning" class="uploader-optional-warning hide mt-20">Uploading supporting documents is highly recommended by FlaggGRC to ensure effective compliance monitoring.</div>'
          html += '<div part="uploader-analysis-message" class="uploader-analysis-message mt-20">The analysis is running in the background. You can proceed further.</div>'
        }
        // }
        html += '<br />';
        if (event['reportformat'] != null && event['reportformat'].length > 0) {
          html += '<div id="report-format-container" class="report-format-container" part="report-format-container"><div class="box"></div></div>'
        } else if (event['customreporting'] != null && event['customreporting'].length > 0) {
          html += '<div id="report-format-container" class="report-format-container" part="report-format-container"><div class="box"></div></div>'
        }
        html += '<br />';
        if (makercheckers.length > 0) {
          html += '<div part="td-head" class="td-head d-flex justify-center align-center"><span class="material-symbols-outlined">check_small</span><div>&nbsp;Auto-approve Enabled</div></div>';

          if (completeness == "pending-approval" && this.enableDeleteLatestReport) {
            html += '<div part="td-head" class="td-head d-flex justify-center align-center"><button class="mt-5" part="button" id="button-auto-approve">Auto Approve</button></div>';
          }
        }
        html += '</div>';
        html += '</div>';

      }

    }

    if (this.myRole == this.TAB_AUDITOR) {

      html += '<div class="d-flex justify-between m-20" part="list-report-results-title-container">';
      html += '<h3 part="results-title" class="m-0"><br />Audit Compliance</h3>';
      html += '</div>';
      html += '<div class="m-20" part="report-container">';
      html += '<div class="d-flex justify-between align-center">'
      html += '<button class="invisible" part="button">Save</button>'
      html += '<button id="button-uploader-submit-audit" class="button-submit" part="button">Save</button>'
      html += '</div>'

      html += '<div class="d-flex m-20 flex-col">';
      html += '<label part="input-label">Auditor Comments</label>';
      html += '<input id="input-auditor-comments" type="text" part="input" value=""/><br />';
      if (event.module != 'contract' && event.module != 'license' && event.module != 'rcmresource') {
        html += '<label part="input-label">Date of Completion</label>';
        html += '<input id="input-auditor-doc" part="input" type="date" value="' + (dateOfCompletion == "" ? dateOfCompletion : new Date(parseInt(dateOfCompletion)).toISOString().substring(0, 10)) + '" max="' + (new Date().toISOString().substring(0, 10)) + '" readonly/><br />';
        html += '<label part="input-label">Percentage</label>';
        html += '<input id="input-reporter-percentage" part="input" type="number" max="100" min="0" step="1" value="' + percentage + '" disabled/><br />';
        html += '<div part="input-reporter-percentage-message" class="input-reporter-percentage-message mb-20">For reporting full non-compliance, choose 0%. For reporting compliance with gaps, choose the appropriate % value.</div><br />'
      }
      html += '<div>'
      html += '<label part="input-label">Approve?</label><br />';
      html += '<div class="mt-5">'
      html += '<input id="input-approve-yes" name="radio-approved" type="radio" checked/> Yes';
      html += '<input id="input-approve-no" name="radio-approved" type="radio"/> No';
      html += '</div>'
      html += '</div>';
      html += '<br />';
      if (docs.length > 0) {
        html += '<label part="input-label">Supporting Documents</label>';
        html += '<slot name="uploader"></slot>';
        html += '<div part="uploader-analysis-message" class="uploader-analysis-message mt-20">The analysis is running in the background. You can proceed further.</div>'
      }
      html += '</div>';
      html += '</div>';

    }

    if (this.myRole == this.TAB_VIEWER) {

      html += '<div class="d-flex justify-between m-20" part="list-report-results-title-container">';
      html += '<h3 part="results-title" class="m-0"><br />View Compliance</h3>';
      html += '</div>';
      html += '<div class="m-20" part="report-container">';

      html += '<div class="d-flex m-20 flex-col">';
      html += '<div>'
      html += '<label part="input-label">Approve?</label><br />';
      html += '<div class="mt-5">'
      html += '<input id="input-approve-yes" name="radio-approved" type="radio" checked/> Yes';
      html += '<input id="input-approve-no" name="radio-approved" type="radio"/> No';
      html += '</div>'
      html += '</div>';
      html += '<br />';
      if (docs.length === 0) {
        html += '<label part="input-label">Supporting Documents</label>';
        html += '<slot name="uploader"></slot>';
        html += '<div part="uploader-analysis-message" class="uploader-analysis-message mt-20">The analysis is running in the background. You can proceed further.</div>'
      }
      html += '</div>';
      html += '</div>';
    }
    return html;
  }

  renderListReporting = async (listReportingContainer: HTMLDivElement, event: any, mmddyyyy: any, eventsContainer: HTMLDivElement) => {
    console.log('listreporting event', event, event.reportingnonenc);
    if (event.reportingnonenc) {
      await this.fetchEventDetails(event, mmddyyyy, null, eventsContainer, "", "", true, listReportingContainer, null, null, event.percentage, event.reportedlocations, null, event.dateofcompletion, false, true);
      return;
    }
    let html = ''
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]

    let reportformatName: string = '';
    if (event['reportformat'] != null) {
      reportformatName = (event['reportformat'][0] ?? "").trim().replace('&amp;', '&');
    }
    let docs = event['documents'] == null ? [] : event['documents'];
    event.approved = event['approved'] == null ? false : event['approved'];
    event.dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion'];
    event.makercheckers = event['makercheckers'] == null ? [] : event['makercheckers'];
    event.docsOptional = event['docs'] == null ? [] : event['docs'];
    html = this.renderReporting(event, mmddyyyy);
    console.log('reporting html', html);
    let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2];

    let emailcontent = `<table border="0" cellspacing="0" style="color:#666666;border-radius:5px;border:solid 1px #efefef;width:100%; margin-top:20px"><tbody><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Compliance ID</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.id}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Country</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.countryname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Entity</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.entityname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Location</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.locationname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Statute</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${(event.statute[0] ?? "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Subcategory</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.subcategory}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Reporter</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.reporters[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Approver</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.approvers[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Due Date</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${ddmmyyyy}</td></tr></tbody></table>`;

    let listReportingContainers = eventsContainer.querySelectorAll('.list-reporting-container') as NodeListOf<HTMLDivElement>
    for (let tempReportingContainer of listReportingContainers) {
      tempReportingContainer.style.display = 'none';
      tempReportingContainer.innerHTML = '';
    }

    listReportingContainer.style.display = 'flex';
    const id = listReportingContainer.id;
    const idArr = id.split("-")
    // const i = idArr[3];
    const j = idArr[5];
    let buttonListReportings = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
    for (let buttonListReporting of buttonListReportings) {
      if (buttonListReporting.id == 'button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') {
        console.log('buttonListReporting', buttonListReporting.id, 'button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-');
        buttonListReporting.setAttribute('part', 'button-list-reporting-selected')
      } else {
        buttonListReporting.setAttribute('part', 'button-list-reporting')
      }
    }
    let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
    for (let streamEventTitle of streamEventTitles) {
      if (streamEventTitle.id == 'stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + ((event.module ?? false) ? event.module : 'compliance') + '-') {
        streamEventTitle.setAttribute('part', 'stream-event-title-selected')
      } else {
        streamEventTitle.removeAttribute('part')
      }
    }
    listReportingContainer.innerHTML = html;
    if (this._SfUploader[0] != null) {
      (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.emailcontent = emailcontent;
    }

    (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.addEventListener('change', (e) => {
      let value = (e.target as HTMLInputElement).value;
      if (this.reportingSuggestionsNotApplicable.indexOf(value) >= 0) {
        console.log('suggestion matched', value);
        let uploadOptionalWarning = listReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement;
        uploadOptionalWarning.classList.remove('hide');
        let supportingDocumentsLabel = listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement;
        supportingDocumentsLabel.innerText = 'Supporting Documents';
      } else {
        let uploadOptionalWarning = listReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement;
        uploadOptionalWarning.classList.add('hide');
        let supportingDocumentsLabel = listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement;
        supportingDocumentsLabel.innerText = 'Supporting Documents' + (event.docsOptional.length > 0 ? '' : '*');
      }
    })
    let deleteButtons = listReportingContainer.querySelectorAll('.button-delete') as NodeListOf<HTMLButtonElement>
    for (let deleteButton of deleteButtons) {
      deleteButton?.addEventListener('click', async () => {

        await this.fetchDeleteReview(event["id"], mmddyyyy, event.entityid, event.locationid);
        this.setSuccess('Deleted successfully!')
        setTimeout(() => {
          this.clearMessages()
        }, 3000);
        //console.log('deleted', resultDelete);
        if (this.getCurrentTab() == this.TAB_CUSTOM) {
          this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
        } else {
          // if(currentColumnButton != null) {
          //   currentColumnButton.click();
          // }
        }

      });
    }
    listReportingContainer.querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length <= 1) {
        await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
        this.setSuccess('Auto-Approved successfully!')
        setTimeout(() => {
          this.clearMessages()
        }, 3000);
      } else {
        let bulkBodyReview = []
        for (var k = 0; k < this.selectedItemIds.length; k++) {

          const selectedId = this.selectedItemIds[k];
          //console.log('selectedid', selectedId);
          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

          //console.log(entityId, locationId, eventId, mmddyyyy);
          let yearStr = this.getFinancialYear(mmddyyyy)
          bulkBodyReview.push({
            "mmddyyyy": mmddyyyy,
            "projectid": this.projectId,
            "type": "review",
            "eventid": eventId,
            "comments": "Auto approved",
            "approved": true,
            "entityid": entityId,
            "locationid": locationId,
            "username": this.userName,
            "userid": this.userProfileId,
            "userrole": this.myRole,
            "year": yearStr,
            "module": event.module ?? "compliance"
          })
        }
        await this.uploadReviewsBulk(bulkBodyReview);
      }
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

    });
    listReportingContainer.querySelector('#upload-guidance-button')?.addEventListener('click', async () => {
      console.log('upload guidance clicked', event);
      let inputReportingPercentage = (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement)?.value ?? "100";
      let selectReportedLocations = (listReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf<HTMLSelectElement>);
      let selectReportedLocationValue = "[]";
      for (let selectReportedLocation of selectReportedLocations) {
        selectReportedLocationValue = JSON.stringify([...JSON.parse(selectReportedLocationValue), selectReportedLocation.value])
      }
      let approvercomments = (listReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement)?.value ?? "";
      let reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.value ?? "";
      let dateOfCompletion;
      if ((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement) != null) {
        dateOfCompletion = new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "";
      } else {
        dateOfCompletion = new Date((listReportingContainer.querySelector('#input-approver-doc') as HTMLInputElement).value).getTime() + "";
      }
      let documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader).selectedValues()
      if (dateOfCompletion == "NaN") {
        dateOfCompletion = "";
      }
      console.log('dateOfCompletion', dateOfCompletion)
      await this.fetchEventDetails(event, mmddyyyy, null, eventsContainer, "", "", true, listReportingContainer, reportercomments, approvercomments, inputReportingPercentage, selectReportedLocationValue, documents, dateOfCompletion);
    })
    if (this.mode == "consumer" || this.mode == "next") {
      let reportingSuggestionMoreButton = listReportingContainer.querySelector('#reporting-suggestions-more') as HTMLButtonElement;
      reportingSuggestionMoreButton?.addEventListener('click', (e) => {
        (e.target as HTMLButtonElement).style.display = 'none';
        let reportingSuggestions = listReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf<HTMLDivElement>;
        reportingSuggestions.forEach(suggestion => {
          suggestion.classList.remove('hide');
        })
      })
      let reportingSuggestionButtons = listReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf<HTMLDivElement>;
      for (let reportingSuggestionButton of reportingSuggestionButtons) {
        reportingSuggestionButton.addEventListener('click', (e) => {
          let button = e.currentTarget as HTMLDivElement;
          (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value = ((listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value + " " + button.innerHTML).trim();
          (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).dispatchEvent(new Event('change', { bubbles: true }));
        })
      }

      let inputReportingPercentage = listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement;
      let percentage = inputReportingPercentage?.value ?? 0
      const entityContainers = listReportingContainer.querySelectorAll('.reporting-entity-container') as NodeListOf<HTMLDivElement>;
      const locationsContainers = listReportingContainer.querySelectorAll('.reporting-location-container') as NodeListOf<HTMLDivElement>;
      const addLocationButtons = listReportingContainer.querySelectorAll('.button-reporter-location-add') as NodeListOf<HTMLButtonElement>;
      if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) {
        entityContainers.forEach(container => container.classList.remove('hide'));
        locationsContainers.forEach(container => container.classList.remove('hide'));
        addLocationButtons.forEach(container => container.classList.remove('hide'));
      } else {
        entityContainers.forEach(container => container.classList.add('hide'));
        locationsContainers.forEach(container => container.classList.add('hide'));
        addLocationButtons.forEach(container => container.classList.add('hide'));
      }
      inputReportingPercentage?.addEventListener('change', () => {
        setTimeout(() => {
          let percentage = inputReportingPercentage.value
          console.log('percentage', percentage, inputReportingPercentage, inputReportingPercentage.value, event.reportedlocations);
          if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) {
            entityContainers.forEach(container => container.classList.remove('hide'));
            locationsContainers.forEach(container => container.classList.remove('hide'));
            addLocationButtons.forEach(container => container.classList.remove('hide'));
          } else {
            entityContainers.forEach(container => container.classList.add('hide'));
            locationsContainers.forEach(container => container.classList.add('hide'));
            addLocationButtons.forEach(container => container.classList.add('hide'));
          }
          if ((percentage != null && parseInt(percentage) == 0) || event.docsOptional.length > 0) {
            (listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents';
          } else {
            (listReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents*';
          }
          if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100 && (event.reportedlocations == "" || event.reportedlocations == "[]")) {
            event.percentage = percentage
            event.reportedlocations = JSON.stringify([""])
            event.reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;
            event.dateofcompletion = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
            event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
            console.log('rendering list reporting', event.percentage, event.reportedlocations)
            this.renderListReporting(listReportingContainer, event, mmddyyyy, eventsContainer);
          }
        }, 200);
      })
      let projectUserMap = Util.getProjectUsermap()
      addLocationButtons.forEach((addLocationBtn) => {
        addLocationBtn.addEventListener('click', () => {
          let iconhtml = addLocationBtn.innerHTML
          let index = parseInt(addLocationBtn.id.split('-')[4])
          console.log('button clicked', iconhtml, addLocationBtn.id);
          if (iconhtml == "add") {
            console.log('this.reportedLocationsVals', this.reportedLocationsVals)
            this.reportedLocationsVals.push("");
          } else {
            this.reportedLocationsVals.splice(index, 1);
          }
          event.percentage = inputReportingPercentage.value;
          event.reportedlocations = JSON.stringify(this.reportedLocationsVals)
          if (this.reportedLocationsVals.length == 0) {
            event.percentage = "100";
          }
          console.log('rendering list reporting', event.percentage, event.reportedlocations)
          event.reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;
          event.dateofcompletion = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
          event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
          this.renderListReporting(listReportingContainer, event, mmddyyyy, eventsContainer);
        })
      })

      for (let indexRepLoc = 0; indexRepLoc < this.reportedLocationsVals.length; indexRepLoc++) {
        console.log('AddingEntities', indexRepLoc)
        let selectReportingEntity = listReportingContainer.querySelector('#input-reporter-entity-' + indexRepLoc) as HTMLSelectElement;
        let selectReportingLocation = listReportingContainer.querySelector('#input-reporter-location-' + indexRepLoc) as HTMLSelectElement;
        if (selectReportingEntity != null && selectReportingLocation != null) {
          selectReportingEntity.innerHTML = '';
          let defaultOption = new Option("Select Location", "", true, true)
          defaultOption.disabled = true
          selectReportingEntity.add(defaultOption)
          for (let country of Object.keys(projectUserMap)) {
            if (country == "roles") {
              continue;
            }
            for (let entity of Object.keys(projectUserMap[country])) {
              let entityName = entity.split(';')[0].replace(/ *\([^)]*\) */g, "")
              let option = new Option(entityName, entity)
              selectReportingEntity.add(option);
            }
          }
          selectReportingEntity.addEventListener('change', (e: any) => {
            selectReportingLocation.innerHTML = ''
            let defaultOption = new Option("Select Location", "", true, true)
            defaultOption.disabled = true
            selectReportingLocation.add(defaultOption)
            for (let country of Object.keys(projectUserMap)) {
              if (country == "roles") {
                continue;
              }
              for (let entity of Object.keys(projectUserMap[country])) {
                if (entity.indexOf(e.target.value) < 0) {
                  continue;
                }
                for (let location of Object.keys(projectUserMap[country][entity])) {
                  let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "")
                  let option = new Option(locationName, location)
                  selectReportingLocation.add(option);
                }
              }
            }
            (listReportingContainer.querySelector('#reporting-location-container-' + indexRepLoc) as HTMLDivElement).classList.remove('hide')
            selectReportingLocation.value = event.reportedlocations != null ? (Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations) : "";
          })


          if (selectReportingLocation.innerHTML == '') {
            let defaultOption = new Option("Select Location", "", true, true)
            defaultOption.disabled = true
            selectReportingLocation.add(defaultOption)
            // for (let country of Object.keys(projectUserMap)) {
            //   if (country == "roles") {
            //     continue;
            //   }
            //   for (let entity of Object.keys(projectUserMap[country])) {
            //     for (let location of Object.keys(projectUserMap[country][entity])) {
            //       let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "")
            //       let option = new Option(locationName, location)
            //       selectReportingLocation.add(option);
            //       break;
            //     }
            //     break;
            //   }
            //   break;
            // }
          }
          selectReportingLocation.addEventListener('change', (e: any) => {
            if (selectReportingEntity.value == "") {
              return;
            }
            let index = parseInt(e.target.id.split('-')[3])
            this.reportedLocationsVals[index] = e.target.value
          })

          if (event.reportedlocations != null && event.reportedlocations.length > 0) {
            console.log('setting reportedlocations', event.reportedlocations)
            let tempReportedLocation = Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations
            for (let country of Object.keys(projectUserMap)) {
              if (country == "roles") {
                continue;
              }
              for (let entity of Object.keys(projectUserMap[country])) {
                let flagSetVal = false;
                for (let location of Object.keys(projectUserMap[country][entity])) {
                  if (tempReportedLocation.indexOf(location) >= 0) {
                    selectReportingEntity.value = entity;
                    const changeEvent = new Event('change', { bubbles: true });
                    selectReportingEntity.dispatchEvent(changeEvent)
                    selectReportingLocation.value = location;
                    flagSetVal = true;
                    break;
                  }
                }
                if (flagSetVal) {
                  break;
                }
              }
            }
          } else {
            selectReportingEntity.value = "";
            selectReportingLocation.value = "";
          }
        }
      }

      listReportingContainer.querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = (listReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement).value;
        console.log('comments', comments, JSON.stringify(event.comments))
        const approved = (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(event);
        let newEvent = { ...event };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('selectedevent', JSON.stringify(event));
          if (await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) {
            if (this.mode == "next") {
              for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) {
                  this.nextEvents[this.nextTabRole][mmdd][p].approved = approved
                  console.log('selected event', this.nextEvents[this.nextTabRole][mmdd][p]);
                  this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString()
                  if (approved) {
                    this.nextEvents[this.nextTabRole][mmdd][p].dateofcompletion = new Date().getTime() + ""
                  }
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                }
              }
            } else {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                  this.events[mmdd][p].approved = approved
                  console.log('selected event', this.events[mmdd][p]);
                  this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                  if (approved) {
                    this.events[mmdd][p].dateofcompletion = new Date().getTime() + ""
                  }
                }
              }

              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(event)
            }
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            let entityid = selectedId.split('-')[7].replace(/_/g, '-');
            let locationid = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityid,
              "locationid": locationid,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": event.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            let entityid = selectedId.split('-')[7].replace(/_/g, '-');
            let locationid = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            if (this.mode == "next") {
              for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityid) {
                  flagBulk = true;
                  this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                }
              }
            } else {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationid && this.events[mmdd][p].entityid == entityid) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }
          }
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          // this.renderRoleTabsNext(this.nextPage)
          this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            console.log('events', this.events);
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
          }
        }

      });

      listReportingContainer.querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = (listReportingContainer.querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked;

        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {
            if (await this.uploadAudit(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                  if (approved) {
                    this.events[mmdd][p].dateofcompletion = new Date().getTime() + ""
                  }
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(event)
            }
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": event.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              if (this.mode == "next") {
                for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                  if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) {
                    flagBulk = true;
                    this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                  }
                }
              } else {
                for (var p = 0; p < this.events[mmdd].length; p++) {
                  if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                    this.events[mmdd][p].isbulk = true
                    flagBulk = true;
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(this.events[mmdd][p])
                  }
                }
              }
            }
          }
          if (this.mode == "next") {
            // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
            this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {
        if (event.approved) {

          if ((listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            (listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }


        } else {

          if ((listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            (listReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            listReportingContainer.querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = (listReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              const reporterdoc = (listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((listReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);

              // if(docsOptional.length === 0) {
              let percentage: string = "100";
              if ((listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }
              docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }
              let flag = false;
              do {
                if (docs.length > 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments.trim().toLowerCase()) < 0) {
                  for (let doc of docs) {
                    if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) {
                      flag = false
                    } else {
                      flag = true;
                    }
                  }
                } else {
                  flag = true;
                }
                if (flag === false) {
                  await this.sleep(1000);
                  console.log('waiting for docs', docs);
                  docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
                }
              } while (flag === false);
              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (this._SfReporting[0] != null) {
                reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? "";
                reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? "";
              }

              console.log('percentage', percentage, (listReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value);
              if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) {

                //console.log('reporter comments 3', reportercomments);
                buttonClick.innerHTML = "Save"
                this.setError('Invalid Percentage!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {
                if (docs.length == 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments.trim()) < 0) {

                  //console.log('reporter comments 3', reportercomments);
                  buttonClick.innerHTML = "Save"
                  this.setError('No documents uploaded!');
                  setTimeout(() => {
                    this.clearMessages();
                  }, 3000);

                } else {

                  //console.log('reporterdoc', reporterdoc);

                  if (reporterdoc.length === 0) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion not selected!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else if ((new Date(mmddyyyy).getTime() - (this.reportingLimitDays * 24 * 60 * 60 * 1000)) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError(`Reporting allowed only within ${this.reportingLimitDays} days before due date`);
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);
                  } else if ((new Date(mmddyyyy).getTime() - (this.reportingLimitDays * 24 * 60 * 60 * 1000)) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError(`Reporting allowed only within ${this.reportingLimitDays} days before due date`);
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);
                  } else if (parseInt(reporterdoc) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion cannot be in future!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else {

                    //console.log('makerscheckers 1', reportercomments);

                    if (reportercomments.trim().length === 0) {
                      buttonClick.innerHTML = "Save"
                      this.setError('Comments cannot be blank!');
                      setTimeout(() => {
                        this.clearMessages();
                      }, 3000);

                    } else {
                      let flagBulk = false;
                      // let reportedlocations = selectReportingLocation?.value ?? "";
                      let reportedlocations = "[]";
                      if (parseInt(percentage) !== 100) {
                        let selectReportedLocations = (listReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf<HTMLSelectElement>);
                        for (let selectReportedLocation of selectReportedLocations) {
                          reportedlocations = JSON.stringify([...JSON.parse(reportedlocations), selectReportedLocation.value])
                        }
                      }
                      if (this.selectedItemIds.length <= 1) {

                        if (await this.uploadReport(event.entityid, event.locationid, mmddyyyy, event["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, event.module ?? "compliance", percentage, event.makercheckers, reportedlocations)) {

                          if (this.mode != "next") {
                            for (var p = 0; p < this.events[mmdd].length; p++) {
                              if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                                this.events[mmdd][p].documents = docs
                                this.events[mmdd][p].percentage = percentage
                                this.events[mmdd][p].reportedlocations = reportedlocations
                                this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                                this.events[mmdd][p].lastupdated = new Date().toString()
                              }
                            }

                            if (event.makercheckers.length > 0) {

                              // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
                              for (var p = 0; p < this.events[mmdd].length; p++) {
                                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                                  this.events[mmdd][p].approved = true
                                  // this.events[mmdd][p].documents = docs
                                  this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                                  this.events[mmdd][p].lastupdated = new Date().toString()
                                }
                              }
                            }
                            if (this.recentlyReported[mmdd] == null) {
                              this.recentlyReported[mmdd] = []
                            }
                            this.recentlyReported[mmdd].push(event)
                            console.log('recently reported', this.recentlyReported)
                          } else {
                            for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                              if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) {
                                this.nextEvents[this.nextTabRole][mmdd][p].documents = docs
                                this.nextEvents[this.nextTabRole][mmdd][p].percentage = percentage
                                this.nextEvents[this.nextTabRole][mmdd][p].reportedlocations = reportedlocations
                                this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                                this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString()
                              }
                            }

                            if (event.makercheckers.length > 0) {

                              // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
                              for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                                if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) {
                                  this.nextEvents[this.nextTabRole][mmdd][p].approved = true
                                  // this.events[mmdd][p].documents = docs
                                  this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                                  this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString()
                                }
                              }
                            }
                            if (this.recentlyReported[mmdd] == null) {
                              this.recentlyReported[mmdd] = []
                            }
                            this.recentlyReported[mmdd].push(event)
                            console.log('recently reported', this.recentlyReported)
                          }
                        }
                      } else {
                        let bulkBody = []
                        let bulkBodyReview = []
                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);

                          const makercheckersL = selectedId.split('-')[5];
                          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                          //console.log(entityId, locationId, eventId, mmddyyyy);

                          // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null)
                          // if(parseInt(makercheckersL) > 0) {
                          //   bulkBodyReview.push({ 
                          //     "mmddyyyy": mmddyyyy,
                          //     "projectid": this.projectId, 
                          //     "type": "report",
                          //     "eventid": eventId,
                          //     "comments": reportercomments,
                          //     "dateofcompletion": reporterdoc,
                          //     "percentage": percentage,
                          //     "entityid": entityId,
                          //     "locationid": locationId,
                          //     "event": null,
                          //     "docs": JSON.stringify(docs),
                          //     "approved": true,
                          //     "username": this.userName,
                          //     "reportformatvalues": reportformatvalues,
                          //     "reportformatschema": reportformatschema,
                          //     "userid": this.userProfileId,
                          //     "userrole": this.myRole,
                          //     "year": this.calendarStartYYYY,
                          //     "module": event.module ?? "compliance"
                          //   } )
                          //   // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true);

                          // }else{
                          let yearStr = this.getFinancialYear(mmddyyyy)
                          bulkBody.push({
                            "mmddyyyy": mmddyyyy,
                            "projectid": this.projectId,
                            "type": "report",
                            "eventid": eventId,
                            "comments": reportercomments,
                            "dateofcompletion": reporterdoc,
                            "percentage": percentage,
                            "reportedlocations": reportedlocations,
                            "entityid": entityId,
                            "locationid": locationId,
                            "event": null,
                            "docs": JSON.stringify(docs),
                            "username": this.userName,
                            "reportformatvalues": reportformatvalues,
                            "reportformatschema": reportformatschema,
                            "userid": this.userProfileId,
                            "userrole": this.myRole,
                            "year": yearStr,
                            "module": event.module ?? "compliance",
                            "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                          })
                          // }

                          // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
                          // await this.sleep(2000);
                          // this.clearMessages();

                        }
                        // await this.uploadReportsBulk(bulkBody);

                        // await this.fetchBulkReportingData();
                        if (bulkBody.length > 0) {
                          await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                        }

                        // if(bulkBodyReview.length > 0){
                        //   await this.uploadReportsReviewsBulk(bulkBodyReview)
                        // }
                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);
                          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                          let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                          if (this.mode == "next") {
                            for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                              if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) {
                                flagBulk = true;
                                this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                                if (this.recentlyReported[mmdd] == null) {
                                  this.recentlyReported[mmdd] = []
                                }
                                this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                              }
                            }
                          } else {
                            for (var p = 0; p < this.events[mmdd].length; p++) {
                              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                                flagBulk = true;
                                this.events[mmdd][p].isbulk = true
                                if (this.recentlyReported[mmdd] == null) {
                                  this.recentlyReported[mmdd] = []
                                }
                                this.recentlyReported[mmdd].push(this.events[mmdd][p])
                              }
                            }
                          }
                        }
                      }

                      if (this.mode == "next") {
                        // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                        this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
                      } else {
                        // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                        //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                        // } else 
                        if (this.getCurrentTab() == this.TAB_FIND) {
                          const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                          this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                        } else {
                          if (this.selectedItemIds.length > 0) {
                            await this.fetchBulkReportingData();
                          }
                          this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                          // if(currentColumnButton != null) {
                          //   currentColumnButton.click();
                          // }
                        }
                      }
                    }
                  }
                }
              }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
          (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        }
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);

          if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
            (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
          }
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          if ((listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
            (listReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
          }
        });


        //console.log('documentType checking', documentType);

        if (event.documenttype != null) {
          if (Array.isArray(event.documenttype)) {
            (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype[0] ?? "";
          } else {
            (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype;
          }
        } else if (event.documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documentType;
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = "";
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = 0;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = docs.length;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || event.approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: event.entityid,
          locationId: event.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: event['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        console.log('uploader prepopulate', (this._SfUploader[0].querySelector('#uploader') as SfIUploader).prepopulatedInputArr, (this._SfUploader[0].querySelector('#uploader') as SfIUploader).extract)

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (event["approved"] != null) {
          if (event["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if ((listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
              (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if ((listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
              (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement != null) {
            (listReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if ((listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
            (listReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }
        }
      }
    }
    if (event['reportformat'] != null && event['reportformat'].length > 0) {
      this.fetchReportFormat(listReportingContainer, reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? "");
    }
  }

  attachListReportingListeners = (eventsContainer: HTMLDivElement) => {
    let buttonListReports = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
    for (let buttonListReport of buttonListReports) {
      buttonListReport?.addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        // const i = idArr[5];
        const j = idArr[5];
        let listReportingContainer = eventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement
        // console.log('mmddyyyy', this.events[mmdd][j], listReportingContainer, '#list-reporting-container-'+mmdd.replace(/\//g,'-')+'-'+j);
        if (listReportingContainer.style.display == 'none' || listReportingContainer.style.display == '') {
          this.renderListReporting(listReportingContainer, this.events[mmdd][j], mmdd + '/' + yyyy, eventsContainer)
        } else {
          listReportingContainer.innerHTML = '';
          listReportingContainer.style.display = 'none';
          ev.target.setAttribute('part', 'button-list-reporting')
          let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
          for (let streamEventTitle of streamEventTitles) {
            streamEventTitle.removeAttribute('part')
          }
        }
        // console.log('part', ev.target.getAttribute('part'));
      })
    }
  }

  attachReviewListeners = (eventsContainer: HTMLDivElement) => {
    let buttonReviews = eventsContainer.querySelectorAll('.button-icon-review') as NodeListOf<HTMLButtonElement>
    for (let buttonReview of buttonReviews) {
      buttonReview?.addEventListener('click', async (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        // const i = idArr[5];
        const j = idArr[5];
        console.log('review clicked', mmdd, yyyy, j, this.events[mmdd][j], ev.target.checked);
        let eventKey = this.events[mmdd][j].entityid + ';' + this.events[mmdd][j].locationid + ';' + this.events[mmdd][j].id;
        for (var p = 0; p < Object.keys(this.events).length; p++) {
          let tempMmDd = Object.keys(this.events)[p];
          for (var q = 0; q < this.events[tempMmDd].length; q++) {
            let tempEventKey = this.events[tempMmDd][q].entityid + ';' + this.events[tempMmDd][q].locationid + ';' + this.events[tempMmDd][q].id;
            if (tempEventKey == eventKey) {
              this.events[tempMmDd][q].review = ev.target.innerHTML.indexOf('flag_check') < 0
            }
          }
        }
        this.markReviewed(eventKey, yyyy, ev.target.innerHTML.indexOf('flag_check') < 0);
        this.renderAppropriateStream(this.sdate, this.edate, true);
      })
    }
  }

  renderStreamEvents = (index: number, month: number, year: number, showGraph: boolean = true, showBackgroundButton: boolean = false) => {

    //console.log('flowgraph renderStreamEvents', this.flowGraph);

    const lastDay = this.getLastDayOfMonth(month, year);
    let firstDay = new Date(year, month, 1);
    let endDay = new Date(year, month, 1);
    endDay?.setDate(endDay.getDate() + lastDay + 1);
    var period = ("0" + (month + 1)).slice(-2) + "/" + ("0" + 1).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (month + 1)).slice(-2) + "/" + ("0" + lastDay).slice(-2) + '/' + firstDay.getFullYear()

    return this.renderEvents(firstDay, endDay, 1, lastDay, showGraph, index, month, period, null, this.monthNames[month] + " " + year, showBackgroundButton);

  }

  renderThisEvents = (index: number, startDate: Date, showGraph: boolean = true, showBackgroundButton: boolean = false) => {

    var firstDate = new Date();
    var count = 7;

    //console.log('this start date', startDate);

    if (index === 0) {

      firstDate = (this.getFirstDateOfWeek(startDate) as Date);
      console.log('this first date', firstDate);
      count = 7;

    }

    if (index === 1) {

      firstDate = new Date(startDate.getFullYear(), startDate.getMonth(), 1);
      count = this.getLastDayOfMonth(startDate.getMonth(), startDate.getFullYear());
      //console.log('last day of month', count);

    }

    const lastDay = count;
    let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    endDay?.setDate(endDay.getDate() + lastDay + 1);

    var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + 1).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + count).slice(-2) + '/' + endDay.getFullYear()

    return this.renderEvents(firstDay, endDay, 1, lastDay, showGraph, index, (firstDate.getMonth()), period, null, "This " + (index === 0 ? "Week" : "Month"), showBackgroundButton);

  }

  renderRangeEvents = (firstDate: Date, count: number, eventsContainer: HTMLDivElement, showBackgroundButton: boolean = false) => {

    console.log('render range events called', firstDate, count)
    var lastDate = new Date(firstDate.getTime());
    lastDate.setDate(lastDate.getDate() + count - 1)

    const lastDay = count;
    let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    endDay?.setDate(endDay.getDate() + lastDay);
    console.log('firstday', firstDay, endDay)
    var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDay.getDate()).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear();

    console.log('rangeperiod', period, lastDay);

    var html = this.renderEvents(firstDay, endDay, 0, lastDay, true, 0, (firstDate.getMonth()), period, firstDate, "From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), showBackgroundButton);

    eventsContainer.querySelector('.calendar-right-data')!.innerHTML = html;
    if (eventsContainer.innerHTML.indexOf('button-select-all') < 0) {
      eventsContainer.insertAdjacentHTML('beforeend', this.renderSelectAllButtons());
    }
    this.renderButtonRefresh(eventsContainer);
    this.attachTimelineFilterHandlers(eventsContainer);
    let backgroundProcessButton = eventsContainer.querySelector('#button-background-process') as HTMLButtonElement
    if (showBackgroundButton) {
      backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none'
      console.log('backgroundprocessbutton', backgroundProcessButton.style.display);
      if (showBackgroundButton) {
        backgroundProcessButton.addEventListener('click', () => {
          console.log('bulk-progress clicked')
          let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement
          bulkLoader.scrollIntoView();
        })
      }
    }
    const filterButton = eventsContainer.querySelector('#filter-button') as HTMLButtonElement
    filterButton?.addEventListener('click', () => {
      const filterList = eventsContainer.querySelector('#filter-list-container') as HTMLDivElement
      filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none')
      filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close')
      const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement
      filterSubmitButton.addEventListener('click', () => {
        Util.setFeatures(this.selectedFeatures);
        this.enableCustom();
        this.renderTabs(this.selectedTab);
        // this.processDateSelection(eventsContainer);
        if (this.myRole == this.TAB_VIEWER) {
          this.renderCustomViewer()
        } else {
          this.renderCustom();
        }
      })
      // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement
      // selectFeatureAll.addEventListener('click',async(ev: any) => {
      //   let target = ev.target;
      //   if(target.checked){
      //     for(let feature of this.getFeatures()){
      //       if(this.selectedFeatures.indexOf(feature) < 0){
      //         this.selectedFeatures.push(feature);
      //       }
      //     }
      //   }else{
      //     this.selectedFeatures = []
      //   }
      //   const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      //   for(let selectFeature of selectFeatures){
      //     let id = selectFeature.id;
      //     let i = id.split('-')[3];
      //     let selectedFeature = this.getFeatures()[parseInt(i)]
      //     selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0
      //   }
      //   filterSubmitButton.style.visibility = 'visible'
      // })
      // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement
      // selectFeatureAllLabel.addEventListener('click',()=>{
      //   selectFeatureAll.checked = !selectFeatureAll.checked
      //   selectFeatureAll.click();
      // })
      const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf<HTMLLabelElement>
      for (let [i, selectFeature] of selectFeatures.entries()) {
        selectFeature.addEventListener('click', (ev: any) => {
          let target = ev.target;
          let id = target.id;
          let index = id.split('-')[3];
          let selectedFeature = this.getFeatures()[index]
          if (target.checked) {
            if (this.selectedFeatures.indexOf(selectedFeature) < 0) {
              // this.selectedFeatures.push(selectedFeature)
              this.selectedFeatures = [selectedFeature]
            }
          }
          // else{
          //   // selectFeatureAll.checked = false;
          //   if(this.selectedFeatures.indexOf(selectedFeature) >= 0){
          //     this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1);
          //   }
          // }
          // filterSubmitButton.style.visibility = 'visible'
          filterSubmitButton.click();
        })
        selectFeatureLabels[i].addEventListener('click', () => {
          selectFeature.checked = !selectFeature.checked
          selectFeature.click();
        })
      }
    })
    const radioExpander = eventsContainer.querySelector('#graph-radios-expander') as HTMLButtonElement;
    radioExpander?.addEventListener('click', (e: any) => {

      const button = (e.currentTarget as HTMLButtonElement);
      button.style.display = 'none';

      const arrRadios = eventsContainer.querySelectorAll('.chart-radio-item-secondary') as NodeListOf<HTMLDivElement>;
      arrRadios.forEach(div => {
        div.style.display = 'block';
      });


    });
    if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) {
      radioExpander?.click();
    }
    const buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement
    buttonRefresh.addEventListener('click', async () => {
      this.processDateSelection(eventsContainer)
    })

    const chipSuspense = eventsContainer.querySelector('#chip-suspense') as HTMLDivElement
    chipSuspense?.addEventListener('click', async () => {
      this.suspenseFlag = !this.suspenseFlag
      this.processDateSelection(eventsContainer)
    })

    const externalInput = eventsContainer.querySelector('#external-reporting-file-uploader') as HTMLInputElement
    externalInput.addEventListener('change', async () => {
      console.log('trying to upload external file', externalInput.files);
      if (externalInput.files != null) {
        let file = externalInput.files[0]
        if (file != null) {
          let jsonObj = await Util.parseMISExcel(file);
          console.log('parsed JSON', jsonObj, this.events)
          // let externalMapping = await this.fetchExternalMapping()
          // console.log('external mapping', externalMapping);

          // let changeCount = 0
          // let totalCount = 0
          // for (let dateStr of Object.keys(this.events)) {
          //   for (let compliance of this.events[dateStr]) {
          //     let complianceId = compliance.id
          //     totalCount++;
          //     if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //       let externalId = externalMapping.data[complianceId]
          //       if (jsonObj.compliances[externalId] != null) {
          //         console.log('external compliance found', jsonObj.compliances[externalId])
          //         changeCount++
          //       }
          //     }
          //   }
          // }

          // this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [
          //   () => {
          //     for (let dateStr of Object.keys(this.events)) {
          //       for (let [index, compliance] of this.events[dateStr].entries()) {
          //         let complianceId = compliance.id
          //         if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //           let externalId = externalMapping.data[complianceId]
          //           if (jsonObj.compliances[externalId] != null) {
          //             if (jsonObj.compliances[externalId].status == "Complied") {
          //               this.events[dateStr][index].approved = true;
          //               this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() });
          //             }
          //           }
          //         }
          //       }
          //     }
          //     this.renderAppropriateStream(this.sdate, this.edate, true);
          //     this.clearMessages()
          //   },
          //   () => { this.clearMessages() }
          // ])
        }
      }
    })

    this.attachListReportingListeners(eventsContainer);
    this.attachReviewListeners(eventsContainer);
    const buttonArr = eventsContainer.querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonArr.length; i++) {
      let indexPrevNext = i;
      buttonArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.selectedItems = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'



          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null);
          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id;
                flagPrev = false;
              } else {
                prevString = "";
                indexPrev--
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < buttonArr.length - 1) {
              if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id;
                flagNext = false;
              } else {
                nextString = "";
                indexNext++
              }
            } else {
              flagNext = false;
            }
          }
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, eventsContainer, prevString, nextString);
        }
      })

    }
    const titleArr = eventsContainer.querySelectorAll('.button-event-title') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < titleArr.length; i++) {
      let indexPrevNext = i;
      titleArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        const flag = idArr[7];
        if (flag != null && flag == "reportedlocations") {
          return;
        }
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.selectedItems = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'

          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id;
                let prevIdArr = prevString.split("-")
                if ((prevIdArr[7] ?? "") == "reportedlocations") {
                  prevString = "";
                  indexPrev--;
                } else {
                  flagPrev = false;
                }
              } else {
                prevString = "";
                indexPrev--;
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < titleArr.length - 1) {
              if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id;
                console.log('prev nextString', nextString)
                let nextIdArr = nextString.split("-")
                console.log('prev nextArr', nextIdArr)
                if ((nextIdArr[7] ?? "") == "reportedlocations") {
                  nextString = "";
                  console.log('prev nextString2', nextString)
                  indexNext++;
                } else {
                  console.log('prev nextString3', nextString)
                  flagNext = false;
                }
              } else {
                indexNext++;
              }
            } else {
              flagNext = false;
            }
          }

          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, eventsContainer, prevString, nextString);
        }
      })

    }

    const buttonRenewArr = eventsContainer.querySelectorAll('.button-renew') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonRenewArr.length; i++) {
      buttonRenewArr[i].addEventListener('click', async (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        console.log('idArr', idArr);
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]);
        let renewEvent = this.events[mmdd][j];
        let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true);
        console.log('renew clicked', fullEvent, fullEvent.reportformatvalues);
        this.renewRCMResource(fullEvent, fullEvent.reportformatvalues);
      })
    }

    const streamEventsContainer = eventsContainer.querySelectorAll('.stream-events-container') as NodeListOf<HTMLDivElement>;
    const buttonSelect = eventsContainer.querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;
    if (eventsContainer.innerHTML.indexOf('button-select-all') >= 0) {
      let selectAllArr = this.attachSelectAllListeners(eventsContainer, buttonSelect)
      const buttonSelectAll = selectAllArr[0]
      const buttonUnselectAll = selectAllArr[1]
      for (i = 0; i < buttonSelect.length; i++) {

        buttonSelect[i].addEventListener('click', (ev: any) => {

          //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length);

          const id = ev.target.id;
          const idArr = id.split("-")
          const mmdd = idArr[2] + "/" + idArr[3];
          const j = idArr[4];
          // const makercheckers = idArr[5];
          const docs = idArr[6];
          const module = idArr[14];

          if ((ev.target as HTMLInputElement).checked) {
            this.selectedItemIds.push(id);
          } else {
            this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1);
            let listReportingContainer = eventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement
            listReportingContainer.style.display = 'none';
            listReportingContainer.innerHTML = '';
            let buttonListReporting = eventsContainer.querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement
            buttonListReporting.setAttribute('part', 'button-list-reporting')
            let streamEventTitle = eventsContainer.querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText
            streamEventTitle.removeAttribute('part')
          }

          if (this.selectedItemIds.length === 0) {

            for (var k = 0; k < buttonSelect.length; k++) {

              const id1 = buttonSelect[k].id;
              const idArr1 = id1.split("-")
              const isbulk = idArr1[15] == "bulk"
              console.log('isBulk button-select', id1, isbulk)
              if (isbulk) {
                (buttonSelect[k] as HTMLInputElement).style.display = 'none';
              } else {
                (buttonSelect[k] as HTMLInputElement).style.display = 'block';
              }
              (streamEventsContainer[k] as HTMLDivElement).style.display = 'block';

            }

            let bulkUploadLables = eventsContainer.querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
            for (let bulkUploadLable of bulkUploadLables) {
              bulkUploadLable.innerHTML = ''
            }

            buttonSelectAll.style.display = 'none';
            buttonUnselectAll.style.display = 'none';

          } else {

            if (this.selectedItemIds.length === 1) {

              const id1 = id;
              const idArr1 = id1.split("-")
              const status = idArr1[13].replace(/_/g, '-');
              this.selectedStatus = status;

            }

            let totalVisibleCount = 0
            for (var k = 0; k < buttonSelect.length; k++) {

              const id1 = buttonSelect[k].id;
              const idArr1 = id1.split("-")
              const docs1 = idArr1[6];
              const status = idArr1[13].replace(/_/g, '-');
              const module1 = idArr1[14]
              const isbulk = idArr1[15] == "bulk"
              console.log('isBulk button-select', id1, isbulk)
              if (isbulk) {
                (buttonSelect[k] as HTMLInputElement).style.display = 'none';
              }
              if (docs == docs1 && status == this.selectedStatus && module == module1) {
                totalVisibleCount++
              } else {
                (buttonSelect[k] as HTMLInputElement).style.display = 'none';
                (streamEventsContainer[k] as HTMLDivElement).style.display = 'none';
              }

            }

            let bulkUploadLables = eventsContainer.querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
            for (let bulkUploadLable of bulkUploadLables) {
              bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected`
            }

            if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) {
              buttonSelectAll.style.display = 'none';
              buttonUnselectAll.style.display = 'flex';
            } else {
              buttonSelectAll.style.display = 'flex';
              buttonUnselectAll.style.display = 'none';
            }

          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'

          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + ""));
          if (this.selectedItemIds.length == 1) {
            ev.target.scrollIntoView()
          }
        })

      }
    }

    // this.clearGraphData();

    // //console.log('rendering range', firstDate, count);

    // this.selectedItems = [];

    // var html = '';

    // html += '<div class="mb-20 stream-event-list" part="stream-event-list-charts">';
    //   html += '<div part="stream-event-chart-selection" class="mb-20">';
    //     html += '<div part="td-head" class="mb-5">Select Chart</div>';
    //     html += '<div class="mb-10 d-flex flex-wrap align-center">';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-completeness" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_COMPLETENESS) ? 'checked' : '') +'>';
    //       html += '<label for="radio-completeness" part="input-label" class="mr-10">Completeness</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-timeliness" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_TIMELINESS) ? 'checked' : '') +'>';
    //       html += '<label for="radio-timeliness" part="input-label" class="mr-10">Timeliness</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-risk" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_RISKAREAS) ? 'checked' : '') +'>';
    //       html += '<label for="radio-risk" part="input-label" class="mr-10">Risk Areas</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-riskseverity" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_RISKSEVERITY) ? 'checked' : '') +'>';
    //       html += '<label for="radio-riskseverity" part="input-label" class="mr-10">Risk Severity</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-location" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_LOCATION) ? 'checked' : '') +'>';
    //       html += '<label for="radio-location" part="input-label" class="mr-10">Location</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-function" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_FUNCTION) ? 'checked' : '') +'>';
    //       html += '<label for="radio-function" part="input-label" class="mr-10">Function</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-obligationtype" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_OBLIGATIONTYPE) ? 'checked' : '') +'>';
    //       html += '<label for="radio-obligationtype" part="input-label" class="mr-10">Obligation Type</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-jurisdiction" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_JURISDICTION) ? 'checked' : '') +'>';
    //       html += '<label for="radio-jurisdiction" part="input-label" class="mr-10">Jurisdiction</label></div>';
    //       html += '<div part="chart-radio-item"><input type="radio" id="radio-frequency" name="graph-type" part="radio-graph" '+ ((this.flowGraph == this.FLOW_GRAPH_FREQUENCY) ? 'checked' : '') +'>';
    //       html += '<label for="radio-frequency" part="input-label">Frequency</label></div>';
    //     html += '</div>';
    //   html += '</div>';
    //   html += '<div class="chart-container d-flex scroll-x align-center"><div part="chart-item" class="chart-item"><canvas id="myChart"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart4" class="gone"></canvas></div><div part="chart-item chart-item-middle" class="chart-item"><canvas id="myChart2" class="gone"></canvas></div><div part="chart-item" class="chart-item"><canvas id="myChart3" class="gone"></canvas></div></div>';
    //   html += '<div id="chart-settings-controls" class="mt-20"></div>'
    //   html += '<div id="chart-settings"></div>'
    // html += '</div>';

    // html += '<div id="stream-event-0" part="stream-event-list" class="stream-event-list">';

    // var total = 0, notStarted = 0, approved = 0, inProgress = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0;

    // html += '<div id="stream-event-summary" part="stream-event-total" class="d-flex flex-wrap">';
    // html += '<div part="badge-dashboard" class="mr-10 mb-10 no-shrink"><span>Total:</span> <span id="graph-total">DASHBOARD_TOTAL</span></div>';
    // html += '<div part="badge-dashboard" class="stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-icons color-not-started">schedule</span>&nbsp;&nbsp;<span>Not Started:</span> <span id="graph-not-started">DASHBOARD_NOT_STARTED</span></div>';
    // html += '<div part="badge-dashboard" class="stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-symbols-outlined color-pending">pending</span>&nbsp;&nbsp;<span>In Progress:</span> <span id="graph-in-progress">DASHBOARD_IN_PROGRESS</span></div>';
    // html += '<div part="badge-dashboard" class="stat-completeness d-flex justify-center align-center mr-10 mb-10 no-shrink"><span class="material-symbols-outlined color-done">check_circle</span>&nbsp;&nbsp;<span>Approved:</span><span id="graph-approved">DASHBOARD_APPROVED</span></div>';
    // // html += '<div part="calendar-tab-button-not-selected" class="gone d-flex justify-center align-center mr-10 mb-10 no-shrink cursor" id="button-status-more"><span class="material-symbols-outlined">navigate_next</span></div>';
    // html += '<div part="badge-dashboard" class="stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-not-started">timer</span>&nbsp;&nbsp;<span>In Time:</span> <span id="graph-in-time">DASHBOARD_IN_TIME</span></div>';
    // html += '<div part="badge-dashboard" class="stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-past-due-date">running_with_errors</span>&nbsp;&nbsp;<span>Past Due Date:</span> <span id="graph-past-due-date">DASHBOARD_PAST_DUE_DATE</span></div>';
    // html += '<div part="badge-dashboard" class="stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-approved">running_with_errors</span>&nbsp;&nbsp;<span>Late Approved:</span> <span id="graph-late-approved">DASHBOARD_LATE_APPROVED</span></div>';
    // html += '<div part="badge-dashboard" class="stat-timeliness justify-center align-center mr-10 mb-10 no-shrink late-statuses"><span class="material-icons color-late-executed">running_with_errors</span>&nbsp;&nbsp;<span>Late Executed:</span> <span id="graph-late-executed">DASHBOARD_LATE_EXECUTED</span></div>';
    // html += '</div>';
    // html += '<div id="stream-event-filter" part="stream-event-total" class="d-flex flex-wrap"></div>';

    // var lastDate = new Date(firstDate.getTime());
    // lastDate.setDate(lastDate.getDate() + count)

    // this.eventsInWindow = [];
    // var csvCols = "", htmlCols = "";
    // var csvValues = "", htmlValues = "";
    // var period = ("0" + (firstDate.getMonth()+1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2) + ' - ' + ("0" + (lastDate.getMonth()+1)).slice(-2) + "/" + ("0" + lastDate.getDate()).slice(-2)

    // let firstDay: Date | null = null;
    // let endDay = null;

    // var slice = 2;

    // for(var i = 1; i <= count; i++) {

    //   if(i === 1) {
    //     firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    //     endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    //   } else {
    //     endDay?.setDate(endDay.getDate() + 1);
    //   }


    //   const mmdd = ("0" + (firstDate.getMonth()+1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2);

    //   var hide = true;

    //   //console.log('eventslice', slice);
    //   //console.log('event status', mmdd, this.events[mmdd]);

    //   if(this.events[mmdd] != null) {
    //     hide = false;
    //   } else if(i === 1){
    //     hide = false;
    //   } else if(i === (count)){
    //     hide = false;
    //   } else {

    //     const startNextDate = new Date(firstDate.getTime());
    //     startNextDate.setDate(firstDate.getDate() + 1);

    //     const startPrevDate = new Date(firstDate.getTime());
    //     startPrevDate.setDate(firstDate.getDate() - 1);

    //     const mmddNext = ("0" + (startNextDate.getMonth()+1)).slice(-2) + "/" + ("0" + (startNextDate.getDate())).slice(-2);
    //     const mmddPrev = ("0" + (startPrevDate.getMonth()+1)).slice(-2) + "/" + ("0" + (startPrevDate.getDate())).slice(-2);
    //     //console.log('hide', i, hide, startNextDate, startPrevDate, mmddNext, mmddPrev);
    //     if((this.events[mmddPrev] != null || this.events[mmddNext] != null)) {
    //       hide = false;
    //     }
    //   }

    //   if(this.events[mmdd] != null) {
    //     html += '<div part="stream-event-selected" class="d-flex stream-event-selected">';
    //       html += '<div part="stream-event-selected-date">'+("0" + firstDate.getDate()).slice(-2)+'/'+(firstDate.getMonth()+1)+' |</div>';
    //       html += '<div class="stream-event-list-container flex-grow">'
    //       for(var j = 0; j < (this.events[mmdd] as Array<any>).length; j++) {
    //         total++;
    //         this.events[mmdd][j]['mmdd'] = mmdd
    //         this.eventsInWindow.push(this.events[mmdd][j]);

    //         // this.events[mmdd][j] = this.renderLatestCompliance(("0" + (firstDate.getMonth()+1)).slice(-2), this.events[mmdd][j]);

    //         var partStatus = "";
    //         var lateStatus = "in-time";

    //         if(this.events[mmdd][j].approved != null && (this.events[mmdd][j].approved) != null && (this.events[mmdd][j].approved)) {

    //           partStatus = "status-approved";
    //           if(this.getLateExecuted(mmdd, this.events[mmdd][j])) {
    //             lateStatus = "late-executed"
    //           } else {
    //             if(this.getLateApproved(mmdd, this.events[mmdd][j])) {
    //               lateStatus = "late-approved"
    //             }
    //           }
    //         } else if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) {
    //           partStatus = "status-in-progress";
    //           if(this.getPastDueDate(mmdd)) {
    //             lateStatus = "past-due-date"
    //           }
    //         } else {
    //           partStatus = "status-not-started";
    //           if(this.getPastDueDate(mmdd)) {
    //             lateStatus = "past-due-date"
    //           }
    //         }

    //         this.updateRiskAreaStats(this.events[mmdd][j]['riskarea'], partStatus, lateStatus);
    //         this.updateRiskSeverityStats(this.events[mmdd][j]['risk'], partStatus, lateStatus);
    //         this.updateFunctionStats(this.events[mmdd][j]['functions'], partStatus, lateStatus);
    //         this.updateObligationTypeStats(this.events[mmdd][j]['obligationtype'], partStatus, lateStatus);
    //         this.updateJurisdictionStats(this.events[mmdd][j]['jurisdiction'], partStatus, lateStatus)
    //         this.updateFrequencyStats(this.events[mmdd][j]['frequency'], partStatus, lateStatus)
    //         this.updateLocationStats([this.events[mmdd][j]['locationname']], partStatus, lateStatus)

    //         html += '<div class="stream-events-container flex-grow">';
    //           html += '<div class="hidden-tags hide">'+JSON.stringify(this.events[mmdd][j]['tags'])+'</div>'
    //           html += '<div class="hidden-title hide"><table><thead><th part="badge-filtered"><i>filtered out</i></th></thead></table></div>'
    //           html += '<div part="stream-events-event-title" class="stream-events-event-title d-flex align-center pl-5 pb-5">' + ('<input id="button-select-'+mmdd.replace('/', '-')+'-'+j + '-' + (((this.events[mmdd][j].makercheckers != null && (this.events[mmdd][j].makercheckers).length > 0)) ? '1' : '0') + '-' + (((this.events[mmdd][j].docs != null && (this.events[mmdd][j].docs).length > 0)) ? '1' : '0') + '-' + this.events[mmdd][j].entityid.replace(/-/g, '_') + '-' + this.events[mmdd][j].locationid.replace(/-/g, '_') + '-' + this.events[mmdd][j].id.replace(/-/g, '_') +  '-' + this.events[mmdd][j].duedate.split('/')[1] + '-' + this.events[mmdd][j].duedate.split('/')[0] + '-' + this.events[mmdd][j].duedate.split('/')[2] + '-' + partStatus.replace(/-/g,'_') +  '" class="button-select mr-10" type="checkbox" />') + '<sf-i-elastic-text exportparts="highlight,highlight-count" text="'+this.events[mmdd][j]['obligationtitle']+'" minLength="100"></sf-i-elastic-text></div>';
    //           html += '<table class="stream-events-container-table">';
    //           html += '<thead>';
    //           html += '<th part="td-head">';
    //           html += 'Status'
    //           if(csvCols.indexOf('Status') < 0) {
    //             csvCols += 'Period,Status,Id,ObligationTitle,Obligation,Duedate' 
    //             htmlCols += '<tr><th>Id</th><th>Status</th><th>Statute</th><th>Reference</th><th class="w-200px">Applicability</th><th>ObligationType</th><th class="w-200px">Obligation</th><th class="w-200px">InternalControls</th><th class="w-200px">Penalty</th><th>RiskSeverity</th><th>Frequency</th><th>SubFrequency</th><th>DueDate</th><th>ReportParameter</th></tr>'
    //           }
    //           html += '</th>';
    //           html += '<th part="td-head">';
    //           html += '</th>';
    //           html += '<th part="td-head">';
    //           html += 'Location'
    //           html += '</th>'
    //           html += '<th part="td-head">';
    //           html += 'Entity'
    //           html += '</th>'
    //           html += '<th part="td-head">';
    //           html += 'Country'
    //           html += '</th>'
    //           html += '<th part="td-head">';
    //           html += 'Function'
    //           html += '</th>'

    //           for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) {
    //             if(this.getEventPreviewFields().includes(Object.keys(this.events[mmdd][j])[k])) {
    //               html += '<th part="td-head" class="bg-left-no-border">';
    //               html += Object.keys(this.events[mmdd][j])[k];
    //               html += '</th>';
    //             }
    //           }

    //           //console.log('listing docs',this.events[mmdd][j].documents )
    //           if(this.events[mmdd][j].documents != null && this.events[mmdd][j].documents != null && (this.events[mmdd][j].documents).length > 0) {
    //             html += '<th part="td-head">';
    //             html += 'Docs'
    //             html += '</th>';
    //           }
    //           if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) {
    //             html += '<th part="td-head">';
    //             html += 'Comments'
    //             html += '</th>';
    //           } else {
    //             if(partStatus != "status-approved") {
    //               notStarted++;
    //             }
    //           }
    //           if(this.events[mmdd][j].lastupdated != null && this.events[mmdd][j].lastupdated != null && (this.events[mmdd][j].lastupdated).length > 0) {
    //             html += '<th part="td-head">';
    //             html += 'Updated'
    //             html += '</th>';
    //           }
    //           if(this.events[mmdd][j].makercheckers != null && (this.events[mmdd][j].makercheckers).length > 0) {
    //             html += '<th part="td-head">';
    //             html += ''
    //             html += '</th>'
    //           }
    //           if(this.events[mmdd][j].docs != null && (this.events[mmdd][j].docs).length > 0) {
    //             html += '<th part="td-head">';
    //             html += ''
    //             html += '</th>'
    //           }

    //           // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) {
    //           //   html += '<th part="td-head">';
    //           //   html += Object.keys(this.events[mmdd][j])[k];
    //           //   html += '</th>';
    //           // }
    //           html += '</thead>';
    //           html += '<tbody>';
    //           csvValues += (period + ',');
    //           htmlValues += ('<tr><td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["id"]+'</td>');
    //           if(partStatus == "status-approved") {
    //             approved++
    //             html += '<td part="td-body">';
    //             if(lateStatus == "late-executed") {
    //               lateExecuted++;
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-symbols-outlined color-done color-done-item color-done-item-'+i+'">check_circle</span>';
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-icons color-late-executed color-late-executed color-late-executed-'+i+'">running_with_errors</span>';
    //               }
    //               csvValues += 'approved late-executed,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">approved late-executed</td>');
    //             } else if(lateStatus == "late-approved") {
    //               lateApproved++;
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-symbols-outlined color-done color-done-item color-done-item-'+i+'">check_circle</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-icons color-late-approved color-late-approved color-late-approved-'+i+'">running_with_errors</span>'
    //               }
    //               csvValues += 'approved late-approved,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">approved late-approved</td>');
    //             } else {
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-symbols-outlined color-done color-done-item color-done-item-'+i+'">check_circle</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-symbols-outlined color-not-started color-not-started-item color-not-started-item-'+i+'">timer</span>'
    //               }
    //               csvValues += 'approved,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">approved</td>');
    //             }
    //             html += '</td>';
    //           } else if(partStatus == "status-in-progress") {
    //             html += '<td part="td-body">';
    //             if(lateStatus == "past-due-date") {
    //               pastDueDate++;
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-symbols-outlined color-pending color-pending-item color-pending-item-'+i+'">pending</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-icons color-past-due-date color-past-due-date-item color-past-due-date-item-'+i+'">running_with_errors</span>'
    //               }
    //               csvValues += 'in-progress past-due-date,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">in-progress past-due-date</td>');
    //             } else {
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-symbols-outlined color-pending color-pending-item color-pending-item-'+i+'">pending</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-symbols-outlined color-not-started color-not-started-item color-not-started-item-'+i+'">timer</span>'
    //               }
    //               csvValues += 'in-progress,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">in-progress</td>');
    //             }

    //             html += '</td>';
    //           } else {
    //             html += '<td part="td-body">';
    //             if(lateStatus == "past-due-date") {
    //               pastDueDate++;
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-icons color-not-started color-not-started-item color-not-started-item-'+i+'">schedule</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-icons color-past-due-date color-past-due-date-item color-past-due-date-item-'+i+'">running_with_errors</span>'
    //               }
    //               csvValues += 'not started past-due-date,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">not-started past-due-date</td>');
    //             } else {
    //               if(this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {
    //                 html += '<span class="material-icons color-not-started color-not-started-item color-not-started-item-'+i+'">schedule</span>'
    //               }
    //               if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS) {
    //                 html += '<span class="material-symbols-outlined color-not-started color-not-started-item color-not-started-item-'+i+'">timer</span>'
    //               }
    //               csvValues += 'not started,';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +' text-center status-format">not-started</td>');
    //             }

    //             html += '</td>';
    //           }
    //           html += '<td id="td-expand-'+i+'" part="td-body">';
    //           html += '<button id="button-unmapped-expand-'+mmdd.replace('/', '-')+'-'+j+'" part="button-icon-small" class="material-icons button-expand mr-10">open_in_new</button>'
    //           html += '</td>';
    //           html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="'+this.events[mmdd][j]["locationname"].replace(/ *\([^)]*\) */g, "")+'" minLength="10"></sf-i-elastic-text></td>';
    //           html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="'+this.events[mmdd][j]["entityname"].replace(/ *\([^)]*\) */g, "")+'" minLength="10"></sf-i-elastic-text></td>';
    //           html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="'+this.events[mmdd][j]["countryname"].replace(/ *\([^)]*\) */g, "")+'" minLength="10"></sf-i-elastic-text></td>';
    //           var functions = '';
    //           for(const element of this.events[mmdd][j]["functions"])  {
    //             functions += (element.split(';')[0].replace(/ *\([^)]*\) */g, "") + ",");
    //           }
    //           functions = functions.replace(/,\s*$/, "");
    //           html += '<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="'+functions+'" minLength="10"></sf-i-elastic-text></td>';
    //           for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) {
    //             if(this.getEventPreviewFields().includes(Object.keys(this.events[mmdd][j])[k])) {

    //               html += '<td part="td-body">';
    //               if(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].indexOf("[") >= 0) {
    //                 html += this.getEventTexts(Object.keys(this.events[mmdd][j])[k], JSON.parse(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]]), this.events[mmdd][j]);
    //               } else {
    //                 html += ' <sf-i-elastic-text exportparts="highlight,highlight-count" text="'+this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].replace(/"/g, "")+'" minLength="20"></sf-i-elastic-text>';
    //               }
    //               html += '</td>';

    //             }
    //           }

    //           csvValues += this.events[mmdd][j]["id"] + ',' + this.events[mmdd][j]["obligationtitle"] + ',' + this.events[mmdd][j]["obligation"] + ',' + this.events[mmdd][j]["duedate"];
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["statute"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["reference"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["applicability"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["obligationtype"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["obligation"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["internalcontrols"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["penalty"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["risk"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["frequency"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["subfrequency"]+'</td>');
    //           htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+this.events[mmdd][j]["duedate"]+'</td>');


    //           if(this.events[mmdd][j].documents != null && this.events[mmdd][j].documents != null && (this.events[mmdd][j].documents).length > 0) {
    //             html += '<td part="td-body">';
    //             html += '<span class="material-icons muted">description</span>'
    //             html += (this.events[mmdd][j].documents).length
    //             html += '</td>';
    //           }
    //           if(this.events[mmdd][j].comments != null && this.events[mmdd][j].comments != null && (this.events[mmdd][j].comments).length > 0) {
    //             html += '<td part="td-body">';
    //             html += '<span class="material-icons muted">forum</span>'
    //             html += (this.events[mmdd][j].comments).length
    //             html += '</td>';
    //           }
    //           if(this.events[mmdd][j].lastupdated != null && this.events[mmdd][j].lastupdated != null && (this.events[mmdd][j].lastupdated).length > 0) {
    //             html += '<td part="td-body">';
    //             html += Util.timeSince(new Date(this.events[mmdd][j].lastupdated).getTime())
    //             html += '</td>';
    //           }
    //           if(this.events[mmdd][j].makercheckers != null && (this.events[mmdd][j].makercheckers).length > 0) {
    //             html += '<td part="td-body">';
    //             html += '<span class="material-symbols-outlined muted">done_all</span>'
    //             html += '</td>';
    //           }
    //           if(this.events[mmdd][j].docs != null && (this.events[mmdd][j].docs).length > 0) {
    //             html += '<th part="td-body">';
    //             html += '<span class="material-symbols-outlined muted">scan_delete</span>'
    //             html += '</th>'
    //           }
    //           csvValues += '\n';

    //           // for(var k = 0; k < Object.keys(this.events[mmdd][j]).length; k++) {
    //           //   html += '<th part="td-body">';
    //           //   if(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].indexOf("[") >= 0) {
    //           //     html += this.getEventTexts(Object.keys(this.events[mmdd][j])[k], JSON.parse(this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]]), this.events[mmdd][j]);
    //           //   } else {
    //           //     html += this.events[mmdd][j][Object.keys(this.events[mmdd][j])[k]].replace(/"/g, "");
    //           //   }

    //           //   html += '</th>';
    //           // }
    //           html += '</tbody>';
    //           html += '</table>';
    //           html += '<div class="hidden-filtername hide"><table><thead><th part="badge-filter-name" class="filtername"></th></thead></table></div>'

    //           let reporterStr = this.getReporterStringFromEvent(this.events[mmdd][j]);
    //           let approverStr = this.getApproverStringFromEvent(this.events[mmdd][j]);

    //           if(this.flowGraph != this.FLOW_GRAPH_COMPLETENESS && this.flowGraph != this.FLOW_GRAPH_TIMELINESS) {

    //             let graphParam = '';
    //             if(Array.isArray(this.events[mmdd][j][this.flowGraph])) {
    //               graphParam = this.events[mmdd][j][this.flowGraph].toString().replace(/ *\([^)]*\) */g, "");
    //             } else {
    //               graphParam = this.events[mmdd][j][this.flowGraph].replace(/ *\([^)]*\) */g, "");
    //             }
    //             html += '<div class="d-flex"><div part="badge-filter-name" class="graphparamname graphparamname1 mb-20">' + graphParam + '</div>'+reporterStr + approverStr+'</div>';
    //             htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+graphParam+'</td>');

    //           } else {

    //             if(this.flowGraph == this.FLOW_GRAPH_COMPLETENESS) {

    //               html += '<div class="d-flex"><div part="badge-filter-name" class="graphparamname graphparamname1 mb-20">' + partStatus.replace('status-', '') + '</div>'+reporterStr + approverStr+'</div>';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+partStatus.replace('status-', '')+'</td>');

    //             }

    //             if(this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {

    //               html += '<div class="d-flex"><div part="badge-filter-name" class="graphparamname graphparamname1 mb-20">' + lateStatus + '</div>'+reporterStr + approverStr+'</div>';
    //               htmlValues += ('<td class="'+ (total%2 === 0 ? 'td-odd' : 'td-even') +'">'+lateStatus+'</td>');

    //             }

    //           }

    //           htmlValues += ('</tr>');

    //         html += '</div>';
    //       }
    //       html += '</div>';
    //     html += '</div>';

    //   } else {

    //     if(!hide) {
    //       html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected">';
    //       html += '<div>'+("0" + firstDate.getDate()).slice(-2)+'/'+(firstDate.getMonth()+1)+'</div>';
    //       html += '</div>';
    //       slice = 2;
    //     } else {
    //       //console.log('eventslice=person', i, slice, i%slice);
    //       if(i%slice === 0) {
    //         html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected-hidden">';
    //         //html += '<div>'+("0" + i).slice(-2)+' |</div>';
    //         html += '<div>.</div>';
    //         html += '</div>';
    //         slice+=3;
    //       }
    //     }

    //   }

    //   firstDate.setDate(firstDate.getDate() + 1);

    // }

    // html += '</div>';

    // this.period = firstDay?.getDate() + '/' + (firstDay!.getMonth()+1) + '/' + firstDay?.getFullYear() + " - " + endDay?.getDate() + '/' + (endDay!.getMonth()+1) + '/' + endDay?.getFullYear();

    // this.csvDataCompliances = csvCols + "\n" + csvValues;
    // this.htmlDataCompliances = '<table>' + htmlCols + htmlValues + '</table>';

    // inProgress = total - notStarted - approved;

    // //console.log('progress', total, notStarted, approved)

    // html = html.replace("DASHBOARD_TOTAL", total+"");
    // html = html.replace("DASHBOARD_NOT_STARTED", notStarted+"");
    // html = html.replace("DASHBOARD_APPROVED", approved+"");
    // html = html.replace("DASHBOARD_IN_PROGRESS", inProgress+"");
    // html = html.replace("DASHBOARD_IN_TIME", (total - pastDueDate - lateApproved - lateExecuted)+"");
    // html = html.replace("DASHBOARD_PAST_DUE_DATE", pastDueDate+"");
    // html = html.replace("DASHBOARD_LATE_EXECUTED", lateExecuted+"");
    // html = html.replace("DASHBOARD_LATE_APPROVED", lateApproved+"");

    // this.csvDataStats = 'Period,Total,Not Started,Approved,In Progress,Past Due Date,Late Executed,Late Approved\n';
    // this.csvDataStats += this.period + "," + total + "," + notStarted + "," + approved + "," + inProgress + "," + pastDueDate + "," + lateExecuted + "," + lateApproved;

    // this.htmlDataStats = '<table class="w-100"><tr><th class="w-14">Total</th><th class="w-14">Not Started</th><th class="w-14">Approved</th><th class="w-14">In Progress</th><th class="w-14">Past Due Date</th><th class="w-14">Late Executed</th><th class="w-14">Late Approved</th><tr>';
    // this.htmlDataStats += '<tr><td class="w-14 text-center td-odd">'+total+'</td><td class="w-14 text-center td-odd">'+notStarted+'</td><td class="w-14 text-center td-odd">'+approved+'</td><td class="w-14 text-center td-odd">'+inProgress+'</td><td class="w-14 text-center td-odd">'+pastDueDate+'</td><td class="w-14 text-center td-odd">'+lateExecuted+'</td><td class="w-14 text-center td-odd">'+lateApproved+'</td><tr></table>';



  }

  renderRangeStatistics = (firstDate: Date, count: number, eventsContainer: HTMLDivElement) => {


    var lastDate = new Date(firstDate.getTime());
    lastDate.setDate(lastDate.getDate() + count - 1)

    const lastDay = count;
    let firstDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    let endDay = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    endDay?.setDate(endDay.getDate() + lastDay);
    var period = ("0" + (firstDate.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDate.getDate()).slice(-2) + '/' + firstDate.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear();
    console.log('rangeperiod', period, lastDay)

    var html = this.renderStatistics(firstDay, endDay, 0, lastDay, true, 0, (firstDate.getMonth()), period, firstDate, "You are viewing consolidated statistics for your entire scope from " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'));

    eventsContainer.querySelector('.calendar-right-data')!.innerHTML = html;
    this.renderButtonRefresh(eventsContainer);
    const filterButton = eventsContainer.querySelector('#filter-button') as HTMLButtonElement
    filterButton?.addEventListener('click', () => {
      const filterList = eventsContainer.querySelector('#filter-list-container') as HTMLDivElement
      filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none')
      filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close')
      const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement
      filterSubmitButton.addEventListener('click', () => {
        Util.setFeatures(this.selectedFeatures);
        this.renderTabs(this.selectedTab)
        this.processDateSelectionViewer(eventsContainer);
      })
      const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf<HTMLLabelElement>
      for (let [i, selectFeature] of selectFeatures.entries()) {
        selectFeature.addEventListener('click', (ev: any) => {
          let target = ev.target;
          let id = target.id;
          let index = id.split('-')[3];
          let selectedFeature = this.getFeatures()[index]
          if (target.checked) {
            if (this.selectedFeatures.indexOf(selectedFeature) < 0) {
              // this.selectedFeatures.push(selectedFeature)
              this.selectedFeatures = [selectedFeature]
            }
          }
          filterSubmitButton.click();
        })
        selectFeatureLabels[i].addEventListener('click', () => {
          selectFeature.checked = !selectFeature.checked
          selectFeature.click();
        })
      }
    })

    const buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement
    buttonRefresh.addEventListener('click', async () => {
      this.processDateSelectionViewer(eventsContainer)
    })
    let filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).value
    // if (Object.keys(this.statisticsFiltersData).length > 0 && filtercriteria != "location" && filtercriteria != "all") {
    if (Object.keys(this.statisticsFiltersData).length > 0 && filtercriteria != "all") {
      this.renderDrilldownListeners(eventsContainer);
    }
  }

  renderDrilldownListeners = async (eventsContainer: HTMLDivElement) => {
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log('rendering drilldown listeners', this.statisticsFiltersData, this.statisticsMeta)
    let rows = eventsContainer.querySelectorAll('.tablerow') as NodeListOf<HTMLTableRowElement>
    let filtercriteria = Object.keys(this.statisticsFiltersData)[0]
    console.log('rendering statistics filters for criteria', filtercriteria, this.statisticsMeta[filtercriteria])
    let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[filtercriteria])
    for (let [rowIndex, row] of rows.entries()) {
      let filterVal = sortedFilters[rowIndex]
      let filterValue = filterVal.split(';')[1]
      let filterName = filterVal.split(';')[0].replace(/\([^)]*\)/g, "")

      let filterNameDiv = row.querySelector('#filter-' + rowIndex) as HTMLDivElement
      filterNameDiv.addEventListener('click', () => {
        console.log('clicked name filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "")
      })
      let notStartedDiv = row.querySelector('#filter-not-started-' + rowIndex) as HTMLDivElement
      notStartedDiv.addEventListener('click', () => {
        console.log('clicked not started filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "not-started")
      })
      let pendingApprovalDiv = row.querySelector('#filter-pending-approval-' + rowIndex) as HTMLDivElement
      pendingApprovalDiv.addEventListener('click', () => {
        console.log('clicked pending approval filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "pending-approval")
      })
      let rejectedDiv = row.querySelector('#filter-rejected-' + rowIndex) as HTMLDivElement
      rejectedDiv.addEventListener('click', () => {
        console.log('clicked rejected filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "rejected")
      })
      let approvedDiv = row.querySelector('#filter-approved-' + rowIndex) as HTMLDivElement
      approvedDiv.addEventListener('click', () => {
        console.log('clicked approved filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName, "approved")
      })
      let totalDiv = row.querySelector('#filter-total-' + rowIndex) as HTMLDivElement
      totalDiv.addEventListener('click', () => {
        console.log('clicked total filter', rowIndex)
        console.log('filter', filtercriteria, filterValue, filterName)
        this.renderStatisticsDetails(filtercriteria, filterValue, filterName)
      })
    }
  }

  renderStatisticsFilters = (eventsContainer: HTMLDivElement) => {
    let selectFilterCriteria = eventsContainer.querySelector('#select-filter-criteria') as HTMLSelectElement
    let inputLabelFilter = eventsContainer.querySelector('#input-label-filter') as HTMLLabelElement
    let selectFilterCriteriaMobile = eventsContainer.querySelector('#select-filter-criteria-mobile') as HTMLSelectElement
    let inputLabelFilterMobile = eventsContainer.querySelector('#input-label-filter-mobile') as HTMLLabelElement
    selectFilterCriteria.style.display = 'block'
    inputLabelFilter.style.display = 'block'
    selectFilterCriteriaMobile.style.display = 'block'
    inputLabelFilterMobile.style.display = 'block'
    selectFilterCriteria.innerHTML = ""
    selectFilterCriteriaMobile.innerHTML = ""
    let filterscriteria = "all"
    if (Object.keys(this.statisticsFiltersData ?? {}).length > 0 && this.statisticsSelectedFilter != "all") {
      filterscriteria = Object.keys(this.statisticsFiltersData)[0]
    }
    let option = new Option()
    option.value = "all";
    option.innerHTML = "all"
    selectFilterCriteria.add(option)
    option = new Option()
    option.value = "all";
    option.innerHTML = "all"
    selectFilterCriteriaMobile.add(option)


    for (let criteria of Object.keys(this.statisticsMeta)) {
      if (criteria == "subfilters") {
        continue;
      }
      let option = new Option()
      option.value = criteria;
      option.selected = (criteria == filterscriteria)

      if (criteria == "reporter" || criteria == "approver" || criteria == "functionhead") {
        option.innerHTML = "user:" + criteria
      } else {
        option.innerHTML = criteria
      }
      selectFilterCriteria.add(option)
      option = new Option()
      option.value = criteria;
      console.log('statistics filters criteria', criteria, filterscriteria, criteria == filterscriteria, this.statisticsSelectedFilter)

      option.selected = (criteria == filterscriteria)
      if (criteria == "reporter" || criteria == "approver" || criteria == "functionhead") {
        option.innerHTML = "user:" + criteria
      } else {
        option.innerHTML = criteria
      }
      selectFilterCriteriaMobile.add(option)
    }

    let selectFilterCriteriaNew = Util.clearListeners(selectFilterCriteria)
    selectFilterCriteriaNew.addEventListener('change', (ev: any) => {
      console.log('statsoption change triggered');
      let target = ev.target as HTMLSelectElement
      this.statisticsSelectedFilter = target.value
      let inputLabelCriteria = eventsContainer.querySelector('#input-label-criteria') as HTMLLabelElement
      let selectFilterValues = eventsContainer.querySelector('#select-filter-values') as HTMLSelectElement
      selectFilterValues.value = ""
      let inputLabelSubfilters = eventsContainer.querySelector('#input-label-subfilter') as HTMLLabelElement
      let selectSubfilterCriteria = eventsContainer.querySelector('#select-subfilter-criteria') as HTMLSelectElement
      selectSubfilterCriteria.value = ""
      selectSubfilterCriteria.length = 0


      selectFilterValues.innerHTML = ""
      let option = new Option()
      option.value = "";
      option.innerHTML = "All";
      selectFilterValues.add(option)
      if (this.statisticsMeta[target.value] != null && target.value != "all") {
        let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[target.value])
        selectFilterValues.style.display = 'block'
        inputLabelCriteria.style.display = 'block'
        inputLabelCriteria.innerHTML = target.value
        for (let filter of sortedFilters) {
          let option = new Option()
          option.value = filter.split(';')[1];
          option.innerHTML = filter.split(';')[0].replace(/\([^)]*\)/g, "")
          selectFilterValues.add(option)
        }
        let selectFilterValuesNew = Util.clearListeners(selectFilterValues)
        selectFilterValuesNew.addEventListener('change', () => {
          console.log('changed')
          this.processDateSelectionViewer(eventsContainer);
        })
        selectSubfilterCriteria.style.display = 'block'
        inputLabelSubfilters.style.display = 'block'
        let sortedSubfilters = Util.alphabeticalSort(Object.keys(this.statisticsMeta.subfilters))

        if (sortedSubfilters.length > 1) {
          let option = new Option()
          option.value = "";
          option.innerHTML = "None";
          selectSubfilterCriteria.add(option)
        }
        for (let subfilter of sortedSubfilters) {
          let option = new Option()
          option.value = subfilter;
          option.innerHTML = subfilter
          selectSubfilterCriteria.add(option)
        }
        let inputLabelSubfiltersValue = eventsContainer.querySelector('#input-label-subfilter-value') as HTMLLabelElement
        let selectSubfilterValues = eventsContainer.querySelector('#select-subfilter-values') as HTMLSelectElement
        inputLabelSubfiltersValue.style.display = 'none'
        selectSubfilterValues.style.display = 'none'
        let selectSubfilterCriteriaNew = Util.clearListeners(selectSubfilterCriteria)
        selectSubfilterCriteriaNew.addEventListener('change', () => {
          this.processDateSelectionViewer(eventsContainer)
        })
      } else {
        selectFilterValues.style.display = 'none'
        inputLabelCriteria.style.display = 'none'
        selectSubfilterCriteria.style.display = 'none'
        inputLabelSubfilters.style.display = 'none'
      }
      this.processDateSelectionViewer(eventsContainer)
    })
    let selectFilterCriteriaMobileNew = Util.clearListeners(selectFilterCriteriaMobile)
    selectFilterCriteriaMobileNew.addEventListener('change', (ev: any) => {
      /* let target = ev.target as HTMLSelectElement
      let inputLabelCriteriaMobile = eventsContainer.querySelector('#input-label-criteria-mobile') as HTMLLabelElement
      let selectFilterValuesMobile = eventsContainer.querySelector('#select-filter-values-mobile') as HTMLSelectElement
      selectFilterValuesMobile.value = ""
      this.processDateSelectionViewer(eventsContainer)

      selectFilterValuesMobile.innerHTML = ""
      let option = new Option()
      option.value = "";
      option.innerHTML = "All";
      selectFilterValuesMobile.add(option)
      if (this.statisticsMeta[target.value] != null) {
        let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[target.value])
        selectFilterValuesMobile.style.display = 'block'
        inputLabelCriteriaMobile.style.display = 'block'
        inputLabelCriteriaMobile.innerHTML = target.value
        for (let filter of sortedFilters) {
          let option = new Option()
          option.value = filter.split(';')[1];
          option.innerHTML = filter.split(';')[0].replace(/\([^)]*\)/g, "")
          selectFilterValuesMobile.add(option)
        }
        let selectFilterValuesMobileNew = Util.clearListeners(selectFilterValuesMobile)
        selectFilterValuesMobileNew.addEventListener('change', () => {
          console.log('changed')
          this.processDateSelectionViewer(eventsContainer);
        })
      } else {
        selectFilterValuesMobile.style.display = 'none'
        inputLabelCriteriaMobile.style.display = 'none'
      } */
      console.log('statsoption change triggered');
      let target = ev.target as HTMLSelectElement
      this.statisticsSelectedFilter = target.value
      let inputLabelCriteriaMobile = eventsContainer.querySelector('#input-label-criteria-mobile') as HTMLLabelElement
      let selectFilterValuesMobile = eventsContainer.querySelector('#select-filter-values-mobile') as HTMLSelectElement
      selectFilterValuesMobile.value = ""
      let inputLabelSubfiltersMobile = eventsContainer.querySelector('#input-label-subfilter-mobile') as HTMLLabelElement
      let selectSubfilterCriteriaMobile = eventsContainer.querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement
      selectSubfilterCriteriaMobile.value = ""
      selectSubfilterCriteriaMobile.length = 0


      selectFilterValuesMobile.innerHTML = ""
      let option = new Option()
      option.value = "";
      option.innerHTML = "All";
      selectFilterValuesMobile.add(option)
      if (this.statisticsMeta[target.value] != null && target.value != "all") {
        let sortedFilters = Util.alphabeticalSort(this.statisticsMeta[target.value])
        selectFilterValuesMobile.style.display = 'block'
        inputLabelCriteriaMobile.style.display = 'block'
        inputLabelCriteriaMobile.innerHTML = target.value
        for (let filter of sortedFilters) {
          let option = new Option()
          option.value = filter.split(';')[1];
          option.innerHTML = filter.split(';')[0].replace(/\([^)]*\)/g, "")
          selectFilterValuesMobile.add(option)
        }
        let selectFilterValuesNew = Util.clearListeners(selectFilterValuesMobile)
        selectFilterValuesNew.addEventListener('change', () => {
          console.log('changed')
          this.processDateSelectionViewer(eventsContainer);
        })
        selectSubfilterCriteriaMobile.style.display = 'block'
        inputLabelSubfiltersMobile.style.display = 'block'
        let sortedSubfilters = Util.alphabeticalSort(Object.keys(this.statisticsMeta.subfilters))

        if (sortedSubfilters.length > 1) {
          let option = new Option()
          option.value = "";
          option.innerHTML = "None";
          selectSubfilterCriteriaMobile.add(option)
        }
        for (let subfilter of sortedSubfilters) {
          let option = new Option()
          option.value = subfilter;
          option.innerHTML = subfilter
          selectSubfilterCriteriaMobile.add(option)
        }
        let inputLabelSubfiltersValue = eventsContainer.querySelector('#input-label-subfilter-value-mobile') as HTMLLabelElement
        let selectSubfilterValues = eventsContainer.querySelector('#select-subfilter-values-mobile') as HTMLSelectElement
        inputLabelSubfiltersValue.style.display = 'none'
        selectSubfilterValues.style.display = 'none'
        let selectSubfilterCriteriaNew = Util.clearListeners(selectSubfilterCriteriaMobile)
        selectSubfilterCriteriaNew.addEventListener('change', () => {
          this.processDateSelectionViewer(eventsContainer)
        })
      } else {
        selectFilterValuesMobile.style.display = 'none'
        inputLabelCriteriaMobile.style.display = 'none'
        selectSubfilterCriteriaMobile.style.display = 'none'
        inputLabelSubfiltersMobile.style.display = 'none'
      }
      this.processDateSelectionViewer(eventsContainer)
    });
    (selectFilterCriteriaNew as HTMLSelectElement).value = filterscriteria;
    (selectFilterCriteriaMobileNew as HTMLSelectElement).value = filterscriteria;
    let selectFilterValues = eventsContainer.querySelector('#select-filter-values') as HTMLSelectElement
    let inputLabelCriteria = eventsContainer.querySelector('#input-label-criteria') as HTMLLabelElement
    let selectFilterValuesMobile = eventsContainer.querySelector('#select-filter-values-mobile') as HTMLSelectElement
    let inputLabelCriteriaMobile = eventsContainer.querySelector('#input-label-criteria-mobile') as HTMLLabelElement
    if (filterscriteria == "all") {
      selectFilterValues.style.display = 'none'
      inputLabelCriteria.style.display = 'none'
      selectFilterValuesMobile.style.display = 'none'
      inputLabelCriteriaMobile.style.display = 'none'
    } else {
      selectFilterValues.style.display = 'block'
      inputLabelCriteria.style.display = 'block'
      selectFilterValuesMobile.style.display = 'block'
      inputLabelCriteriaMobile.style.display = 'block'
    }
  }
  renderSelectAllButtons = () => {
    let selectAllHtml = '<div class="d-flex justify-end w-100" style="position: fixed; bottom: 70px; left: 0px; pointer-events: none" part="button-select-all-container">';
    selectAllHtml += '<button part="button-select-all" id="button-select-all" class="d-flex align-center mt-10 mr-10 ml-10" style="pointer-events: all"><span class="material-symbols-outlined">select_all</span>&nbsp;<h4>Select All</h4><span>&nbsp;(Max ' + this.selectallblock + ')</span></button>';
    selectAllHtml += '<button part="button-unselect-all" id="button-unselect-all" class="d-flex align-center mt-10 mr-10 ml-10" style="pointer-events: all"><span class="material-symbols-outlined">remove_selection</span>&nbsp;<h4>Unselect</h4></button>';
    selectAllHtml += '</div>';
    return selectAllHtml
  }
  attachSelectAllListeners = (eventsContainer: HTMLDivElement, buttonSelect: NodeListOf<HTMLInputElement>) => {
    const buttonSelectAll = eventsContainer.querySelector('#button-select-all') as HTMLButtonElement
    const buttonUnselectAll = eventsContainer.querySelector('#button-unselect-all') as HTMLButtonElement
    if (this.selectedItemIds.length == 0) {
      buttonSelectAll.style.display = 'none';
      buttonUnselectAll.style.display = 'none';
    }
    buttonSelectAll?.addEventListener('click', () => {
      let count = this.selectedItemIds.length
      for (let checkSelect of buttonSelect) {
        console.log('select count', count, parseInt(this.selectallblock))
        if (count < parseInt(this.selectallblock) && checkSelect.style.display != 'none' && !(checkSelect as HTMLInputElement).checked) {
          checkSelect.click();
          count++;
        }
        if (count >= parseInt(this.selectallblock)) {
          break;
        }
      }
      setTimeout(() => {
        console.log('Selected All', this.selectedItemIds);
      }, 1000)
    })
    buttonUnselectAll?.addEventListener('click', () => {
      for (let checkSelect of buttonSelect) {
        if ((checkSelect as HTMLInputElement).checked) {
          checkSelect.click();
        }
      }
    })
    return [buttonSelectAll, buttonUnselectAll]
  }
  renderRegisterEvents = (events: any, meta: string = "", searchCountryIndex: number = -1, searchIndex: number = -1, searchVal: string = "") => {

    var html = '';
    this.registerSelectedIds = []
    this.csvDataRegisters = '';
    let flagUpdateFilters = Object.keys(this.registerFilters).length == 0;
    const configHome = Util.getProjectConfigHome();
    const showUnderstood = (configHome.features == null || (configHome.features.indexOf('hide-understood') < 0)) && (this.myRole == this.TAB_REPORTER)
    console.log('showunderstood', configHome.features, showUnderstood);
    html += '<div class="d-flex flex-col align-end">'
    html += '<button id="button-export" part="button" class="d-flex justify-center align-center mr-10"><span class="material-symbols-outlined">download</span>&nbsp;&nbsp;<span>Export Register</span></button>';
    html += '</div>'
    html += '<div class="d-flex scroll-x w-100p">';

    for (var i = 0; i < Object.keys(events).length; i++) {
      const country = Object.keys(events)[i];
      html += ('<button class="tab-button tab-button-country" id="tab-button-country-' + i + '" part="' + (this.selectedCountryTab == i ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">' + country + '</button>');
    }

    html += '</div>';

    html += '<div id="register-list" class="pl-10 pt-10"></div>';
    if (this._SfRegisterContainer.querySelector('.calendar-right-data-register') == null) { return; }
    this._SfRegisterContainer.querySelector('.calendar-right-data-register').innerHTML = html;

    const divRegisterList = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#register-list');

    const arrButtons = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.tab-button-country') as NodeListOf<HTMLButtonElement>;

    for (i = 0; i < arrButtons.length; i++) {
      const button = Util.clearListeners(arrButtons[i]);
      button.addEventListener('click', (e: any) => {
        const index = e.currentTarget.id.split('-')[3];
        this.selectedCountryTab = index
        this.selectedRegisterIndex = -1
        this.renderRegisterEvents(events);
      });
    }
    this.tablecols = []
    let linesCount = 0;
    let searchFilterString = ""
    if (this.selectedCountryTab >= 0) {

      const index = this.selectedCountryTab;
      //console.log('indexclicked', index);

      const objCountry = events[Object.keys(events)[index]];
      //console.log('indexclicked', objCountry);

      var html = '';
      this.csvDataRegisters += '"ID",';
      linesCount = 0
      for (var i = 0; i < Object.keys(objCountry).length; i++) {

        const statute = Object.keys(objCountry)[i];

        // this.csvDataRegisters += ('\n\n"' + statute + '"\n\n');

        html += ('<h3 part="register-section-title-' + (i != this.selectedRegisterIndex ? 'not-selected' : 'selected') + '" class="left-sticky register-statute" id="register-statute-' + i + '">' + statute + '</h3>');
        // html += '<div class="w-100p scroll-x '+(i != 0 ? 'hide' : '')+'" id="register-body-'+i+'" >';
        //   html += '<table>';

        if (i == this.selectedRegisterIndex && meta == "") {
          console.log('meta', meta, this.selectedCountryTab);
          for (var k = 0; k < JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols).length; k++) {
            if (!this.EXCLUDE_COLS_FROM_REGS.includes(JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k].toLowerCase())) {
              this.csvDataRegisters += ('"' + JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k] + '",');

              console.log('loggin col', JSON.parse(objCountry[statute][Object.keys(objCountry[statute])[0]].cols)[k])
            }

          }
          this.csvDataRegisters = this.csvDataRegisters.replace(/,\s*$/, "");
          this.csvDataRegisters += ('\n');
        } else {
          continue;
        }
        html += '<div class="w-100p scroll-x ' + (i != this.selectedRegisterIndex ? 'hide' : '') + ' register-body-' + i + '">';

        html += '<div class="d-flex flex-col align-stretch left-sticky">';
        html += '<div class="d-flex justify-between align-end" part="register-search-container">'
        html += '<div class="title-item-date">';
        html += '<label part="input-label">Search In Statute</label><br />'
        html += '<div class="d-flex align-end">'
        html += '<input id="stream-search-statute-' + index + '-' + i + '" part="input" class="stream-search-statute" type="text" value="' + ((searchCountryIndex == index && searchIndex == i) ? searchVal : "") + '"/>'
        html += '<button id="button-search-statute-' + index + '-' + i + '" part="button" class="button-search-statute d-flex justify-center align-center ml-10"><span class="material-symbols-outlined">search</span></button>';
        if (showUnderstood) {
          html += '<button id="button-accept-all" part="button-accept-selected" class="d-flex justify-center align-center ml-10 hide"><span class="material-symbols-outlined">check</span>&nbsp;&nbsp;Accept Selected</button>';
        }
        html += '</div>';
        html += '</div>';
        html += '<div class="title-item-date">';
        html += '<button id="button-download-statute-' + index + '-' + i + '" part="button" class="button-download-statute d-flex justify-center align-center ml-10 hide"><span class="material-symbols-outlined">download</span>&nbsp;&nbsp;<span>Export</span></button>';
        html += '</div>';
        html += '</div>';
        html += '<div id="filter-string" part="filter-string" class="d-flex align-center">Test String</div>'
        html += '</div>';
        html += '<table>';
        let tableBodyHtml = ''

        for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) {

          const complianceId = Object.keys(objCountry[statute])[j];
          const compliance = objCountry[statute][complianceId];
          console.log('hidecompliances', compliance.hide, complianceId);
          const understood = objCountry[statute][complianceId]['understood'] ?? -1
          const data = JSON.parse(compliance.data);
          const cols = JSON.parse(compliance.cols);
          if (!this.tablecols.includes('ID') && !this.EXCLUDE_COLS_FROM_REGS.includes('ID')) {
            this.tablecols.push('ID')
          }

          // for (let col of cols) {
          for (let registercol of this.COLS_REGS) {
            if (!this.tablecols.includes(registercol.toLowerCase())) {
              this.tablecols.push(registercol)
              if (flagUpdateFilters && this.registerFilters[registercol] == null) {
                this.registerFilters[registercol] = {}
              }
            }
          }
          // }

          if (compliance.hide != null && compliance.hide == true) {
            continue;
          }
          linesCount++
          let understoodMessage = 'Not reviewed'
          let understoodMessagePart = 'mark-understood-message'
          if (showUnderstood) {
            switch (understood) {
              case 0:
                understoodMessage = "Not Understood";
                understoodMessagePart = "mark-understood-not-understood"
                break;
              case 1:
                understoodMessage = "Compliance Understood";
                understoodMessagePart = "mark-understood-compliance-understood"
                break;
              case 2:
                understoodMessage = "Applicability Not Clear";
                understoodMessagePart = "mark-understood-not-applicable"
                break;
              case 3:
                understoodMessage = "Compliance and applicability Understood";
                understoodMessagePart = "mark-understood-compliance-applicability-understood"
                break;
              case 4:
                understoodMessage = "Accepted";
                understoodMessagePart = "mark-understood-accepted"
                break;
              case 5:
                understoodMessage = "Not For Me";
                understoodMessagePart = "mark-understood-not-accepted"
                break;
              default:
                understoodMessage = "Not reviewed";
                understoodMessagePart = "mark-understood-not-reviewed"
                break;
            }
          }
          this.csvDataRegisters += ('"' + complianceId + '",');
          // html += '<div class="w-100p scroll-x ' + (i != this.selectedRegisterIndex ? 'hide' : '') + ' register-body-' + i + '">';
          // html += '<table>';
          tableBodyHtml += '<tr>';
          if (showUnderstood) {
            tableBodyHtml += ('<td class="td-body left-sticky" part="td-body-register-check"><input type="checkbox" id="input-check-' + index + '-' + i + '-' + j + '" class="input-check"' + ((this.registerSelectedIds.indexOf(compliance.id) >= 0) ? " checked" : '') + '></td>');
          }
          tableBodyHtml += ('<td class="td-body left-sticky d-flex align-start" part="td-body-register-open"><button part="button-icon" id="button-icon-country-' + index + '-' + i + '-' + j + '" class="button-icon-country"><span class="material-symbols-outlined">open_in_new</span></button>')
          if (showUnderstood) {
            tableBodyHtml += '<span part="' + understoodMessagePart + '">' + understoodMessage + '</span>'
          }
          tableBodyHtml += '</div></td>';
          if (flagUpdateFilters) {
            if (this.registerFilters["ID"] == null) {
              this.registerFilters["ID"] = {}
            }
            this.registerFilters["ID"][complianceId] = true;
          }
          tableBodyHtml += ('<td class="td-body" part="td-body-register"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + complianceId + '" highlight="' + searchVal + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');

          // tableBodyHtml += ('<td class="td-body" part="td-body-register"><span part="td-head" style="padding-left: 0px !important">ID</span><br /><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + complianceId + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
          // let tempCount = 0;
          for (let registercol of this.COLS_REGS) {
            if (compliance[registercol] != null) {
              console.log("Fetching from compliance", registercol)
              let colVal = compliance[registercol] + ""
              if (Array.isArray(compliance[registercol])) {
                colVal = ""
                for (let registerColVal of compliance[registercol]) {
                  colVal += registerColVal.split(';')[0]
                  if (registerColVal.indexOf(compliance[registercol]) < (compliance[registercol].length - 1)) {
                    colVal += ", "
                  }
                }
              }
              console.log('ColVal', compliance[registercol], colVal)
              tableBodyHtml += ('<td class="td-body" part="td-body-register"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + colVal + '" highlight="' + searchVal + '" minLength="80" lineSize="4"></sf-i-elastic-text></td>');
              this.csvDataRegisters += ('"' + (colVal + "").replace(/"/g, '') + '",');
              // this.csvDataRegisters += ('",');

              if (flagUpdateFilters) {

                this.registerFilters[registercol][colVal.toString().trim()] = true;
                // if (cols[k] == "thirdlineofdefence") {
                //   console.log('thirdlineofdefence', data[k], this.registerFilters[cols[k]], k + 1, cols[k])
                // }
              }
              // tempCount++;
              // } else {
              //   console.log('skipping col', cols[k], this.tablecols.indexOf(cols[k]), k + 1)
              // }
            } else if (cols.indexOf(registercol) >= 0) {
              let k = cols.indexOf(registercol)
              console.log('fetching from cols', registercol, k, data[k])
              // for (var k = 0; k < cols.length; k++) {
              // if (!this.EXCLUDE_COLS_FROM_REGS.includes(cols[k].toLowerCase()) && this.tablecols.indexOf(cols[k]) == tempCount + 1) {
              // tableBodyHtml += ('<td class="td-body" part="td-body-register"><span part="td-head" style="padding-left: 0px !important">' + cols[k] + '</span><br /><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + data[k] + '" minLength="80" lineSize="4"></sf-i-elastic-text></td>');
              tableBodyHtml += ('<td class="td-body" part="td-body-register"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + data[k] + '" highlight="' + searchVal + '" minLength="80" lineSize="4"></sf-i-elastic-text></td>');
              this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",');
              // this.csvDataRegisters += ('",');

              if (flagUpdateFilters) {

                this.registerFilters[cols[k]][data[k].toString().trim()] = true;
                if (cols[k] == "thirdlineofdefence") {
                  console.log('thirdlineofdefence', data[k], this.registerFilters[cols[k]], k + 1, cols[k])
                }
              }
              // tempCount++;
            } else {
              console.log("column not found", registercol, Object.keys(compliance))
            }
          }
          if (compliance['entities'] != null && Array.isArray(compliance['entities'])) {
            let entities = '';
            for (let entity of compliance['entities']) {
              entities += entity.split(';')[0].replace(/\([^)]*\)/g, "") + ','
            }
            entities = entities.slice(0, entities.length - 1)
            tableBodyHtml += ('<td class="td-body" part="td-body-register"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + entities + '" highlight="' + searchVal + '" minLength="80" lineSize="4"></sf-i-elastic-text></td>');
            if (!this.tablecols.includes('entities') && !this.EXCLUDE_COLS_FROM_REGS.includes('entities')) {
              this.tablecols.push('entities')
            }
            if (flagUpdateFilters) {
              if (this.registerFilters["entities"] == null) {
                this.registerFilters["entities"] = {}
              }
              this.registerFilters["entities"][entities] = true;
            }
            // this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",');
          }
          if (compliance['locations'] != null && Array.isArray(compliance['locations'])) {
            let locations = '';
            for (let location of compliance['locations']) {
              locations += location.split(';')[0].replace(/\([^)]*\)/g, "") + ','
            }
            locations = locations.slice(0, locations.length - 1)
            tableBodyHtml += ('<td class="td-body" part="td-body-register"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + locations + '" highlight="' + searchVal + '" minLength="80" lineSize="4"></sf-i-elastic-text></td>');
            if (!this.tablecols.includes('locations') && !this.EXCLUDE_COLS_FROM_REGS.includes('locations')) {
              this.tablecols.push('locations')
            }
            if (flagUpdateFilters) {
              if (this.registerFilters["locations"] == null) {
                this.registerFilters["locations"] = {}
              }
              this.registerFilters["locations"][locations] = true;
            }
            // this.csvDataRegisters += ('"' + (data[k] + "").replace(/"/g, '') + '",');
          }
          this.csvDataRegisters = this.csvDataRegisters.replace(/,\s*$/, "");
          this.csvDataRegisters += ('\n');
          console.log('enter');
          tableBodyHtml += '</tr>';
          // html += '</table>';
          // html += '</div>';
        }
        html += '<thead><tr>';
        if (showUnderstood) {
          html += '<th class="td-body" part="td-body-check"><input type="checkbox" id="input-check-all" class="input-check-all"' + ((this.registerSelectedIds.length > 0 && this.registerSelectedIds.length == objCountry[statute].length) ? " checked" : '') + '></th>'
        }
        html += '<th class="td-body" part="td-body-register"><span part="td-head" style="padding-left: 0px !important"></span></th>'
        searchFilterString = ""
        for (let colName of this.tablecols) {
          let allSelected = true;
          for (let subfilterObj of Object.keys(this.registerFilters[colName] ?? {})) {
            if (this.registerFilters[colName][subfilterObj] == false) {
              allSelected = false;
              for (let subfilterObjVal of Object.keys(this.registerFilters[colName] ?? {})) {
                if (this.registerFilters[colName][subfilterObjVal] == true) {
                  if (searchFilterString == "") {
                    searchFilterString += subfilterObjVal
                  } else {
                    searchFilterString += ', ' + subfilterObjVal
                  }
                }
              }
              break;
            }
          }

          html += '<th class="td-body" part="td-body-register"><div class="d-flex align-start"><span part="' + (allSelected ? 'td-head' : 'td-head-selected') + '" style="' + (allSelected ? 'padding-left: 0px !important' : '') + '">' + colName + '</span><div class="filter-button-container ml-10"><button part="' + (allSelected ? 'col-icon' : 'col-icon-selected') + '" id="filter-button-' + this.tablecols.indexOf(colName) + '" class="filter-button material-symbols-outlined">filter_list</button>'
          html += '<div id="filter-list-container-' + this.tablecols.indexOf(colName) + '" class="filter-list-container hide flex-col justify-between align-start p-10" part="filter-list-container" anchor="filter-button">'
          html += `<div id="filter-label-container-${this.tablecols.indexOf(colName)}" class="filter-label-container d-flex justify-between align-center" part="filter-label-container"><div class="d-flex align-center"><input class="input-select-filter" type="checkbox" ${allSelected ? 'checked' : ''} id="input-select-filter-${this.tablecols.indexOf(colName)}-all" name="features" part="input-select-feature" value="all-${colName}"></input><label class="filter-label" part="filter-label" for="input-select-filter-${this.tablecols.indexOf(colName)}-all">All</label></div><button id="button-submit-filters-${this.tablecols.indexOf(colName)}" part="col-option-icon" class="button-submit-filters material-icons invisible">check</button></div>`
          for (let [index, filterKey] of Object.keys(this.registerFilters[colName]).entries()) {
            // console.log('rendering filter', filterKey);
            html += `<div class="filter-input-container d-flex justify-start align-start"><input class="input-select-filter" type="checkbox" ${this.registerFilters[colName][filterKey] == true ? 'checked' : ''} id="input-select-filter-${this.tablecols.indexOf(colName)}-${index}" name="features" part="input-select-feature" value="${filterKey}"></input><label for="input-select-filter-${this.tablecols.indexOf(colName)}-${index}" id="input-select-filter-label-${this.tablecols.indexOf(colName)}-${index}" class="input-select-filter-label"  part="input-select-feature-label">${filterKey}</label></div>`
          }
          html += '</div></div></th>'
        }
        html += '</tr></thead>';
        html += tableBodyHtml;
        html += '</table>';
        html += '</div>';

        //   html += '</table>';
        // html += '</div>';

      }

      divRegisterList!.innerHTML = html;
      console.log('registerFilters', flagUpdateFilters, this.registerFilters, html.indexOf('input-select-filter-0-0'));
      // console.log('csvdataregisters', this.csvDataRegisters);
      let buttonExportRegister = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-export') as HTMLButtonElement
      buttonExportRegister?.addEventListener('click', () => {
        this.exportRegister();
      })
      if (this.selectedRegisterIndex >= 0) {
        const divFilterString = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#filter-string') as HTMLDivElement
        let filterString = ""
        if (searchVal != "" || searchFilterString != "") {
          filterString = linesCount + " result(s) when "
          if (searchVal != "") {
            filterString += "searched by \"" + searchVal + "\""
            if (searchFilterString != "") {
              filterString += ", filtered by \"" + searchFilterString + "\""
            }
          } else if (searchFilterString != "") {
            filterString += "filtered by \"" + searchFilterString + "\""
          }
        }
        if (filterString != "") {
          filterString += '<span class="material-symbols-outlined ml-5" id="filter-delete" part="filter-delete">delete</span>'
        }
        if (divFilterString != null) {
          divFilterString.innerHTML = filterString
        }
        const filterDeleteButton = divFilterString.querySelector('#filter-delete') as HTMLSpanElement;
        filterDeleteButton?.addEventListener('click', () => {
          for (let col of Object.keys(this.registerFilters)) {
            for (let filterVal of Object.keys(this.registerFilters[col])) {
              this.registerFilters[col][filterVal] = true;
            }
          }
          this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, "");
        })
      }

      const arrButtonCountries = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-icon-country') as NodeListOf<HTMLButtonElement>;

      for (i = 0; i < arrButtonCountries.length; i++) {
        const button = Util.clearListeners(arrButtonCountries[i]);

        button.addEventListener('click', (e: any) => {

          const index = e.currentTarget.id.split('-')[3];
          const i1 = e.currentTarget.id.split('-')[4];
          const j1 = e.currentTarget.id.split('-')[5];
          //console.log('country clicked', index, i1, j1);

          const objCountry = events[Object.keys(events)[index]];
          const statute = Object.keys(objCountry)[i1];
          const complianceId = Object.keys(objCountry[statute])[j1];
          const compliance = objCountry[statute][complianceId];

          this.renderEventDetailShort(compliance, Object.keys(events)[index], statute);

        });
      }

      const buttonAcceptAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-accept-all') as HTMLButtonElement

      buttonAcceptAll?.addEventListener('click', async () => {
        console.log('accepting', this.registerSelectedIds);
        let resultMarkUnderstoodBulk = await this.markUnderstoodBulk(this.registerSelectedIds, this.userProfileId, 4);
        console.log('markUnderstoodBulk result', resultMarkUnderstoodBulk);
        let objCountry = events[Object.keys(events)[this.selectedCountryTab]];
        const statute = Object.keys(objCountry)[this.selectedRegisterIndex];
        console.log('objectCountry', Object.keys(objCountry), this.selectedRegisterIndex, statute, objCountry[statute]);
        for (let complianceId of Object.keys(objCountry[statute])) {
          console.log('changing understood', complianceId, this.registerSelectedIds.indexOf(complianceId));
          if (this.registerSelectedIds.indexOf(complianceId) >= 0) {
            objCountry[statute][complianceId].understood = 4
          }
        }
        events[Object.keys(events)[searchCountryIndex]] = objCountry
        this.registerEvents = events;
        this.renderRegisterEvents(this.registerEvents, meta, searchCountryIndex, searchIndex, searchVal);
      })
      const arrInputChecks = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-check') as NodeListOf<HTMLInputElement>;

      for (i = 0; i < arrInputChecks.length; i++) {
        const checkbox = Util.clearListeners(arrInputChecks[i]);

        checkbox.addEventListener('change', (e: any) => {

          const index = e.currentTarget.id.split('-')[2];
          const i1 = e.currentTarget.id.split('-')[3];
          const j1 = e.currentTarget.id.split('-')[4];
          //console.log('country clicked', index, i1, j1);

          const objCountry = events[Object.keys(events)[index]];
          const statute = Object.keys(objCountry)[i1];
          const complianceId = Object.keys(objCountry[statute])[j1];
          // const compliance = objCountry[statute][complianceId];
          let tempArr = this.registerSelectedIds
          if (tempArr.indexOf(complianceId) >= 0) {
            tempArr.splice(tempArr.indexOf(complianceId), 1);
          }
          if (e.currentTarget.checked && this.registerSelectedIds.indexOf(complianceId) < 0) {
            tempArr.push(complianceId)
          }
          this.registerSelectedIds = tempArr
          console.log('input clicked', statute, i1, j1, complianceId, this.registerSelectedIds)
          if (!e.currentTarget.checked) {
            const inputCheckAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-check-all') as HTMLInputElement
            inputCheckAll.checked = false;
          }
          if (this.registerSelectedIds.length > 0) {
            buttonAcceptAll.classList.remove('hide')
          } else {
            buttonAcceptAll.classList.add('hide')
          }

        });
      }

      const inputCheckAll = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-check-all') as HTMLInputElement

      inputCheckAll?.addEventListener('change', (e) => {
        if (e.currentTarget == null) {
          console.log('returning')
          return;
        }
        let arrInputChecksTemp = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-check') as NodeListOf<HTMLInputElement>;
        console.log('input check length', arrInputChecksTemp.length)
        for (let inputCheck of arrInputChecksTemp) {
          console.log('checking all', (e.currentTarget as HTMLInputElement).checked)
          inputCheck.checked = (e.currentTarget as HTMLInputElement).checked
          inputCheck.dispatchEvent(
            new Event("change", { bubbles: true })
          );
        }
        // if ((e.currentTarget as HTMLInputElement).checked) {
        //   buttonAcceptAll.classList.remove('hide')
        // } else {
        //   buttonAcceptAll.classList.add('hide')
        // }
      })

      const arrRegisterStatutes = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.register-statute') as NodeListOf<HTMLDivElement>;
      for (i = 0; i < arrRegisterStatutes.length; i++) {

        const button = Util.clearListeners(arrRegisterStatutes[i]);
        button.addEventListener('click', async (e: any) => {

          // const button = (e.currentTarget as HTMLDivElement);
          const index = e.currentTarget.id.split('-')[2];
          console.log('index', index);
          if (this.selectedRegisterIndex == index) {
            this.selectedRegisterIndex = -1;
          } else {
            this.selectedRegisterIndex = index;
            let selectedCountry = Object.keys(events)[this.selectedCountryTab]
            let selectedStatute = Object.keys(events[selectedCountry])[index]
            console.log('registerevents', Object.keys(events[selectedCountry][selectedStatute]).length)
            if (Object.keys(events[selectedCountry][selectedStatute]).length == 0) {
              let tempRegisters = await this.fetchRegisters("", "", selectedCountry, selectedStatute);
              this.registerEvents[selectedCountry][selectedStatute] = tempRegisters[selectedCountry][selectedStatute]
            }
          }
          this.renderRegisterEvents(this.registerEvents);
          // const divBodys = ((this._SfRegisterContainer.querySelector('.calendar-right-data') as HTMLDivElement).querySelectorAll('.register-body-'+ index) as NodeListOf<HTMLDivElement>);
          // for(let divBody of divBodys){
          //   if(divBody.classList.contains('hide')) {
          //     divBody.classList.remove('hide')
          //     button.setAttribute('part','register-section-title-selected');
          //   } else {
          //     divBody.classList.add('hide')
          //     button.setAttribute('part','register-section-title-not-selected');
          //   }
          // }

        });

      }

      const arrInputStatuteSearch = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.stream-search-statute') as NodeListOf<HTMLInputElement>;
      for (i = 0; i < arrInputStatuteSearch.length; i++) {
        const input = Util.clearListeners(arrInputStatuteSearch[i]);
        input.addEventListener('change', (e: any) => {
          const searchedValue = e.currentTarget.value;
          const countryIndex = e.currentTarget.id.split('-')[3];
          const searchIndex = e.currentTarget.id.split('-')[4];
          // const objCountry = events[Object.keys(events)[countryIndex]]
          // const statute = Object.keys(objCountry)[searchIndex];
          // for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) {
          //   const complianceId = Object.keys(objCountry[statute])[j];
          //   const compliance = objCountry[statute][complianceId];
          //   if (JSON.stringify(compliance).toLowerCase().includes(searchedValue.toLowerCase())) {
          //     events[Object.keys(events)[countryIndex]][statute][complianceId].hide = false;
          //   } else {
          //     events[Object.keys(events)[countryIndex]][statute][complianceId].hide = true;
          //   }
          // }

          this.processRegisterFilters(events, meta, countryIndex, searchIndex, searchedValue);
          // this.renderRegisterEvents(events, meta, countryIndex, searchIndex, searchedValue);

        })
      }
      const arrButtonStatuteSearch = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-search-statute') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrButtonStatuteSearch.length; i++) {
        const button = Util.clearListeners(arrButtonStatuteSearch[i]);
        button.addEventListener('click', (e: any) => {
          const inputId = e.currentTarget.id.replace('button-', 'stream-')
          const searchedValue = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector(inputId).value;
          const countryIndex = e.currentTarget.id.split('-')[3];
          const searchIndex = e.currentTarget.id.split('-')[4];
          this.processRegisterFilters(events, meta, countryIndex, searchIndex, searchedValue);

        })
      }

      const arrButtonDownloadStatute = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-download-statute') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrButtonDownloadStatute.length; i++) {
        const button = Util.clearListeners(arrButtonDownloadStatute[i]);
        button.addEventListener('click', (e: any) => {
          const countryIndex = e.currentTarget.id.split('-')[3];
          const searchIndex = e.currentTarget.id.split('-')[4];
          const objCountry = events[Object.keys(events)[countryIndex]]
          const statute = Object.keys(objCountry)[searchIndex];
          let csvData = '"ID","Country","Entities","Locations","Statute","Reference","Obligation Title"\n';
          for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) {
            const complianceId = Object.keys(objCountry[statute])[j];
            const compliance = objCountry[statute][complianceId];
            console.log('hidecompliances', compliance.hide, complianceId);
            if (compliance.hide != null && compliance.hide == true) {
              continue;
            }

            const data = JSON.parse(compliance.data);
            const cols = JSON.parse(compliance.cols);
            csvData += ('"' + complianceId + '",');
            csvData += ('"' + Object.keys(events)[countryIndex] + '",');
            csvData += ('"' + (compliance['entities'] != null && Array.isArray(compliance['entities']) ? compliance['entities'].map((e: string) => e.split(';')[0].replace(/\([^)]*\)/g, "")).join(',') : '') + '",');
            csvData += ('"' + (compliance['locations'] != null && Array.isArray(compliance['locations']) ? compliance['locations'].map((e: string) => e.split(';')[0].replace(/\([^)]*\)/g, "")).join(',') : '') + '",');
            csvData += ('"' + statute + '",');
            csvData += ('"' + data[cols.indexOf('reference')] + '",');
            csvData += ('"' + data[cols.indexOf('obligationtitle')] + '"\n');
          }
          console.log('csvData', csvData);
          const ts = new Date();
          let fileName = 'register_' + statute.replace(/ /g, '_').slice(0, 25) + '_' + ts + '.xlsx'
          Util.downloadExcelFromCSV(csvData, fileName, "Register Export", this.projectName);
        })
      }

      const arrFilterButtons = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.filter-button') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrFilterButtons.length; i++) {
        const button = Util.clearListeners(arrFilterButtons[i]);
        button.addEventListener('click', (e: any) => {
          const index = e.currentTarget.id.split('-')[2];
          let filterListContainer = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#filter-list-container-' + index) as HTMLDivElement;
          if (filterListContainer != null) {
            if (filterListContainer.classList.contains('hide')) {
              filterListContainer.classList.remove('hide');
            } else {
              filterListContainer.classList.add('hide');
            }
          }
        })
      }

      const arrFilterInputs = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.input-select-filter') as NodeListOf<HTMLInputElement>;
      for (i = 0; i < arrFilterInputs.length; i++) {
        const input = Util.clearListeners(arrFilterInputs[i]);
        input.addEventListener('change', (e: any) => {
          let checked = e.currentTarget.checked;
          let selectedColIndex = e.currentTarget.id.split('-')[3];
          let selectedFilterIndex = e.currentTarget.id.split('-')[4];
          let colName = this.tablecols[selectedColIndex]
          // for (let [colIndex, colName] of Object.keys(this.registerFilters).entries()) {
          if (colName != null) {
            for (let [filterIndex, filterKey] of Object.keys(this.registerFilters[colName]).entries()) {
              if (filterIndex == parseInt(selectedFilterIndex) || selectedFilterIndex == 'all') {
                this.registerFilters[colName][filterKey] = checked;
                console.log('registerFilters entry', this.registerFilters[colName][filterKey], colName, filterKey);
              }
              if (selectedFilterIndex == 'all') {
                ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-' + filterIndex) as HTMLInputElement).checked = checked;
              }
            }
            if (!checked) {
              ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-all') as HTMLInputElement).checked = checked;
            }
            if (selectedFilterIndex == 'all') {
              for (let [filterIndex, filterKey] of Object.keys(this.registerFilters[colName]).entries()) {
                ((this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#input-select-filter-' + selectedColIndex + '-' + filterIndex) as HTMLInputElement).checked = checked;
                console.log('Changing Key', filterKey);
              }
            }
          }
          // }
          // this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, searchVal);
          const buttonSubmitFilters = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#button-submit-filters-' + selectedColIndex) as HTMLButtonElement
          if (buttonSubmitFilters != null) {
            buttonSubmitFilters.style.visibility = 'visible'
          }
          console.log('registerFilters applying', colName, selectedFilterIndex, this.tablecols)
        })
      }

      const arrButtonSubmitFilters = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelectorAll('.button-submit-filters') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrButtonSubmitFilters.length; i++) {
        const button = Util.clearListeners(arrButtonSubmitFilters[i])
        button.addEventListener('click', (e: any) => {
          console.log('registerFilters applied', e.currentTarget.id)
          this.processRegisterFilters(events, meta, searchCountryIndex, searchIndex, searchVal);
        })
      }
      const registerStatute = (this._SfRegisterContainer.querySelector('.calendar-right-data-register') as HTMLDivElement).querySelector('#register-statute-' + this.selectedRegisterIndex) as HTMLDivElement;
      if (registerStatute != null) {
        registerStatute.scrollIntoView();
      }


    } else {
      const index = 0;
      this.selectedCountryTab = index
      this.renderRegisterEvents(events, meta);
    }

  }

  processRegisterFilters = (events: any, meta: string = "", searchCountryIndex: number = -1, searchIndex: number = -1, searchVal: string = "") => {
    if (this.selectedCountryTab >= 0) {
      const index = this.selectedCountryTab;
      //console.log('indexclicked', index);

      const objCountry = events[Object.keys(events)[index]];
      for (var i = 0; i < Object.keys(objCountry).length; i++) {

        const statute = Object.keys(objCountry)[i];
        for (var j = 0; j < Object.keys(objCountry[statute]).length; j++) {
          let flagFilter = true;
          const complianceId = Object.keys(objCountry[statute])[j];
          events[Object.keys(events)[index]][statute][complianceId].hide = false;
          if (this.registerFilters['ID'][complianceId] == false) {
            flagFilter = false;
            events[Object.keys(events)[index]][statute][complianceId].hide = true;
          }
          const compliance = objCountry[statute][complianceId];
          const data = JSON.parse(compliance.data);
          const cols = JSON.parse(compliance.cols);
          for (var k = 0; k < cols.length; k++) {
            if (this.registerFilters[cols[k]] != null && this.registerFilters[cols[k]][data[k]] == false) {
              flagFilter = false
              events[Object.keys(events)[index]][statute][complianceId].hide = true;
            } else {
              console.log('notFound', k, this.registerFilters[cols[k]])
            }
          }
          if (JSON.stringify(compliance).toLowerCase().includes(searchVal.toLowerCase())) {
            if (flagFilter) {
              events[Object.keys(events)[index]][statute][complianceId].hide = false;
            }
          } else {
            events[Object.keys(events)[index]][statute][complianceId].hide = true;
          }
        }
      }
    }

    this.renderRegisterEvents(events, meta, searchCountryIndex, searchIndex, searchVal);
  }
  checkStartDateEarliness = (value: string) => {

    var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    var startDateChosen = new Date(value);

    if (startDateChosen.getTime() > startDateCalendar.getTime()) {
      return true;
    } else {
      return false;
    }
  }

  checkEndDateLateness = (value: string) => {

    var endDateCalendar = new Date(this.calendarStartMM + '/' + (this.calendarStartDD + 10) + '/' + (parseInt(this.calendarStartYYYY) + 1));
    var endDateChosen = new Date(value);

    //console.log('end date calendar', endDateCalendar);
    //console.log('end date chosen', endDateChosen);

    if (endDateChosen.getTime() > endDateCalendar.getTime()) {
      return false;
    } else {
      return true;
    }
  }

  attachHandlers = (eventContainer: HTMLDivElement, valueStart: string, valueEnd: string) => {

    const radioCompleteness = eventContainer.querySelector('#radio-completeness') as HTMLButtonElement;
    radioCompleteness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderCompletenessGraph(eventContainer);
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioTimeliness = eventContainer.querySelector('#radio-timeliness') as HTMLButtonElement;
    radioTimeliness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_TIMELINESS;
      //console.log('setting flow graph to ', this.flowGraph);
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderTimelinessGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioCompliance = eventContainer.querySelector('#radio-compliance') as HTMLButtonElement;
    radioCompliance?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLIANCE;
      //console.log('setting flow graph to ', this.flowGraph);
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderComplianceGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioRisk = eventContainer.querySelector('#radio-risk') as HTMLButtonElement;
    radioRisk?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKAREAS;
      // console.log('setting flow graph to ', this.flowGraph);
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderRiskGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioFunction = eventContainer.querySelector('#radio-function') as HTMLButtonElement;
    radioFunction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FUNCTION;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderFunctionGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });


    const radioRiskSeverity = eventContainer.querySelector('#radio-riskseverity') as HTMLButtonElement;
    radioRiskSeverity?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderRiskSeverityGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioObligationType = eventContainer.querySelector('#radio-obligationtype') as HTMLButtonElement;
    radioObligationType?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderObligationTypeGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioJurisdiction = eventContainer.querySelector('#radio-jurisdiction') as HTMLButtonElement;
    radioJurisdiction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_JURISDICTION;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderJurisdictionGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    const radioFrequency = eventContainer.querySelector('#radio-frequency') as HTMLButtonElement;
    radioFrequency?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FREQUENCY;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderFrequencyGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });


    const radioSubcategory = eventContainer.querySelector('#radio-subcategory') as HTMLButtonElement;
    radioSubcategory?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderSubcategoryGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });


    const radioLocation = eventContainer.querySelector('#radio-location') as HTMLButtonElement;
    radioLocation?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_LOCATION;
      this.renderRangeEvents(new Date(valueStart), (new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), eventContainer);
      this.renderLocationGraph(eventContainer)
      this.attachHandlers(eventContainer, valueStart, valueEnd);

    });

    // const buttonStatusMore = (this._SfCustomContainer as HTMLDivElement).querySelector('#button-status-more');
    // buttonStatusMore?.addEventListener('click', () => {

    //   const divStatusList = (this._SfCustomContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf<HTMLDivElement>;
    //   for(var i = 0; i < divStatusList.length; i++) {
    //     divStatusList[i].style.display = 'flex';
    //   }
    //   (buttonStatusMore as HTMLButtonElement).style.display = 'none';

    // });

  }

  processFindSelection = async (eventContainer: HTMLDivElement, searchString: string) => {
    var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1));

    const tsStart = new Date(startDateCalendar);
    const tsEnd = new Date(endDateCalendar);
    tsStart.setDate(tsStart.getDate() - 2);
    tsEnd.setDate(tsEnd.getDate() + 2);

    //console.log('tsstart', tsStart);
    //console.log('tsend', tsEnd);

    // await this.fetchUserCalendar_2(tsStart.getMonth() + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), valueEnd.split('-')[1] + "/" + valueEnd.split('-')[2] + "/" + valueEnd.split('-')[0]);
    await this.fetchAndYearlyRenderUserCalendar_2((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear(), searchString);
    this.renderRangeEvents(startDateCalendar, ((endDateCalendar.getTime() + 24 * 60 * 60 * 1000) - startDateCalendar.getTime()) / (1000 * 60 * 60 * 24), (this._SfFindContainer as HTMLDivElement));

    this.attachHandlers(eventContainer, this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY, this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1));

    if (eventContainer.innerHTML.indexOf('myChart') >= 0) {

      this.renderCompletenessGraph(eventContainer);

    }
  }

  processDateSelection = async (eventContainer: HTMLDivElement, fetchData: boolean = true, showBackgroundButton: boolean = false) => {

    // var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    // var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1));

    var valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value;
    if (valueStart == "") {
      valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value;
    }
    var valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value;
    if (valueEnd == "") {
      valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value;
    }

    if (this.mode == "viewer") {
      valueStart = this.sdate;
      valueEnd = this.edate;
    }
    //console.log('valuestart', valueStart);
    //console.log('valueend', valueEnd);


    if (valueStart != "" && valueEnd != "") {
      this.initCustomRightCol();
      // if(!this.checkStartDateEarliness(valueStart)) {
      //   (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen Start Date cannot be earlier than " + startDateCalendar;
      //   return;
      // }
      // if(!this.checkEndDateLateness(valueEnd)) {
      //   (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be later than " + endDateCalendar;
      //   return;
      // }
      if (new Date(valueStart).getTime() > new Date(valueEnd).getTime()) {
        (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be earlier than chosen Start Date";
        return;
      }
      if (!this.isLessThanYearApart(valueEnd, valueStart)) {
        (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen time window cannot be greater than 365 days";
        return;
      }
      const tsStart = new Date(valueStart);
      const tsEnd = new Date(valueEnd);
      console.log('start date', tsStart, 'endDate', tsEnd)
      // tsStart.setDate(tsStart.getDate() - 2);
      // tsEnd.setDate(tsEnd.getDate() + 2);
      if (fetchData) {
        await this.renderWithFeatures((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear())
        // await this.fetchAndYearlyRenderUserCalendar_2((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear());
      }
      this.renderRangeEvents(new Date(valueStart), ((new Date(valueEnd).getTime()) - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), (this._SfCustomContainer as HTMLDivElement), showBackgroundButton);
    } else if (valueStart != "" && valueEnd == "") {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select End Date";
    } else if (valueStart == "" && valueEnd != "") {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date";
    } else {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date and End Date";
    }

    this.attachHandlers(eventContainer, valueStart, valueEnd);

    if (eventContainer.innerHTML.indexOf('myChart') >= 0) {

      this.renderCompletenessGraph(eventContainer);

    }

  }

  isLessThanYearApart = (date1: string | Date, date2: string | Date) => {
    let d1: Date = new Date(date1);
    let d2: Date = new Date(date2);

    // Ensure d1 is always the earlier date
    if (d1 > d2) {
      [d1, d2] = [d2, d1];
    }

    // Check if the dates are exactly one year apart (same month & day)
    if (d2.getFullYear() - d1.getFullYear() === 1 && d2.getMonth() === d1.getMonth() && d2.getDate() === d1.getDate()) {
      return false;
    }

    // Calculate difference in milliseconds
    const diffInMs = d2.getTime() - d1.getTime();

    // One full year in milliseconds, considering leap years
    const oneYearInMs = 365.25 * 24 * 60 * 60 * 1000;

    return diffInMs < oneYearInMs;
  }
  processDateSelectionViewer = async (eventContainer: HTMLDivElement) => {

    // var startDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    // var endDateCalendar = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + (parseInt(this.calendarStartYYYY) + 1));

    var valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value;
    if (valueStart == "") {
      valueStart = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value;
    }
    var valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value;
    if (valueEnd == "") {
      valueEnd = ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value;
    }

    //console.log('valuestart', valueStart);
    //console.log('valueend', valueEnd);
    let filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).value
    console.log('statistics filters criteria change1', this.statisticsSelectedFilter, filtercriteria)

    let filtercriterianame = ""
    if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).selectedIndex] != null) {
      filtercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).selectedIndex].innerHTML
    }
    let mobileSelect = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement)
    let mobileSelectVisible = !!(mobileSelect.offsetWidth || mobileSelect.offsetHeight || mobileSelect.getClientRects().length)
    if (mobileSelectVisible) {
      filtercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).value
      if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).selectedIndex] != null) {
        filtercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement).selectedIndex].innerHTML
      }
    }
    console.log('statistics filters criteria change2', this.statisticsSelectedFilter, filtercriteria, mobileSelectVisible)
    let filtervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).value
    let filtervaluename = ""
    if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).selectedIndex] != null) {
      filtervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).selectedIndex].innerHTML
    }
    if (filtervalue == "") {
      filtervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).value
      if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).selectedIndex] != null) {
        filtervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement).selectedIndex].innerHTML
      }
    }

    if (filtercriteria == "all") {
      this.htmlStatsFilter = "Filters Selected -> All"
    } else {
      if (filtervalue == "") {
        this.htmlStatsFilter = "Filters Selected -> " + Util.titleCase(filtercriterianame) + " -> All"
      } else {
        this.htmlStatsFilter = "Filters Selected -> " + Util.titleCase(filtercriterianame) + " -> " + Util.titleCase(filtervaluename)
      }
    }

    let subfiltervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).value
    let subfiltervaluename = ""
    if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).selectedIndex] != null) {
      subfiltervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement).selectedIndex].innerHTML
    }
    if (subfiltervalue == "") {
      subfiltervalue = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).value
      if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).selectedIndex] != null) {
        subfiltervaluename = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement).selectedIndex].innerHTML
      }
    }
    console.log('subfiltervalue, subfiltervaluename', subfiltervalue, subfiltervaluename)
    let subfiltercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).value
    let subfiltercriterianame = ""
    if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).selectedIndex] != null) {
      subfiltercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement).selectedIndex].innerHTML
    }
    if (subfiltercriteria == "") {
      subfiltercriteria = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).value
      if (((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).selectedIndex] != null) {
        subfiltercriterianame = ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).options[((this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement).selectedIndex].innerHTML
      }
    }

    console.log('subfiltercriteria, subfiltercriterianame', subfiltercriteria, subfiltercriterianame)
    if (valueStart != "" && valueEnd != "") {
      this.initCustomRightColViewer();
      // if(!this.checkStartDateEarliness(valueStart)) {
      //   (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen Start Date cannot be earlier than " + startDateCalendar;
      //   return;
      // }
      // if(!this.checkEndDateLateness(valueEnd)) {
      //   (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be later than " + endDateCalendar;
      //   return;
      // }
      if (new Date(valueStart).getTime() > new Date(valueEnd).getTime()) {
        (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen End Date cannot be earlier than chosen Start Date";
        return;
      }
      if (!this.isLessThanYearApart(valueEnd, valueStart)) {
        console.log('dates entered', valueEnd, valueStart);
        (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Chosen time window cannot be greater than 365 days";
        return;
      }
      const tsStart = new Date(valueStart);
      const tsEnd = new Date(valueEnd);
      // tsStart.setDate(tsStart.getDate() - 2);
      // tsEnd.setDate(tsEnd.getDate() + 2);

      //console.log('tsstart', tsStart);
      //console.log('tsend', tsEnd);
      let tempFilterCriteria = filtercriteria
      if (tempFilterCriteria == "") {
        tempFilterCriteria = "all"
      }
      this.statisticsSelectedFilter = tempFilterCriteria;
      console.log('statistics filters criteria change', this.statisticsSelectedFilter, filtercriteria)
      let meta = await this.fetchStatistics((tsStart.getMonth() + 1) + "/" + tsStart.getDate() + "/" + tsStart.getFullYear(), (tsEnd.getMonth() + 1) + "/" + tsEnd.getDate() + "/" + tsEnd.getFullYear(), tempFilterCriteria, filtervalue, subfiltercriteria, subfiltervalue);
      this.renderRangeStatistics(new Date(valueStart), ((new Date(valueEnd).getTime()) - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24), (this._SfCustomContainer as HTMLDivElement));

      if (meta != null) {
        this.renderStatisticsFilters((this._SfCustomContainer as HTMLDivElement))
        if (this.statisticsLoadLocation && this.locationId != "") {

          ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).value = 'location';
          ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement).dispatchEvent(new Event('change'))
          await new Promise((resolve) => setTimeout(resolve, 500));
          ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).value = this.locationId;
          for (let option of ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).options) {
            console.log('statsoption value', option.value, this.locationId)
            if (option.value == this.locationId) {
              filtervalue = option.value
              filtervaluename = option.innerHTML
              break;
            }
          }
          this.statisticsLoadLocation = false;
          ((this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement).dispatchEvent(new Event('change'))
          // this.processDateSelectionViewer(eventContainer);
        }

        if (this.statisticsSelectedFilter == "all") {
          this.processStatisticsGraphs(new Date(valueStart), 0, ((new Date(valueEnd).getTime() - new Date(valueStart).getTime()) / (1000 * 60 * 60 * 24)));
        }
      }
    } else if (valueStart != "" && valueEnd == "") {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select End Date";
    } else if (valueStart == "" && valueEnd != "") {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date";
    } else if (valueStart == "" && valueEnd == "") {
      (this._SfStreamEventStatus as HTMLDivElement).innerHTML = "Please select Start Date and End Date";
    }

    this.attachHandlers(eventContainer, valueStart, valueEnd);

    if (eventContainer.innerHTML.indexOf('myChart') >= 0) {

      this.renderCompletenessGraph(eventContainer, -1, 2, ["Completeness", "From " + new Date(valueStart).toLocaleDateString('en-IN') + " To " + new Date(valueEnd).toLocaleDateString('en-IN'), this.htmlStatsFilter], true);

    }

  }

  processStatisticsGraphs = (firstDate: Date, iInit: number, iLast: number) => {
    let month = firstDate.getMonth()
    let tempFunctionsData: any = {}
    let functionsArr = Util.alphabeticalSort(this.statisticsMeta.function)
    for (let functionStr of functionsArr) {
      let functionName = functionStr.split(';')[0].replace(/\([^)]*\)/g, "")
      let functionId = functionStr.split(';')[1]
      for (var i = iInit; i <= iLast; i++) {

        let mmdd: string = "";

        if (firstDate == null) {
          mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
        } else {
          const currDate = new Date(firstDate.getTime());
          currDate.setDate(firstDate.getDate() + (i));
          mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
        }
        if (this.statisticsFiltersData.function[functionId] != null && this.statisticsFiltersData.function[functionId][mmdd] != null) {
          if (tempFunctionsData[functionName] == null) {
            tempFunctionsData[functionName] = {}
          }
          if (tempFunctionsData[functionName]['not-started'] == null) {
            tempFunctionsData[functionName]['not-started'] = 0;
          }
          if (tempFunctionsData[functionName]['pending-approval'] == null) {
            tempFunctionsData[functionName]['pending-approval'] = 0;
          }
          if (tempFunctionsData[functionName]['rejected'] == null) {
            tempFunctionsData[functionName]['rejected'] = 0;
          }
          if (tempFunctionsData[functionName]['approved'] == null) {
            tempFunctionsData[functionName]['approved'] = 0;
          }
          tempFunctionsData[functionName]['not-started'] += this.statisticsFiltersData.function[functionId][mmdd]['not-started'] != null ? this.statisticsFiltersData.function[functionId][mmdd]['not-started'] : 0;
          tempFunctionsData[functionName]['pending-approval'] += this.statisticsFiltersData.function[functionId][mmdd]['pending-approval'] != null ? this.statisticsFiltersData.function[functionId][mmdd]['pending-approval'] : 0;
          tempFunctionsData[functionName]['rejected'] += this.statisticsFiltersData.function[functionId][mmdd]['rejected'] != null ? this.statisticsFiltersData.function[functionId][mmdd]['rejected'] : 0;
          tempFunctionsData[functionName]['approved'] += this.statisticsFiltersData.function[functionId][mmdd]['approved'] != null ? this.statisticsFiltersData.function[functionId][mmdd]['approved'] : 0;
        }
      }
    }

    console.log('tempFunctionsData:', tempFunctionsData);
    this.statisticsFunctionsGraphData = tempFunctionsData

    let tempLocationsData: any = {}
    let locationsArr = Util.alphabeticalSort(this.statisticsMeta.location)
    for (let locationStr of locationsArr) {
      let locationName = locationStr.split(';')[0].replace(/\([^)]*\)/g, "")
      let locationId = locationStr.split(';')[1]
      for (var i = iInit; i <= iLast; i++) {

        let mmdd: string = "";

        if (firstDate == null) {
          mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
        } else {
          const currDate = new Date(firstDate.getTime());
          currDate.setDate(firstDate.getDate() + (i));
          mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
        }
        if (this.statisticsFiltersData.location[locationId] != null && this.statisticsFiltersData.location[locationId][mmdd] != null) {
          if (tempLocationsData[locationName] == null) {
            tempLocationsData[locationName] = {}
          }
          if (tempLocationsData[locationName]['not-started'] == null) {
            tempLocationsData[locationName]['not-started'] = 0;
          }
          if (tempLocationsData[locationName]['pending-approval'] == null) {
            tempLocationsData[locationName]['pending-approval'] = 0;
          }
          if (tempLocationsData[locationName]['rejected'] == null) {
            tempLocationsData[locationName]['rejected'] = 0;
          }
          if (tempLocationsData[locationName]['approved'] == null) {
            tempLocationsData[locationName]['approved'] = 0;
          }
          tempLocationsData[locationName]['not-started'] += this.statisticsFiltersData.location[locationId][mmdd]['not-started'] != null ? this.statisticsFiltersData.location[locationId][mmdd]['not-started'] : 0;
          tempLocationsData[locationName]['pending-approval'] += this.statisticsFiltersData.location[locationId][mmdd]['pending-approval'] != null ? this.statisticsFiltersData.location[locationId][mmdd]['pending-approval'] : 0;
          tempLocationsData[locationName]['rejected'] += this.statisticsFiltersData.location[locationId][mmdd]['rejected'] != null ? this.statisticsFiltersData.location[locationId][mmdd]['rejected'] : 0;
          tempLocationsData[locationName]['approved'] += this.statisticsFiltersData.location[locationId][mmdd]['approved'] != null ? this.statisticsFiltersData.location[locationId][mmdd]['approved'] : 0;
        }
      }
    }

    console.log('tempLocationsData:', tempLocationsData);
    this.statisticsLocationsGraphData = tempLocationsData

    let tempReportersData: any = {}
    let reportersArr = Util.alphabeticalSort(this.statisticsMeta.reporter)
    for (let reporterStr of reportersArr) {
      let reporterName = reporterStr.split(';')[0].replace(/\([^)]*\)/g, "")
      let reporterId = reporterStr.split(';')[1]
      for (var i = iInit; i <= iLast; i++) {

        let mmdd: string = "";

        if (firstDate == null) {
          mmdd = ("0" + (month + 1)).slice(-2) + "/" + ("0" + i).slice(-2);
        } else {
          const currDate = new Date(firstDate.getTime());
          currDate.setDate(firstDate.getDate() + (i));
          mmdd = ("0" + (currDate.getMonth() + 1)).slice(-2) + "/" + ("0" + currDate.getDate()).slice(-2);
        }
        if (this.statisticsFiltersData.reporter[reporterId] != null && this.statisticsFiltersData.reporter[reporterId][mmdd] != null) {
          if (tempReportersData[reporterName] == null) {
            tempReportersData[reporterName] = {}
          }
          if (tempReportersData[reporterName]['not-started'] == null) {
            tempReportersData[reporterName]['not-started'] = 0;
          }
          if (tempReportersData[reporterName]['pending-approval'] == null) {
            tempReportersData[reporterName]['pending-approval'] = 0;
          }
          if (tempReportersData[reporterName]['rejected'] == null) {
            tempReportersData[reporterName]['rejected'] = 0;
          }
          if (tempReportersData[reporterName]['approved'] == null) {
            tempReportersData[reporterName]['approved'] = 0;
          }
          tempReportersData[reporterName]['not-started'] += this.statisticsFiltersData.reporter[reporterId][mmdd]['not-started'] != null ? this.statisticsFiltersData.reporter[reporterId][mmdd]['not-started'] : 0;
          tempReportersData[reporterName]['pending-approval'] += this.statisticsFiltersData.reporter[reporterId][mmdd]['pending-approval'] != null ? this.statisticsFiltersData.reporter[reporterId][mmdd]['pending-approval'] : 0;
          tempReportersData[reporterName]['rejected'] += this.statisticsFiltersData.reporter[reporterId][mmdd]['rejected'] != null ? this.statisticsFiltersData.reporter[reporterId][mmdd]['rejected'] : 0;
          tempReportersData[reporterName]['approved'] += this.statisticsFiltersData.reporter[reporterId][mmdd]['approved'] != null ? this.statisticsFiltersData.reporter[reporterId][mmdd]['approved'] : 0;
        }
      }
    }

    console.log('tempReportersData:', tempReportersData);
    this.statisticsReportersGraphData = tempReportersData

    this.renderStatisticsGraph((this._SfCustomContainer as HTMLDivElement), this.statisticsFunctionsGraphData, this.statisticsLocationsGraphData, this.statisticsReportersGraphData);
  }

  initFindRightCol = () => {

    var html = "";

    html += '<div id="stream-event-0" part="stream-event-list" class="stream-event-list">';
    html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected">';
    html += '<div><h2 id="stream-event-status">Type something and press enter</h2></div>';
    html += '</div>';
    html += '</div>';


    (this._SfFindContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html

  }

  initCustomRightCol = () => {

    var html = "";

    html += '<div id="stream-event-0" part="stream-event-list" class="stream-event-list">';
    html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected">';
    html += '<div><h2 id="stream-event-status">Please select Start Date and End Date</h2></div>';
    html += '</div>';
    html += '</div>';


    (this._SfCustomContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html

  }

  initCustomRightColViewer = () => {

    var html = "";

    html += '<div id="stream-event-0" part="stream-event-list" class="stream-event-list">';
    html += '<div part="stream-event-not-selected" class="d-flex stream-event-not-selected">';
    html += '<div><h2 id="stream-event-status">Please select Start Date, End Date and Filter Criteria</h2></div>';
    html += '</div>';
    html += '</div>';


    (this._SfCustomContainer as HTMLDivElement).querySelector('.calendar-right-data')!.innerHTML = html

  }

  checkAndShowBulk = () => {

    const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf<HTMLInputElement>;

    var checked = 0;

    //console.log('checkAndShowBulk', inputArr.length);

    for (var i = 0; i < inputArr.length; i++) {

      //console.log(inputArr[i].checked);
      if (inputArr[i].checked) {
        checked++;
      }

    }

    //console.log('checkAndShowBulk', checked);

    if (checked > 1) {
      return true;
    }

    return false;

  }

  calculateAndShowSummary = () => {

    //console.log('showing summary',this.mappedValuesUsers);

    const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-users');
    var mapped = 0;
    for (var i = 0; i < Object.keys(this.mappedValuesUsers).length; i++) {
      if (this.mappedValuesUsers[Object.keys(this.mappedValuesUsers)[i]].length > 0) {
        mapped++;
      }
    }

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-summary')!.innerHTML = 'Completed ' + mapped + ' / ' + inputArr.length;
    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-graph')!.querySelector('.div-graph-pending')! as HTMLDivElement).style.width = ((inputArr.length - mapped) * 100 / (inputArr.length)) + '%';
    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-graph')!.querySelector('.div-graph-complete')! as HTMLDivElement).style.width = ((mapped) * 100 / (inputArr.length)) + '%';

    //console.log('showing summary', mapped, Object.keys(this.mappedValuesUsers).length);

    if (mapped == inputArr.length) {
      ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.style.visibility = 'visible';
    } else {
      ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.style.visibility = 'hidden';
    }
  }

  showAllEvents = () => {

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = true;
    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = false;
    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = false;
    //this.renderMapping(this.unmappedEvents)
    this.applyFilter();
    this.calculateAndShowSummary();

  }

  showMappedEvents = () => {

    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = false;
    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = true;
    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = false;
    //this.renderMapping(this.unmappedEvents)
    this.applyFilter("mapped")

  }

  showUnmappedEvents = () => {

    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement)!.checked = false;
    // ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement)!.checked = false;
    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement)!.checked = true;
    //this.renderMapping(this.unmappedEvents)
    this.applyFilter("unmapped")

  }

  updateInAllSelections = (param: string, value: any) => {

    //console.log('updateinallselections', param, value);

    const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf<HTMLInputElement>;
    const inputDatesArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-dates') as NodeListOf<HTMLInputElement>;
    const divDatesArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-dates') as NodeListOf<HTMLDivElement>;
    const inputTagsArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-tags') as NodeListOf<SfIForm>;
    const divTagsArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-tags') as NodeListOf<HTMLDivElement>;
    const inputUsersArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-users') as NodeListOf<SfIForm>;
    const divUsersArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.div-users') as NodeListOf<HTMLDivElement>;

    for (var i = 0; i < inputArr.length; i++) {
      //console.log('updateinallselections', i);
      if (inputArr[i].checked) {
        if (param == "duedate") {
          inputDatesArr[i].value = value;
          divDatesArr[i].innerHTML = value;
          this.mappedValuesDueDates[i] = value;
        }
        if (param == "tags") {
          inputTagsArr[i].preselectedValues = JSON.stringify(value);
          inputTagsArr[i].populatePreselected();
          divTagsArr[i].innerHTML = '';
          var html = '';
          for (var j = 0; j < value.length; j++) {
            html += value[j];
            if (j < (value.length - 1)) {
              html += ",";
            }
          }
          divTagsArr[i].innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
          this.mappedValuesTags[i] = value;
        }
        if (param == "users") {
          // inputUsersArr[i].value = value;
          // divUsersArr[i].innerHTML = value;
          // this.mappedValuesUsers[i] = value;
          inputUsersArr[i].preselectedValues = JSON.stringify(value);
          inputUsersArr[i].populatePreselected();
          divUsersArr[i].innerHTML = '';
          var html = '';
          for (var j = 0; j < value.length; j++) {
            html += value[j];
            if (j < (value.length - 1)) {
              html += ",";
            }
          }
          divUsersArr[i].innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
          this.mappedValuesUsers[i] = value;
          this.updateMappingStatus(value, i);
          this.calculateAndShowSummary();
        }
      }
    }

  }

  updateMappingStatus = (value: any, clickIndex: number) => {
    //console.log('clickindex', clickIndex);
    if (value.length > 0) {
      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + clickIndex) as HTMLDivElement).innerHTML = '<span class="material-icons color-done">check_circle</done>'
    } else {
      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + clickIndex) as HTMLDivElement).innerHTML = '<span class="material-icons color-pending">pending</done>'
    }
  }

  filterEventsInWindow = (tags: Array<string>, _ctx: any, divContainer: HTMLDivElement | null) => {

    const arrData = [];

    //console.log('window', this.eventsInWindow, ctx);

    if (divContainer != null) this.clearGraph(divContainer, 2);
    if (divContainer != null) this.clearGraph(divContainer, 3);

    for (var i = 0; i < tags.length; i++) {

      var countApproved = 0;
      var countInProgress = 0;
      var countNotStarted = 0;

      for (var j = 0; j < this.eventsInWindow.length; j++) {

        const event = this.eventsInWindow[j];

        for (var l = 0; l < event.tags.length; l++) {

          if ((event.tags[l] + "").toLowerCase().indexOf((tags[i] + "").toLowerCase().split(';')[1]) >= 0) {
            //console.log('plot approved', event.approved)
            //if(event.documents == null || event.documents[event.mmdd + '/' + new Date().getFullYear()] == null || JSON.parse(event.documents[event.mmdd + '/' + new Date().getFullYear()]) == null) {
            if (event.comments == null || event.comments.length === 0) {
              countNotStarted++;
            } else if (event.approved == null) {
              countInProgress++;
            } else if (!event.approved) {
              countInProgress++;
            } else if (event.approved) {
              countApproved++;
            }
            // if(event.documents == null || event.documents.length === 0) {
            //   countNotStarted++;
            // } else if (event.approved == null) {
            //   countInProgress++;
            // } else if(!event.approved) {
            //   countInProgress++;
            // } else if(event.approved) {
            //   countApproved++;
            // }
          }

        }

      }

      const arrItem = [countApproved, countInProgress, countNotStarted];
      arrData.push(arrItem)

    }

    //console.log(arrData);

    const dataSetApproved = [];
    const dataSetInProgress = [];
    const dataSetNotStarted = [];

    for (i = 0; i < arrData.length; i++) {

      dataSetApproved.push(arrData[i][0]);
      dataSetInProgress.push(arrData[i][1]);
      dataSetNotStarted.push(arrData[i][2]);

    }

    //console.log('plotting dataset', dataSetApproved, dataSetInProgress, dataSetNotStarted);

    const tagsCompressed = [];

    for (i = 0; i < tags.length; i++) {
      tagsCompressed.push(this.truncate(tags[i].split(';')[0], 20, false, false));
    }

    if (divContainer != null) {
      this.clearGraph(divContainer, 1);
      this.showGraph(divContainer, 4);
    }

    if (this.fill == "solid") {

      const data = {
        labels: tagsCompressed,
        datasets: [
          {
            label: 'Approved',
            data: dataSetApproved,
            backgroundColor: '#8cd039'
          },
          {
            label: 'In Progress',
            data: dataSetInProgress,
            backgroundColor: '#FFBA49'
          },
          {
            label: 'Not Started',
            data: dataSetNotStarted,
            backgroundColor: '#A4A9AD'
          }
        ]
      }

      const ctx4 = divContainer?.querySelector('#myChart4') as ChartItem;
      (divContainer?.querySelector('#myChart4') as HTMLCanvasElement).classList.remove('gone');

      if (this.fill == "solid") {

        this.renderChart4(ctx4, 'bar', data, "Custom Plot")

      } else {

        this.renderChart4(ctx4, 'bar', data, "Custom Plot")

      }



    } else {

      const data = {
        labels: tagsCompressed,
        datasets: [
          {
            label: 'Approved',
            data: dataSetApproved,
            backgroundColor: Util.createDiagonalPattern3('#8cd039')
          },
          {
            label: 'In Progress',
            data: dataSetInProgress,
            backgroundColor: Util.createDiagonalPattern1('#FFBA49')
          },
          {
            label: 'Not Started',
            data: dataSetNotStarted,
            backgroundColor: Util.createDiagonalPattern2('#A4A9AD')
          }
        ]
      }

      const ctx4 = divContainer?.querySelector('#myChart4') as ChartItem;
      (divContainer?.querySelector('#myChart4') as HTMLCanvasElement).classList.remove('gone');

      if (this.fill == "solid") {

        this.renderChart4(ctx4, 'bar', data, "Custom Plot")

      } else {

        this.renderChart4(ctx4, 'bar', data, "Custom Plot")

      }

      // this.renderChart(ctx, 'bar', data, "Custom Plot")

    }

  }

  sleep = (ms: number) => {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  hideTabContainers = async () => {

    (this._SfOnboardingStatutesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingCompliancesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingCountriesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingEntitiesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingLocationsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingFunctionsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingTagsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingReportersContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingApproversContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingAuditorsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingViewersContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingDocsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingDuedatesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingExtensionsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingActivationsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingInvalidationsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingTriggersContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingInternalControlsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingSignoffContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingCalendarContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingSuspenseContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingGovLocationsContainer as HTMLDivElement).style.display = 'none';
    (this._SfOnboardingGovUsersContainer as HTMLDivElement).style.display = 'none';

    (this._SfOnboardingStatutesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingCompliancesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingCountriesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingEntitiesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingLocationsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingFunctionsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingTagsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingReportersContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingApproversContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingAuditorsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingViewersContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingDocsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingDuedatesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingExtensionsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingActivationsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingInvalidationsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingTriggersContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingInternalControlsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingCalendarContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingGovLocationsContainer as HTMLDivElement).innerHTML = '';
    (this._SfOnboardingGovUsersContainer as HTMLDivElement).innerHTML = '';

  }

  hideRcmTabContainers = async () => {

    (this._SfRcmComplianceContainer as HTMLDivElement).style.display = 'none';
    (this._SfRcmProjectsContainer as HTMLDivElement).style.display = 'none';
    (this._SfRcmDateContainer as HTMLDivElement).style.display = 'none';
    (this._SfRcmConfirmContainer as HTMLDivElement).style.display = 'none';
    (this._SfRcmJobsContainer as HTMLDivElement).style.display = 'none';

    (this._SfRcmComplianceContainer as HTMLDivElement).innerHTML = '';
    (this._SfRcmProjectsContainer as HTMLDivElement).innerHTML = '';
    (this._SfRcmDateContainer as HTMLDivElement).innerHTML = '';
    (this._SfRcmConfirmContainer as HTMLDivElement).innerHTML = '';
    (this._SfRcmJobsContainer as HTMLDivElement).innerHTML = '';


  }

  loadRcmNotifications = async () => {

    const notifs = await this.fetchRcmNotifications(this.projectId);
    //console.log('notifs', notifs);
    this.renderRcmNotifications(notifs);

  }

  loadRcmCompliances = async () => {

    this.hideRcmTabContainers();
    (this._SfRcmComplianceContainer as HTMLDivElement).style.display = 'flex';

    const compliances: Array<any> = [];

    var nextBackwardTokenOrig = '';

    const tempCompliances: Array<string> = [];

    while (true) {

      const updatedCompliances = await this.fetchUpdatedCompliances(nextBackwardTokenOrig);
      //console.log('updatedCompliances', updatedCompliances.data.length);

      const nextBackwardTokenNew = updatedCompliances.nextBackwardToken;

      //console.log('comparison', nextBackwardTokenNew, nextBackwardTokenOrig);

      if (nextBackwardTokenOrig == nextBackwardTokenNew) {
        //console.log('breaking...');
        break;
      } else {
        nextBackwardTokenOrig = nextBackwardTokenNew;
      }

      for (var i = 0; i < updatedCompliances.data.length; i++) {
        const event = JSON.parse(updatedCompliances.data[i].message);
        //console.log(i, 'event op', JSON.parse(event.req.body).id);
        if (event.op == "update") {
          if (!tempCompliances.includes(JSON.parse(event.req.body).id)) {
            compliances.push(JSON.parse(event.req.body));
            tempCompliances.push(JSON.parse(event.req.body).id);
          }

        }
      }

      //console.log('compliances', compliances);

    }

    if (compliances.length > 0) {
      this.renderRcmCompliances(compliances);
      const arrCompliances = [];
      for (var i = 0; i < compliances.length; i++) {
        arrCompliances.push(compliances[i].id);
      }
      //console.log('compliances 2', arrCompliances);
      const lockedCompliances = await this.fetchRcmLockedCompliances(arrCompliances);
      //console.log('compliances 2 locked', lockedCompliances);
      this.renderRcmLockedCompliances(lockedCompliances);

      (this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#cb-completed')?.addEventListener('change', (e: any) => {

        const cb = (e.currentTarget as HTMLInputElement);
        if (cb.checked) {
          this.renderRcmUnlockedCompliances(lockedCompliances);
        } else {
          this.renderRcmLockedCompliances(lockedCompliances);
        }

      });

      const arrButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.buttonselect-icon') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrButtons.length; i++) {

        arrButtons[i].addEventListener('click', (e: any) => {

          const id = e.currentTarget.id.replace('button-', '');
          var index = -1;
          for (var j = 0; j < compliances.length; j++) {
            if (compliances[j].id == id) {
              index = j;
            }
          }
          //console.log(id, index, compliances[index]);
          this.rcmSelectedCompliance = compliances[index];
          ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects') as HTMLButtonElement).click();

        })

      }

      const arrLockButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.button-lock-icon') as NodeListOf<HTMLButtonElement>;
      for (i = 0; i < arrLockButtons.length; i++) {

        arrLockButtons[i].addEventListener('click', async (e: any) => {

          const index = e.currentTarget.id.replace('button-lock-', '');
          await this.fetchUpdateRcmLock(index);
          this.loadRcmCompliances();

        })

      }

    }

  }

  loadRcmProjects = async () => {

    //console.log('loadRcmProjects');
    this.hideRcmTabContainers();
    (this._SfRcmProjectsContainer as HTMLDivElement).style.display = 'flex';
    this.renderRcmSelectedComplianceInProject((this._SfRcmProjectsContainer as HTMLDivElement));

    var mappedProjects;
    if (this.rcmSelectedCompliance != null) {
      mappedProjects = await this.fetchMappedProjects();
      //console.log('mappedProjects', mappedProjects.data);
    }

    const projects = [];

    if (mappedProjects != null) {
      for (var i = 0; i < mappedProjects.data.length; i++) {

        const projectDetail = await this.fetchDetailProject(mappedProjects.data[i]['projectid']['S']);
        projects.push(projectDetail.data.value);

      }

    }

    this.rcmSelectedProjects = projects;

    this.renderRcmProjects((this._SfRcmProjectsContainer as HTMLDivElement), this.rcmSelectedProjects);

    if (this.rcmSelectedProjects != null && this.rcmSelectedProjects.length > 0) {
      this.renderRcmProceed((this._SfRcmProjectsContainer as HTMLDivElement), (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-date'));
    }
  }

  loadRcmDate = async () => {

    //console.log('loadRcmDate');
    this.hideRcmTabContainers();
    (this._SfRcmDateContainer as HTMLDivElement).style.display = 'flex';
    this.renderRcmDate((this._SfRcmDateContainer as HTMLDivElement));
    this.renderRcmSelectedComplianceInProject((this._SfRcmDateContainer as HTMLDivElement));
    //console.log('projects', this.rcmSelectedProjects);
    this.renderRcmProjects((this._SfRcmDateContainer as HTMLDivElement), this.rcmSelectedProjects);

    if (this.rcmSelectedProjects != null && this.rcmSelectedProjects.length > 0) {
      this.renderRcmProceed((this._SfRcmDateContainer as HTMLDivElement), (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-jobs'));
    }

    ((this._SfRcmDateContainer as HTMLDivElement).querySelector('#rcm-date') as HTMLInputElement)?.addEventListener('change', (e: any) => {
      this.rcmSelectedDate = (e.currentTarget as HTMLInputElement).value;
      //console.log(this.rcmSelectedDate);
    });

    ((this._SfRcmDateContainer as HTMLDivElement).querySelector('#rcm-message') as HTMLInputElement)?.addEventListener('change', (e: any) => {
      this.rcmSelectedMessage = (e.currentTarget as HTMLInputElement).value;
      //console.log(this.rcmSelectedMessage);
    });


  }

  loadRcmJobs = async () => {

    //console.log('loadRcmJobs');
    this.hideRcmTabContainers();
    (this._SfRcmJobsContainer as HTMLDivElement).style.display = 'flex';

    if (this.rcmSelectedCompliance != null) {
      const jobs = await this.fetchRcmJobs(this.rcmSelectedCompliance.id);
      //console.log('jobs', jobs, this.rcmSelectedDate, this.rcmSelectedMessage); 
      if (this.rcmSelectedDate != null && this.rcmSelectedMessage != null) {
        this.renderRcmJobs((this._SfRcmJobsContainer as HTMLDivElement));
        this.renderRcmSelectedDate((this._SfRcmJobsContainer as HTMLDivElement));
      }
      this.renderRcmSelectedComplianceInProject((this._SfRcmJobsContainer as HTMLDivElement));
      this.renderRcmProjects((this._SfRcmJobsContainer as HTMLDivElement), this.rcmSelectedProjects);
      this.renderRcmSelectedJobs((this._SfRcmJobsContainer as HTMLDivElement), jobs);

      //console.log('projects', this.rcmSelectedProjects);
      ((this._SfRcmJobsContainer as HTMLDivElement).querySelector('#button-submit') as HTMLButtonElement)?.addEventListener('click', async () => {
        //console.log(this.rcmSelectedCompliance);
        await this.fetchCreateRcmJob(this.rcmSelectedCompliance.id, this.rcmSelectedCompliance, this.rcmSelectedDate, this.rcmSelectedMessage, this.rcmSelectedProjects);
        this.loadRcmJobs();
      });
    } else {

    }


  }

  loadOnboardingStatutes = async () => {
    this.hideTabContainers();
    (this._SfOnboardingStatutesContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutes();
    //console.log('mappedstatutes', mappedStatutes);
    this.renderOnboardingStatutes(mappedStatutes);
  }

  loadOnboardingCompliances = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingCompliancesContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList();
    console.log("mapped statutes", mappedStatutes);
    // const mappedStatutes = await this.fetchMappedStatutes();
    // const mappedCompliances = await this.fetchMappedCompliances();
    // this.renderOnboardingCompliances(mappedStatutes, mappedCompliances);
    this.renderOnboardingStatutesDropdownMapping(this._SfOnboardingCompliancesContainer as HTMLDivElement, mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.renderOnboardingCompliances);
  }

  loadOnboardingCountries = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingCountriesContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList();
    // const countriesJobs = await this.fetchCountriesJobs();
    // const mappedCountries = await this.fetchMappedCountries();
    // const mappedCompliances = await this.fetchMappedCompliances();
    // const mappedStatutes = await this.fetchMappedStatutes();
    // //console.log('countriesJobs', countriesJobs);
    // console.log('mappedCompliances', mappedCompliances);
    // console.log('mappedCountries', mappedCountries);
    // this.renderOnboardingCountries(mappedCountries, mappedCompliances, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingCountriesContainer as HTMLDivElement, 'countries-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, () => { return [] }, this.fetchMappedCountries, this.renderOnboardingCountries);
  }

  loadOnboardingEntities = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingEntitiesContainer as HTMLDivElement).style.display = 'flex';
    // const entitiesJobs = await this.fetchEntitiesJobs();
    const mappedStatutes = await this.fetchMappedStatutesList();
    // const mappedEntities = await this.fetchMappedEntities();
    // const mappedSerializedCountries = await this.fetchMappedSerializedCountries();
    // const arrStatuteEntitiesApplicabilities = await this.loadProposedFromStatutes(1);
    // // const mappedStatutes = await this.fetchMappedStatutes();
    //console.log('mappedSerializedCountries', mappedSerializedCountries);
    //console.log('mappedEntities', mappedEntities);
    //console.log('entitiesApplicabilities', arrStatuteEntitiesApplicabilities);
    // this.renderOnboardingEntities(mappedEntities, mappedSerializedCountries, null, arrStatuteEntitiesApplicabilities);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingEntitiesContainer as HTMLDivElement, 'entities-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedCountries, this.fetchMappedEntities, this.renderOnboardingEntities);
  }

  loadOnboardingLocations = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingLocationsContainer as HTMLDivElement).style.display = 'flex';
    // const locationsJobs = await this.fetchLocationsJobs();
    const mappedStatutes = await this.fetchMappedStatutesList();
    // const mappedSerializedEntities = await this.fetchMappedSerializedEntities();
    // const mappedLocations = await this.fetchMappedLocations();
    //console.log('mappedserializedentities', mappedSerializedEntities);
    //console.log('mappedlocations', mappedLocations); 
    // this.renderOnboardingLocations(mappedLocations, mappedSerializedEntities, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingLocationsContainer as HTMLDivElement, 'locations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedEntities, this.fetchMappedLocations, this.renderOnboardingLocations);
  }

  loadOnboardingFunctions = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingFunctionsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const functionsJobs = await this.fetchFunctionJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedFunctions = await this.fetchMappedFunctions();
    //console.log('functionjobs', functionsJobs);
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedfunctions', mappedFunctions);
    // this.renderOnboardingFunctions(mappedFunctions, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingFunctionsContainer as HTMLDivElement, 'functions-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedLocations, this.fetchMappedFunctions, this.renderOnboardingFunctions);
  }

  loadOnboardingTags = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingTagsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const tagsJobs = await this.fetchTagsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedTags = await this.fetchMappedTags();
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedtags', mappedTags);
    // this.renderOnboardingTags(mappedTags, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingTagsContainer as HTMLDivElement, 'tags-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedTags, this.renderOnboardingTags);
  }

  loadProposedFromStatutes = async (fieldIndex: number) => {
    const mappedStatutes = await this.fetchMappedStatutes();
    //console.log('mappedstatutes', mappedStatutes);
    const arrStatuteReporters: any = {}
    for (var i = 0; i < mappedStatutes.data.mappings.mappings.length; i++) {

      if (arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname] == null) {
        arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname] = {}
      }
      if (arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] == null) {
        arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] = {}
      }

      arrStatuteReporters[mappedStatutes.data.mappings.mappings[i].countryname][mappedStatutes.data.mappings.mappings[i].statutename.trim()] = mappedStatutes.data.mappings.mappings[i].extraFields[fieldIndex];
    }
    //console.log('mappedstatutesend', arrStatuteReporters);
    return arrStatuteReporters;
  }

  loadOnboardingReporters = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingReportersContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const reportersJobs = await this.fetchReportersJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedReporters = await this.fetchMappedReporters();
    // const arrStatuteReporters = await this.loadProposedFromStatutes(1);
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedreporters', mappedReporters);
    //console.log('arrstatutereporters', arrStatuteReporters);
    // this.renderOnboardingReporters(mappedReporters, mappedSerializedLocations, null, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingReportersContainer as HTMLDivElement, 'reporters-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedReporters, this.renderOnboardingReporters);
  }

  loadOnboardingApprovers = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingApproversContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const approversJobs = await this.fetchApproversJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedApprovers = await this.fetchMappedApprovers();
    // const arrStatuteApprovers = await this.loadProposedFromStatutes(2);
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedapprovers', mappedApprovers);
    // this.renderOnboardingApprovers(mappedApprovers, mappedSerializedLocations, null, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingApproversContainer as HTMLDivElement, 'approvers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedApprovers, this.renderOnboardingApprovers);
  }

  loadOnboardingFunctionHeads = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const functionHeadsJobs = await this.fetchFunctionHeadsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedFunctionHeads = await this.fetchMappedFunctionHeads();
    // const arrStatuteFunctionheads = await this.loadProposedFromStatutes(3);
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedfunctionheads', mappedFunctionHeads);
    // this.renderOnboardingFunctionHeads(mappedFunctionHeads, mappedSerializedLocations, null, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingFunctionHeadsContainer as HTMLDivElement, 'functionheads-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedFunctionHeads, this.renderOnboardingFunctionHeads);
  }

  loadOnboardingViewers = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingViewersContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const makerViewersJobs = await this.fetchViewersJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedViewers = await this.fetchMappedViewers();
    // const arrStatuteViewers = await this.loadProposedFromStatutes(5);
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedViewers', mappedViewers);
    // this.renderOnboardingViewers(mappedViewers, mappedSerializedLocations, null, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingViewersContainer as HTMLDivElement, 'viewers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedViewers, this.renderOnboardingViewers);
  }

  loadOnboardingDocs = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingDocsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const docsJobs = await this.fetchDocsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedDocs = await this.fetchMappedDocs();
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedDocs', mappedDocs);
    // this.renderOnboardingDocs(mappedDocs, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingDocsContainer as HTMLDivElement, 'docs-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedDocs, this.renderOnboardingDocs);
  }

  loadOnboardingMakerCheckers = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingMakerCheckersContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const makerCheckersJobs = await this.fetchMakerCheckersJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedMakerCheckers = await this.fetchMappedMakerCheckers();
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedMakerCheckers', mappedMakerCheckers);
    // this.renderOnboardingMakerCheckers(mappedMakerCheckers, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingMakerCheckersContainer as HTMLDivElement, 'makercheckers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedMakerCheckers, this.renderOnboardingMakerCheckers);
  }

  loadOnboardingAuditors = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingAuditorsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const auditorsJobs = await this.fetchAuditorsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedAuditors = await this.fetchMappedAuditors();
    // const arrStatuteAuditors = await this.loadProposedFromStatutes(4);
    //console.log('mappedSerializedFunctionheads', mappedSerializedLocations);
    //console.log('mappedAuditors', mappedAuditors);
    // this.renderOnboardingAuditors(mappedAuditors, mappedSerializedLocations, null, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingAuditorsContainer as HTMLDivElement, 'auditors-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedAuditors, this.renderOnboardingAuditors);

  }

  loadOnboardingDuedates = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingDuedatesContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const duedatesJobs = await this.fetchDueDatesJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedDuedates = await this.fetchMappedDuedates();
    //console.log('mappedSerializedLocations', mappedSerializedLocations);
    //console.log('mappedduedates', mappedDuedates);
    // this.renderOnboardingDuedates(mappedDuedates, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingDuedatesContainer as HTMLDivElement, 'duedates-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedDuedates, this.renderOnboardingDuedates);
  }

  loadOnboardingActivations = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingActivationsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const activationsJobs = await this.fetchExtensionsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedActivations = await this.fetchMappedActivations();
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedactivations', mappedActivations);
    // this.renderOnboardingActivations(mappedActivations, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingActivationsContainer as HTMLDivElement, 'activations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedActivations, this.renderOnboardingActivations);
  }

  loadOnboardingInvalidations = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingInvalidationsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const invalidationsJobs = await this.fetchExtensionsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedInvalidations = await this.fetchMappedInvalidations();
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedinvalidations', mappedInvalidations);
    // this.renderOnboardingInvalidations(mappedInvalidations, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingInvalidationsContainer as HTMLDivElement, 'invalidations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedInvalidations, this.renderOnboardingInvalidations);
  }

  loadOnboardingAlertSchedules = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const alertschedulesJobs = await this.fetchAlertSchedulesJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedAlertSchedules = await this.fetchMappedAlertSchedules();
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedalertschedules', mappedAlertSchedules);
    // this.renderOnboardingAlertSchedules(mappedAlertSchedules, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingAlertSchedulesContainer as HTMLDivElement, 'alertschedules-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedAlertSchedules, this.renderOnboardingAlertSchedules);
  }

  loadOnboardingExtensions = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingExtensionsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const extensionsJobs = await this.fetchExtensionsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedExtensions = await this.fetchMappedExtensions();
    //console.log('mappedserializedlocations', mappedSerializedLocations);
    //console.log('mappedextensions', mappedExtensions);
    // this.renderOnboardingExtensions(mappedExtensions, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingExtensionsContainer as HTMLDivElement, 'extensions-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedExtensions, this.renderOnboardingExtensions);
  }

  loadOnboardingTriggers = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingTriggersContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const triggersJobs = await this.fetchInternalControlsJobs();
    // const mappedSerializedAlertSchedules = await this.fetchMappedSerializedAlertSchedules();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedTriggers = await this.fetchMappedTriggers();
    //console.log('mappedSerializedAlertSchedules', mappedSerializedAlertSchedules);
    //console.log('mappedTriggers', mappedTriggers);
    // this.renderOnboardingTriggers(mappedTriggers, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingTriggersContainer as HTMLDivElement, 'triggers-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedTriggers, this.renderOnboardingTriggers);
  }

  loadOnboardingInternalControls = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingInternalControlsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const internalcontrolsJobs = await this.fetchInternalControlsJobs();
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedInternalControls = await this.fetchMappedInternalControls();
    //console.log('mappedSerializedlocations', mappedSerializedLocations);
    //console.log('mappedinternalcontrols', mappedInternalControls);
    // this.renderOnboardingInternalControls(mappedInternalControls, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingInternalControlsContainer as HTMLDivElement, 'internalcontrols-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedInternalControls, this.renderOnboardingInternalControls);
  }

  loadOnboardingReportedLocations = async (selectedStatutes: any = []) => {
    this.hideTabContainers();
    (this._SfOnboardingReportedLocationsContainer as HTMLDivElement).style.display = 'flex';
    const mappedStatutes = await this.fetchMappedStatutesList()
    // const mappedSerializedLocations = await this.fetchMappedSerializedLocations();
    // const mappedReportedLocations = await this.fetchMappedReportedLocations();
    //console.log('mappedSerializedlocations', mappedSerializedLocations);
    //console.log('mappedReportedLocations', mappedReportedLocations);
    // this.renderOnboardingReportedLocations(mappedReportedLocations, mappedSerializedLocations, null);
    this.renderOnboardingStatutesDropdownTagging(this._SfOnboardingReportedLocationsContainer as HTMLDivElement, 'reportedlocations-list-container', mappedStatutes, selectedStatutes, this.fetchMappedCompliances, this.fetchMappedFunctions, this.fetchMappedReportedLocations, this.renderOnboardingReportedLocations);
  }

  loadOnboardingSignoff = async () => {
    this.hideTabContainers();
    (this._SfOnboardingSignoffContainer as HTMLDivElement).style.display = 'flex';
    const signoff = await this.fetchGetSignOff();
    this.renderOnboardingSignoff(signoff);
    //console.log(signoff);
  }

  loadOnboardingCalendar = async () => {
    this.hideTabContainers();
    (this._SfOnboardingCalendarContainer as HTMLDivElement).style.display = 'flex';
    const calendarJobs = await this.fetchCalendarJobs();
    this.renderOnboardingCalendar(calendarJobs);
  }

  loadOnboardingSuspense = async (year: string = this.getCurrentYearGeneric()) => {
    this.hideTabContainers();
    (this._SfOnboardingSuspenseContainer as HTMLDivElement).style.display = 'flex';
    const mappedSerializedLocations = await this.fetchMappedSerializedFunctions();
    const suspenseList = await this.fetchSuspenseList(year);
    console.log('suspenseList', suspenseList);
    this.renderOnboardingSuspense(mappedSerializedLocations, suspenseList, year);
  }

  loadOnboardingMappedGovLocations = async () => {
    this.hideTabContainers();
    (this._SfOnboardingGovLocationsContainer as HTMLDivElement).style.display = 'flex';
    let sourceLocationsArr = await this.fetchLocaltions()
    let tempArr = []
    for (let location of sourceLocationsArr) {
      let cols = JSON.parse(location.fields.cols[0])
      let data = JSON.parse(location.fields.data[0])
      let tempObj = {
        id: location.id,
        name: data[cols.indexOf("name")]
      }
      tempArr.push(tempObj)
    }
    sourceLocationsArr = tempArr
    console.log('locations', sourceLocationsArr)
    let mappedModules = await this.fetchMappedGovLocationsList();
    this.renderOnboardingGovLocations(sourceLocationsArr, mappedModules);
  }

  loadOnboardingMappedGovUsers = async () => {
    this.hideTabContainers();
    (this._SfOnboardingGovUsersContainer as HTMLDivElement).style.display = 'flex';
    let sourceLocationsArr = await this.fetchLocaltions()
    let mappedModules = await this.fetchMappedGovLocationsList();
    let tempArr = []
    for (let location of sourceLocationsArr) {
      let cols = JSON.parse(location.fields.cols[0])
      let data = JSON.parse(location.fields.data[0])
      if (mappedModules[location.id] != null) {
        for (let mappedModule of mappedModules[location.id]) {
          let tempObj = {
            id: location.id,
            name: data[cols.indexOf("name")],
            moduleid: mappedModule.id,
            modulename: mappedModule.name
          }
          tempArr.push(tempObj)
        }
      }
    }
    sourceLocationsArr = tempArr
    console.log('users', sourceLocationsArr)
    let mappedUsers = await this.fetchMappedGovUsersList();
    this.renderOnboardingGovUsers(sourceLocationsArr, mappedUsers);
  }

  calculateStartAndEndDateOfPast = (index: number = 0) => {

    //console.log('calculating start and end of past');

    let block = 10;

    if (index === 0) {

      block = 10;

    } else {

      block = 30;

    }

    let nowMonth = new Date().getMonth() + 1;
    let nowYear = parseInt(this.getCurrentYear(nowMonth + ""));
    let nowDate = new Date(nowYear, new Date().getMonth(), new Date().getDate())

    let currDay = nowDate;
    for (var i = 0; i < block; i++) {
      currDay.setDate(currDay.getDate() - 1);
    }

    const startDate = ("0" + (currDay.getMonth() + 1)).slice(-2) + "/" + ("0" + (currDay.getDate() + 1)).slice(-2) + "/" + currDay.getFullYear();

    // currDay = new Date();
    currDay = nowDate;
    for (var i = 0; i < block; i++) {
      currDay.setDate(currDay.getDate() + 1);
    }

    const endDate = ("0" + (currDay.getMonth() + 1)).slice(-2) + "/" + ("0" + (currDay.getDate() + 1)).slice(-2) + "/" + currDay.getFullYear();

    return { startDate: startDate, endDate: endDate }

  }

  calculateStartAndEndDateOfThis = (index: number = 0) => {

    //console.log('calculating start and end of this');

    let block = 10;
    var firstDate = new Date();
    firstDate = new Date(parseInt(this.getCurrentYear((firstDate.getMonth() + 1) + "")), firstDate.getMonth(), firstDate.getDate())

    if (index === 0) {

      let nowMonth = new Date().getMonth() + 1;
      let nowYear = parseInt(this.getCurrentYear(nowMonth + ""));
      let nowDate = new Date(nowYear, new Date().getMonth(), new Date().getDate())

      firstDate = (this.getFirstDateOfWeek(nowDate) as Date);
      console.log('this first date', firstDate);
      block = 10;

    }

    if (index === 1) {

      let nowMonth = new Date().getMonth() + 1;
      let nowYear = parseInt(this.getCurrentYear(nowMonth + ""));

      firstDate = new Date(nowYear, new Date().getMonth(), 1);
      //console.log('this first date', firstDate);
      block = 35;

    }

    let sDate = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());

    let eDate = new Date(sDate.getFullYear(), sDate.getMonth(), sDate.getDate());

    for (var i = 0; i < block; i++) {
      eDate.setDate(eDate.getDate() + 1);
    }

    return { startDate: (sDate.getMonth() + 1) + '/' + sDate.getDate() + '/' + sDate.getFullYear(), endDate: (eDate.getMonth() + 1) + '/' + eDate.getDate() + '/' + eDate.getFullYear() }


  }

  calculateStartAndEndDateOfUpcoming = (index: number = 0): any => {

    //console.log('calculating start and end of upcoming');

    let nowMonth = new Date().getMonth() + 1;
    let nowYear = parseInt(this.getCurrentYear(nowMonth + ""));

    let currDate = new Date();
    let sDate = new Date(nowYear, currDate.getMonth(), currDate.getDate());
    sDate.setDate(sDate.getDate() - 1);

    let block = 10;
    if (index === 0) {
      block = 8;
    } else if (index === 1) {
      block = 32;
    } else {
      block = 92;
    }

    let eDate = new Date(sDate.getFullYear(), sDate.getMonth(), sDate.getDate());

    for (var i = 0; i < block; i++) {
      eDate.setDate(eDate.getDate() + 1);
    }

    return { startDate: (sDate.getMonth() + 1) + '/' + sDate.getDate() + '/' + sDate.getFullYear(), endDate: (eDate.getMonth() + 1) + '/' + eDate.getDate() + '/' + eDate.getFullYear() }

  }

  calculateMonthFromIndex = (index: number = 0) => {
    let month = parseInt(this.calendarStartMM);
    for (var j = 0; j < 12; j++) {
      if (j == index) {
        return month
      } else {
        if (month === 12) {
          month = 1;
        } else {
          month++;
        }
      }
    }
    return 0;
  }

  calculateStartAndEndDateOfStream = (index: number = 0) => {

    let month = parseInt(this.calendarStartMM);

    //console.log('calculateStartAndEndDateOfStream', index, month);

    for (var j = 0; j < 12; j++) {
      if (j === index) {

        let currentMonth = month;
        let nowMonth = new Date().getMonth() + 1;
        //let nowYear = new Date().getFullYear();
        let nowYear = parseInt(this.getCurrentYear(nowMonth + ""));
        let lastMonth = -1;
        let nextMonth = -1;
        console.log('calculating startAndEndOfStream', index, nowMonth, currentMonth)
        let lastMonthsYear = -1;
        let nextMonthsYear = -1;

        if (currentMonth === 1) {
          // Mar
          lastMonth = 12;
          nextMonth = 2;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear + 1;
          }



        }

        if (currentMonth === 2) {
          // Mar
          lastMonth = 1;
          nextMonth = 3;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          } else {
            lastMonthsYear = nowYear + 1;
            nextMonthsYear = nowYear + 1;
          }

        }

        if (currentMonth === 3) {
          // Mar
          lastMonth = 2;
          nextMonth = 4;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          } else {
            lastMonthsYear = nowYear + 1;
            nextMonthsYear = nowYear + 1;
          }
        }

        if (currentMonth === 4) {
          // Mar
          lastMonth = 3;
          nextMonth = 5;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 5) {
          // Mar
          lastMonth = 4;
          nextMonth = 6;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 6) {
          // Mar
          lastMonth = 5;
          nextMonth = 7;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 7) {
          // Mar
          lastMonth = 6;
          nextMonth = 8;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 8) {
          // Mar
          lastMonth = 7;
          nextMonth = 9;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 9) {
          // Mar
          lastMonth = 8;
          nextMonth = 10;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 10) {
          // Mar
          lastMonth = 9;
          nextMonth = 11;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 11) {
          // Mar
          lastMonth = 10;
          nextMonth = 12;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear - 1;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear;
          }
        }

        if (currentMonth === 12) {
          // Mar
          lastMonth = 11;
          nextMonth = 1;
          if (nowMonth < parseInt(this.calendarStartMM)) {
            lastMonthsYear = nowYear - 1;
            nextMonthsYear = nowYear;
          } else {
            lastMonthsYear = nowYear;
            nextMonthsYear = nowYear + 1;
          }
        }

        // //console.log('calculateStartAndEndDateOfStream', currentMonth, index);

        // if(currentMonth <= 11 && currentMonth >= 2) {
        //   lastMonth = parseInt(((currentMonth - 1) + "").slice(-2));
        //   nextMonth = parseInt(((currentMonth + 1) + "").slice(-2));
        // } else if(currentMonth === 12) {
        //   lastMonth = 11;
        //   nextMonth = 1;
        // } else if(currentMonth === 1) {
        //   lastMonth = 12;
        //   nextMonth = 2;
        // }

        // //console.log('last month', lastMonth);
        // //console.log('next month', nextMonth, this.calendarStartMM);

        // // let lastMonthsYear = -1;
        // // let nextMonthsYear = -1;

        // if((lastMonth) >= parseInt(this.calendarStartMM)) {
        //   lastMonthsYear = parseInt(this.calendarStartYYYY);
        // } else {
        //   if(j === 0) {
        //     lastMonthsYear = parseInt(this.calendarStartYYYY);
        //   } else {
        //     lastMonthsYear = parseInt(this.calendarStartYYYY) + 1;
        //   }

        // }

        // if((nextMonth) >= parseInt(this.calendarStartMM)) {
        //   nextMonthsYear = parseInt(this.calendarStartYYYY);
        // } else {
        //   nextMonthsYear = parseInt(this.calendarStartYYYY) + 1;
        // }

        let startDate = ("0" + lastMonth).slice(-2) + "/25/" + lastMonthsYear;
        let endDate = ("0" + nextMonth).slice(-2) + "/01/" + nextMonthsYear;

        return { startDate: startDate, endDate: endDate };

      } else {

        if (month === 12) {
          month = 1;
        } else {
          month++;
        }

      }

    }

    return null;

  }

  renderAdhocConfirmed = async (adhocQuestions: any, render: boolean) => {

    for (var i = 0; i < Object.keys(adhocQuestions).length; i++) {

      const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement;
      console.log(radioYes.checked);

      if (render) {
        if (!radioYes.checked) {
          const divQuestion = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-question-' + i) as HTMLDivElement);
          if (divQuestion != null) {
            console.log('divQuestion', divQuestion, render, divQuestion.classList);
            if (!divQuestion.classList.contains('hide')) {
              divQuestion.classList.add('hide');
            }
          }
        }
      } else {
        if (!radioYes.checked) {
          const divQuestion = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-question-' + i) as HTMLDivElement);
          if (divQuestion != null) {
            console.log('divQuestion', divQuestion, render, divQuestion.classList);
            if (divQuestion.classList.contains('hide')) {
              divQuestion.classList.remove('hide');
            }
          }
        }
      }

    }

  }

  renderAdhoc = async (flagFetch: boolean = true, searchString: string = '', adhocQuestionsFetched: any = {}) => {

    var html = '';
    html += '<div part="stream-event-list" class="p-10 w-100" id="adhoc-list">';
    html += 'Loading ...';
    html += '</div>';

    (this._SfAdhocContainer as HTMLDivElement).innerHTML = html;

    const adhocQuestions: any = adhocQuestionsFetched;
    if (flagFetch) {
      const resultAdhoc = await this.fetchAdhoc();
      console.log('resultAdhoc', resultAdhoc);
      if (resultAdhoc.data?.events?.['00/00'] != null) {
        for (var i = 0; i < resultAdhoc.data.events["00/00"].length; i++) {

          if (resultAdhoc.data.events["00/00"][i]['adhocquestion'] != null && resultAdhoc.data.events["00/00"][i]['adhocquestion'].length > 0) {
            if (adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()] == null) {
              adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()] = [];
            }
            adhocQuestions[resultAdhoc.data.events["00/00"][i]['adhocquestion'][0].trim()].push(resultAdhoc.data.events["00/00"][i]);
          }
        }
      } else {
        await this.uploadAdHocCheckTime(false);
      }
      console.log('adHocQuestions', adhocQuestions);
    }

    // console.log('adhocQuestions', adhocQuestions);

    html = '';

    html += '<div class="d-flex w-100 flex-col">';
    html += '<div class="title-item-date d-flex flex-col">';
    html += '<label part="input-label">Search</label>'
    html += '<input id="ad-hoc-search" part="input" type="text" autofocus value="' + searchString + '"/>'
    html += '</div>';


    html += '<div class="d-flex w-100 flex-col">';
    html += '<div class="calendar-left-col-register flex-grow flex-col justify-start">';
    const arrAllTriggerIds: any = {};

    for (i = 0; i < Object.keys(adhocQuestions).length; i++) {

      // const firstCompliance = adhocQuestions[Object.keys(adhocQuestions)[i]][0];
      // console.log('triggers', i, '=' + firstCompliance.triggers + '=');
      // const firstComplianceTriggers = firstCompliance.triggers == null ? [] : firstCompliance.triggers == "" ? [] : JSON.parse(firstCompliance.triggers);
      const flagHide = !flagFetch && searchString.trim() !== '' && Object.keys(adhocQuestions)[i].toLowerCase().indexOf(searchString.trim().toLowerCase()) === -1;
      // console.log('Filter', flagHide, searchString, Object.keys(adhocQuestions)[i].toLowerCase().indexOf(searchString.toLowerCase()));
      html += '<div part="stream-event-selected" id="adhoc-question-' + i + '" class="pl-10 pr-10 pb-20 mb-10' + (flagHide ? ' hide' : '') + '">';

      html += '<h3 part="results-title" class="mb-0">' + Object.keys(adhocQuestions)[i] + '</h3>';
      html += '<button part="adhoc-compliance-list-count-not-selected" id="compliance-count-' + i + '" class="compliance-count mb-20 mt-10" part="text-view">' + adhocQuestions[Object.keys(adhocQuestions)[i]].length + ' compliance(s) associated</button><br />';
      html += '<div id="compliance-list-body-' + i + '" class="hide">'
      html += '<table class="mb-20">';
      html += '<tr>';
      html += '<td part="td-head">ComplianceId</td><td part="td-head">Location</td><td part="td-head">Obligation Title</td><td part="td-head">Obligation</td>';
      html += '</tr>'
      for (var j = 0; j < adhocQuestions[Object.keys(adhocQuestions)[i]].length; j++) {
        const compliance = adhocQuestions[Object.keys(adhocQuestions)[i]][j];

        html += '<tr>';
        html += ('<td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + compliance.id + '" minLength="10" lineSize="6"></sf-i-elastic-text></td><td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + compliance.locationname.replace(/ *\([^)]*\) */g, "").trim() + '" minLength="80" lineSize="6"></sf-i-elastic-text></td><td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + compliance.obligationtitle.replace(/ *\([^)]*\) */g, "").trim() + '" minLength="80" lineSize="6"></sf-i-elastic-text></td><td part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + compliance.obligation + '" minLength="80" lineSize="6"></sf-i-elastic-text></td>');
        html += '</tr>'
      }
      html += '</table>'
      html += '</div>'
      html += '<div>';
      html += '<input type="radio" name="my-radio-group-' + i + '" id="radio-no-' + i + '" value="no" checked/><label for="radio-no-' + i + '">No</label>&nbsp;&nbsp;<input type="radio" name="my-radio-group-' + i + '" id="radio-yes-' + i + '" value="yes" /><label for="radio-yes-' + i + '">Yes</label>';
      html += '</div>';
      html += '<div id="choose-date-' + i + '" class="mb-20 mt-20 hide">'
      html += ('<label part="input-label">Date of occurrence</label><br />');
      html += ('<input part="input" id="date-of-occurrence-' + i + '" type="date" style="margin-left: 0; margin-right: 0; padding: 0" /><br />');
      html += '<div class="mb-20"></div>'
      html += ('<label part="input-label">Remarks</label><br />');
      html += ('<textarea part="input" id="remarks-' + i + '" style="margin: 0; padding: 0"></textarea><br />');
      if (this.locationId != "") {
        html += ('<label part="td-head">Will be triggered for this location</label>');
      } else if (this.entityId != "") {
        html += ('<label part="td-head">Will be triggered for all locations of this entity</label>');
      } else if (this.countryId != "") {
        html += ('<label part="td-head">Will be triggered for all locations of this country</label>');
      }
      html += '</div>';

      let arrTriggerIds: Array<string> = [];
      let arrTriggerRemarks: Array<string> = [];
      let arrTriggerStatutes: any = {};
      let arrTriggers: any = {};

      for (var j = 0; j < adhocQuestions[Object.keys(adhocQuestions)[i]].length; j++) {
        const compliance = adhocQuestions[Object.keys(adhocQuestions)[i]][j];
        const locationname = compliance.locationname;
        const statutename = compliance.statute[0];
        const complianceTriggers = compliance.triggers == null ? [] : compliance.triggers == "" ? [] : JSON.parse(compliance.triggers);
        console.log('complianceTriggers', complianceTriggers, statutename);
        for (var k = 0; k < complianceTriggers.length; k++) {

          const triggerDate = complianceTriggers[k].triggerDate;
          const occurrenceDate = complianceTriggers[k].occurrenceDate;
          const complianceId = complianceTriggers[k].complianceId;
          const triggerId = complianceTriggers[k].triggerId;
          const remarks = complianceTriggers[k].remarks;

          const triggerdd = triggerDate.split('/')[0];
          const triggermm = triggerDate.split('/')[1];
          const triggeryyyy = triggerDate.split('/')[2];
          const tsTrigger = (new Date(triggeryyyy, parseInt(triggermm) - 1, triggerdd) + "").split(" ");
          const dateTrigger = (tsTrigger[0] + " " + tsTrigger[1] + " " + tsTrigger[2] + " " + tsTrigger[3]);

          const occurrencedd = occurrenceDate.split('/')[0];
          const occurrencemm = occurrenceDate.split('/')[1];
          const occurrenceyyyy = occurrenceDate.split('/')[2];
          const tsOccurrence = (new Date(occurrenceyyyy, parseInt(occurrencemm) - 1, occurrencedd) + "").split(" ");
          const dateOccurrence = (tsOccurrence[0] + " " + tsOccurrence[1] + " " + tsOccurrence[2] + " " + tsOccurrence[3]);

          console.log('triggerId', triggerId);
          if (!arrTriggerIds.includes(triggerId)) {
            arrTriggerIds.push(triggerId);
            arrTriggerRemarks.push(remarks)
          }
          if (arrTriggers[triggerId] == null) {
            arrTriggers[triggerId] = {};
          }
          if (arrTriggerStatutes[triggerId] == null) {
            arrTriggerStatutes[triggerId] = [];
          }
          if (arrTriggerStatutes[triggerId].indexOf(statutename.trim()) === -1) {
            arrTriggerStatutes[triggerId].push(statutename.trim());
          }
          if (arrTriggers[triggerId][dateTrigger] == null) {
            arrTriggers[triggerId][dateTrigger] = {};
          }
          if (arrTriggers[triggerId][dateTrigger][locationname] == null) {
            arrTriggers[triggerId][dateTrigger][locationname] = {};
          }
          if (arrTriggers[triggerId][dateTrigger][locationname][complianceId] == null) {
            arrTriggers[triggerId][dateTrigger][locationname][complianceId] = dateOccurrence;
          }
        }

      }

      arrAllTriggerIds[i] = arrTriggerIds;

      if (arrTriggerIds.length > 0) {

        html += '<div class="mt-20 pt-10">';
        html += ('<label part="adhoc-previous-triggers-count-not-selected" id="previous-triggers-' + i + '" class="mb-10">Previous Triggers (' + arrTriggerIds.length + ')</label><br />');
        html += '</div>';

      }

      html += '<div id="previous-triggers-body-' + i + '" class="hide">';

      for (var j = 0; j < arrTriggerIds.length; j++) {

        html += '<div class="d-flex align-center mt-20">'
        html += '<span class="badge-counter" part="badge-counter">' + (j + 1) + '</span>';
        html += '<div part="results-title"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + arrTriggerRemarks[j] + '" minLength="40"></sf-i-elastic-text></div>';
        html += '</div>'
        html += '<div part="td-body" class="d-flex align-center">'
        html += '<div>Trigger Id: </div>&nbsp;&nbsp;<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + arrTriggerIds[j] + '" minLength="10" lineSize="6"></sf-i-elastic-text>&nbsp;&nbsp; <button id="adhoc-delete-start-' + arrTriggerIds[j].replace(/-/g, "_") + '"  class="mr-10 adhoc-delete-start">Retract</button><button id="adhoc-delete-cancel-' + arrTriggerIds[j].replace(/-/g, "_") + '" class="mr-10 hide adhoc-delete-cancel">Cancel</button><button id="adhoc-delete-confirm-' + arrTriggerIds[j].replace(/-/g, "_") + '" statutes="' + arrTriggerStatutes[arrTriggerIds[j]].join(';') + '" class="mr-10 hide adhoc-delete-confirm">Confirm Retract</button>';
        html += '</div>'


        for (var k = 0; k < Object.keys(arrTriggers[arrTriggerIds[j]]).length; k++) {
          const dateTrigger = Object.keys(arrTriggers[arrTriggerIds[j]])[k];

          for (var l = 0; l < Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger]).length; l++) {
            const locationTrigger = Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger])[l];

            for (var m = 0; m < Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger]).length; m++) {
              const complianceTrigger = Object.keys(arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger])[m];
              const dateOccurrence = arrTriggers[arrTriggerIds[j]][dateTrigger][locationTrigger][complianceTrigger];
              html += '<div part="td-head" class="d-flex align-center ml-10">';
              html += '<div>Occurred on&nbsp;&nbsp;' + dateOccurrence + ',&nbsp;&nbsp;Triggered on&nbsp;&nbsp;' + dateTrigger + '&nbsp;&nbsp;at&nbsp;&nbsp;' + locationTrigger.replace(/ *\([^)]*\) */g, "").trim() + '&nbsp;&nbsp;for Compliance Id&nbsp;&nbsp;</div><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + complianceTrigger + '" minLength="10" lineSize="6"></sf-i-elastic-text>';
              html += '</div>';
            }

          }

        }

      }

      html += '</div>';

      html += '</div>';

    }



    html += '<div class="d-flex justify-end w-100" style="position: fixed; bottom: 70px; left: 0px;">';
    if (this.flagAdhoc) {
      html += '<div class="w-100 d-flex justify-center" part="ad-hoc-review-message-container">'
      html += '<span class="mt-10 pt-10 pb-10 mr-10 ml-10" part="ad-hoc-review-message">Please review the questions. Click yes to trigger associated ad hoc compliances wherever applicable. Click the finished button after you have completed the review.</span>'
      html += '<button part="button-mark-adhoc-reviewed" id="radio-mark-reviewed" class="d-flex align-center mt-10 pt-10 pb-10 mr-10 ml-10">I have completed the review</button>'
      html += '</div>'
      html += '<button part="button-lg-short" id="radio-submit" class="d-flex align-center mt-10 pt-10 pb-10 mr-10 ml-10"><span class="material-symbols-outlined">bolt</span>&nbsp;<span>Trigger</span></button>';
    } else {
      html += '<button part="button-lg-short" id="radio-submit" class="d-flex align-center mt-10 pt-10 pb-10 mr-10 ml-10"><span class="material-symbols-outlined">bolt</span>&nbsp;<span>Trigger</span></button>';
    }
    html += '<button part="button-lg-short-secondary" id="radio-submit-cancel" class="d-flex align-center mt-10 pt-10 pb-10 hide mr-10"><span class="material-symbols-outlined">close</span>&nbsp;<span>Cancel</span></button>'
    html += '<button part="button-lg-short" id="radio-submit-confirm" class="d-flex align-center mt-10 mr-10 pt-10 pb-10 hide"><span class="material-symbols-outlined">check</span>&nbsp;<span>Confirm</span></button>'
    html += '</div>';

    if (Object.keys(adhocQuestions).length === 0) {
      html = '<div class="d-flex justify-center mt-20 mb-20"><div part="results-title">No records found</div></div>';
    }

    (this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-list')!.innerHTML = html;

    let triggerDeleteStartButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-start') as NodeListOf<HTMLButtonElement>);
    for (let triggerDeleteStartButton of triggerDeleteStartButtons) {
      triggerDeleteStartButton.addEventListener('click', (e: any) => {
        const _id = e.currentTarget.id;
        const triggerid = _id.split('-')[3];

        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-start-' + triggerid) as HTMLButtonElement).classList.add('hide');
        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-cancel-' + triggerid) as HTMLButtonElement).classList.remove('hide');
        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-confirm-' + triggerid) as HTMLButtonElement).classList.remove('hide');

      })
    }
    let triggerDeleteCancelButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-cancel') as NodeListOf<HTMLButtonElement>);
    for (let triggerDeleteCancelButton of triggerDeleteCancelButtons) {
      triggerDeleteCancelButton.addEventListener('click', (e: any) => {
        const _id = e.currentTarget.id;
        const triggerid = _id.split('-')[3];

        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-start-' + triggerid) as HTMLButtonElement).classList.remove('hide');
        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-cancel-' + triggerid) as HTMLButtonElement).classList.add('hide');
        ((this._SfAdhocContainer as HTMLDivElement).querySelector('#adhoc-delete-confirm-' + triggerid) as HTMLButtonElement).classList.add('hide');


      })
    }
    let triggerDeleteConfirmButtons = ((this._SfAdhocContainer as HTMLDivElement).querySelectorAll('.adhoc-delete-confirm') as NodeListOf<HTMLButtonElement>);
    for (let triggerDeleteConfirmButton of triggerDeleteConfirmButtons) {
      triggerDeleteConfirmButton.addEventListener('click', async (e: any) => {
        const _id = e.currentTarget.id;
        const triggerid = _id.split('-')[3];
        const statutes = e.currentTarget.getAttribute('statutes')
        console.log('statutes', statutes)
        const untrigger = {
          projectid: this.projectId,
          triggerid: triggerid,
          statutes: statutes.split(';')
        }

        console.log('untrigger', untrigger);
        await this.uploadUnTriggerEvent(untrigger)
        // this.renderAdhoc();

      })
    }

    for (i = 0; i < Object.keys(adhocQuestions).length; i++) {

      const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement;
      radioYes.addEventListener('click', (e: any) => {
        const id = e.currentTarget.id.split('-')[2];
        const chooseDate = (this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-' + id) as HTMLDivElement;
        console.log(chooseDate);
        chooseDate.classList.remove('hide');
      })

      const radioNo = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-no-' + i) as HTMLInputElement;
      radioNo.addEventListener('click', (e: any) => {
        const id = e.currentTarget.id.split('-')[2];
        const chooseDate = (this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-' + id) as HTMLDivElement;
        console.log(chooseDate);
        chooseDate.classList.add('hide');
      })

    }

    for (i = 0; i < Object.keys(adhocQuestions).length; i++) {

      const complianceCount = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-count-' + i) as HTMLDivElement;
      complianceCount.addEventListener('click', (e: any) => {

        const index = e.currentTarget.id.split('-')[2];
        console.log(index);
        const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-list-body-' + index) as HTMLDivElement;
        if (body.classList.contains('hide')) {
          body.classList.remove('hide');
          e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-selected')
        } else {
          body.classList.add('hide');
          e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-not-selected')
        }

      });

    }

    for (i = 0; i < Object.keys(adhocQuestions).length; i++) {

      const previousTriggerCount = (this._SfAdhocContainer as HTMLDivElement).querySelector('#previous-triggers-' + i) as HTMLDivElement;
      if (previousTriggerCount != null) {
        previousTriggerCount.addEventListener('click', (e: any) => {
          const index = e.currentTarget.id.split('-')[2];
          console.log(index);
          const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#previous-triggers-body-' + index) as HTMLDivElement;
          if (body.classList.contains('hide')) {
            body.classList.remove('hide');
            e.currentTarget.setAttribute('part', 'adhoc-previous-triggers-count-selected')
          } else {
            body.classList.add('hide');
            e.currentTarget.setAttribute('part', 'adhoc-previous-triggers-count-not-selected')
          }
        });
      }


      // complianceCount.addEventListener('click', (e:any) => {

      //   const index = e.currentTarget.id.split('-')[2];
      //   console.log(index);
      //   const body = (this._SfAdhocContainer as HTMLDivElement).querySelector('#compliance-list-body-'+index) as HTMLDivElement;
      //   if(body.classList.contains('hide')) {
      //     body.classList.remove('hide');
      //     e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-selected')
      //   } else {
      //     body.classList.add('hide');
      //     e.currentTarget.setAttribute('part', 'adhoc-compliance-list-count-not-selected')
      //   }

      // });

    }

    const onSearch = Util.debounce((query: string) => {
      this.renderAdhoc(false, query, adhocQuestions);
    }, 200);

    let adHocQuestionsSearch = (this._SfAdhocContainer as HTMLDivElement).querySelector('#ad-hoc-search') as HTMLInputElement;
    if (adHocQuestionsSearch != null) {
      adHocQuestionsSearch.addEventListener('keyup', async (ev: any) => {
        //console.log('ev', ev.key);
        if (ev.key == "Enter") {
          const searchString = ev.currentTarget.value;
          console.log('input event', searchString)
          onSearch(searchString);
        }
      });
    }

    const submitButtonCancel = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit-cancel') as HTMLButtonElement;
    if (submitButtonCancel != null) {
      submitButtonCancel.addEventListener('click', () => {
        if (submitButtonConfirm != null && !submitButtonConfirm.classList.contains('hide')) {
          submitButtonConfirm.classList.add('hide');
        }

        if (submitButtonCancel != null && !submitButtonCancel.classList.contains('hide')) {
          submitButtonCancel.classList.add('hide');
        }

        if (submitButton != null && submitButton.classList.contains('hide')) {
          submitButton.classList.remove('hide');
        }
        this.renderAdhocConfirmed(adhocQuestions, false);
      })
    }

    const submitButtonConfirm = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit-confirm') as HTMLButtonElement;
    if (submitButtonConfirm != null) {

      submitButtonConfirm.addEventListener('click', async () => {

        let triggeredCompliances: any = [];

        var submitFlag = true;

        for (i = 0; i < Object.keys(adhocQuestions).length; i++) {

          const radioYes = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-yes-' + i) as HTMLInputElement;
          console.log(radioYes.checked);
          if (radioYes.checked) {
            const compliances = adhocQuestions[Object.keys(adhocQuestions)[i]];
            // const chooseDate = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#choose-date-'+i) as HTMLDivElement)
            const chooseDateInput = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#date-of-occurrence-' + i) as HTMLInputElement);
            const remarksInput = ((this._SfAdhocContainer as HTMLDivElement).querySelector('#remarks-' + i) as HTMLTextAreaElement);
            const dateOfTrigger = (new Date().getDate() + "").slice(-2) + "/" + ((new Date().getMonth() + 1) + "").slice(-2) + "/" + (new Date().getFullYear() + "");
            const dateOfOccurrence = chooseDateInput.value;
            const remarks = remarksInput.value;
            if (dateOfOccurrence == "") {
              chooseDateInput.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important');
              submitFlag = false;
            }
            // if (remarks == "") {
            //   remarksInput.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important');
            //   submitFlag = false;
            // }
            if (submitFlag) {
              triggeredCompliances.push({
                compliances: compliances,
                dateOfOccurrence: dateOfOccurrence,
                dateOfTrigger: dateOfTrigger,
                locationId: this.locationId,
                entityId: this.entityId,
                countryId: this.countryId,
                tagId: this.tagId,
                remarks: remarks,
              });
              chooseDateInput.setAttribute('style', 'border:');
            } else {
              break;
            }
          }

        }

        console.log('triggeredCompliances', triggeredCompliances);
        if (submitFlag) {
          await this.uploadTriggerEvent(triggeredCompliances);

          this.renderAdhoc();
        }

      });

    }

    const submitButton = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-submit') as HTMLButtonElement;
    if (submitButton != null) {

      submitButton.addEventListener('click', async () => {

        if (submitButtonConfirm != null && submitButtonConfirm.classList.contains('hide')) {
          submitButtonConfirm.classList.remove('hide');
        }

        if (submitButtonCancel != null && submitButtonCancel.classList.contains('hide')) {
          submitButtonCancel.classList.remove('hide');
        }

        if (submitButton != null && !submitButton.classList.contains('hide')) {
          submitButton.classList.add('hide');
        }

        this.renderAdhocConfirmed(adhocQuestions, true);

      });

    }

    const markReviewedButton = (this._SfAdhocContainer as HTMLDivElement).querySelector('#radio-mark-reviewed') as HTMLButtonElement;
    if (markReviewedButton != null) {
      markReviewedButton.addEventListener('click', async () => {
        await this.uploadAdHocCheckTime()
      })
    }

  }

  renderRegister = async () => {

    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    html += '<div class="title-item-date hide">';
    html += '<label part="input-label">Search</label><br />'
    html += '<input id="stream-search-mobile" part="input" type="text" autofocus/>'
    html += '</div>';

    html += '</div>';

    html += '<div class="d-flex w-100 flex-col">';
    html += '<div class="calendar-left-col-register flex-grow desktop-only flex-col justify-start">';

    html += '<div>';
    html += '<div class="title-item-date hide">';
    html += '<label part="input-label">Search</label><br />'
    html += '<input id="stream-search" part="input" type="text" autofocus/>'
    html += '</div>';

    console.log('showRegisterExport', this.showRegisterExport);
    // if (this.showRegisterExport && this.showRegisterExport == "true") {

    //   html += '<div class="title-item-date mt-20">';
    //   html += '<label part="input-label">Export</label><br /><br />'
    //   html += '<input type="radio" id="radio-csv" class="switch-csv" value="Excel" checked name="radio-report" part="radio-download"/>';
    //   html += '<label for="radio-csv" part="label-radio-download" class="mr-10">Registers (CSV)</label><br />';
    //   html += '<button id="button-download" part="button" class="d-flex justify-center align-center w-100 mt-20"><span class="material-symbols-outlined">download</span>&nbsp;&nbsp;<span>Export</span></button>';
    //   html += '</div>';
    // }
    html += '</div>';

    html += '</div>';

    html += '<div part="stream-event-list" class="calendar-right-data-register flex-grow pl-10 pt-20">';

    html += '</div>';
    html += '</div>';

    (this._SfRegisterContainer as HTMLDivElement).innerHTML = html;
    this.selectedCountryIndex = 0;
    this.selectedRegisterIndex = -1;
    this.registerEvents = await this.fetchRegisters("", "yes");
    this.renderRegisterEvents(this.registerEvents, "yes");

    (this._SfRegisterContainer as HTMLDivElement).querySelector('#stream-search')?.addEventListener('keyup', async (ev: any) => {
      //console.log('ev', ev.key);
      if (ev.key == "Enter") {
        const searchString = ((this._SfRegisterContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
        this.registerEvents = await this.fetchRegisters(searchString);
        this.renderRegisterEvents(this.registerEvents);
      }
    });

    (this._SfRegisterContainer as HTMLDivElement).querySelector('#button-download')?.addEventListener('click', async () => {
      let tempEvents = await this.fetchRegisters("", "all", "", "")
      this.renderRegisterEvents(tempEvents, "all");
      const ts = new Date();
      console.log(this.csvDataRegisters);
      const blob = new Blob([this.csvDataRegisters], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('download', 'report_' + ts + '.csv');
      a.click()

    });

  }

  renderFind = () => {

    //console.log('renderingFind');

    this.clearGraphData();
    console.log('this.clearSelectedGraphParam(); 3');
    this.clearSelectedGraphParam();
    this.clearSelectedLegend();

    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    html += '<div class="title-item-date">';
    html += '<label part="input-label">Search</label><br />'
    html += '<input id="stream-search-mobile" part="input" type="text" autofocus/>'
    html += '</div>';

    html += '</div>';

    html += '<div class="d-flex w-100">';
    html += '<div class="calendar-left-col desktop-only flex-col justify-start align-end">';

    html += '<div class="title-item-date">';
    html += '<label part="input-label">Search</label><br />'
    html += '<input id="stream-search" part="input" type="text" autofocus/>'
    html += '</div>';

    html += '</div>';

    html += '<div class="calendar-right-data flex-grow">';

    html += '</div>';
    html += '</div>';

    (this._SfFindContainer as HTMLDivElement).innerHTML = html;

    this.initFindRightCol();

    (this._SfFindContainer as HTMLDivElement).querySelector('#stream-search')?.addEventListener('keyup', (ev: any) => {
      //console.log('key', ev.key);
      if (ev.key == "Enter") {
        const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
        this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
      }
    });

  }

  renderCustom = () => {

    this.clearGraphData();
    console.log('this.clearSelectedGraphParam(); 4');
    this.clearSelectedGraphParam();
    this.clearSelectedLegend();

    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    html += '<div class="title-item-date">';
    html += '<label part="input-label">Start Date</label><br />'
    html += '<input id="stream-start-date-mobile" part="input" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label">End Date</label><br />'
    html += '<input id="stream-end-date-mobile" part="input" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-year-to-date-mobile" part="button-lg-short-secondary">Year To Date</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-quarter-mobile" part="button-lg-short-secondary">This Quarter</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-year-mobile" part="button-lg-short-secondary">This Year</button>'
    html += '</div>';

    html += '</div>';

    html += '<div class="d-flex w-100">';
    html += '<div class="calendar-left-col desktop-only flex-col justify-start align-end';
    if (this.mode == "viewer") {
      html += ' hide';
    }
    html += '">';

    html += '<div class="title-item-date">';
    html += '<label part="input-label">Start Date</label><br />'
    html += '<input id="stream-start-date" part="input" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label">End Date</label><br />'
    html += '<input id="stream-end-date" part="input" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-year-to-date" part="button-lg-short-secondary">Year To Date</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-quarter" part="button-lg-short-secondary">This Quarter</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-year" part="button-lg-short-secondary">This Year</button>'
    html += '</div>';


    html += '</div>';

    html += '<div class="calendar-right-data flex-grow">';

    html += '</div>';
    html += '</div>';

    (this._SfCustomContainer as HTMLDivElement).innerHTML = html;

    this.initCustomRightCol();

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date')?.addEventListener('change', (_ev: any) => {
      //console.log('start-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date')?.addEventListener('change', (_ev: any) => {
      //console.log('end-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile')?.addEventListener('change', (_ev: any) => {
      //console.log('start-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile')?.addEventListener('change', (_ev: any) => {
      //console.log('end-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date-mobile')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year-mobile')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      let year = parseInt(this.calendarStartYYYY);
      let month = parseInt(this.calendarStartMM) - 1;

      if (month === 0) {
        month = 12;
        year -= 1;
      }

      // Pad month
      const monthStr = month < 10 ? '0' + month : '' + month;

      // Determine last day of month (safe)
      const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month`
      const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay;
      const finalDate = `${year + 1}-${monthStr}-${dayStr}`;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });
    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      let year = parseInt(this.calendarStartYYYY);
      let month = parseInt(this.calendarStartMM) - 1;

      if (month === 0) {
        month = 12;
        year -= 1;
      }

      // Pad month
      const monthStr = month < 10 ? '0' + month : '' + month;

      // Determine last day of month (safe)
      const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month`
      const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay;
      const finalDate = `${year + 1}-${monthStr}-${dayStr}`;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter-mobile')?.addEventListener('click', () => {

      const mmCurrent = ((new Date().getMonth() + 1));

      let startDate: string = "";
      let endDate: string = "";

      if (mmCurrent >= 4 && mmCurrent <= 6) {

        startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";

      } else if (mmCurrent >= 6 && mmCurrent <= 9) {

        startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";

      } else if (mmCurrent >= 9 && mmCurrent <= 12) {

        startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";

      } else {
        startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01";
      }

      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });
    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter')?.addEventListener('click', () => {

      const mmCurrent = ((new Date().getMonth() + 1));

      let startDate: string = "";
      let endDate: string = "";

      if (mmCurrent >= 4 && mmCurrent <= 6) {

        startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";

      } else if (mmCurrent >= 6 && mmCurrent <= 9) {

        startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";

      } else if (mmCurrent >= 9 && mmCurrent <= 12) {

        startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";

      } else {
        startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01";
      }

      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate;
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
    });

    if (this.selectedFeatures.indexOf('contracts') >= 0 && this.mode != "viewer") {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year') as HTMLButtonElement).click();
    }
    // for(var i = 0; i < 3; i++) {
    //   (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', (ev: any)=> {
    //     const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]);
    //     //console.log('clicked ', target);
    //     this.renderPast(target);
    //   })
    // }
  }

  renderCustomViewer = () => {

    this.clearGraphData();
    this.clearSelectedGraphParam();
    this.clearSelectedLegend();

    if (this.locationId != "") {
      this.statisticsLoadLocation = true;
    }
    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    html += '<div class="title-item-date">';
    html += '<label part="input-label">Start Date</label><br />'
    html += '<input id="stream-start-date-mobile" part="date-range-preselected" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label">End Date</label><br />'
    html += '<input id="stream-end-date-mobile" part="date-range-preselected" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-year-to-date-mobile" part="button-range-preselected">Year To Date</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-quarter-mobile" part="button-range-preselected">This Quarter</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-year-mobile" part="button-range-preselected">This Year</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label-filter-criteria" id="input-label-filter-mobile">Filter Criteria</label>'
    html += '<select id="select-filter-criteria-mobile"></select>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label-filter-value" id="input-label-criteria-mobile"></label>'
    html += '<select id="select-filter-values-mobile"></select>'
    html += '</div>';

    html += '<div class="title-item-date">';
    html += '<label part="input-label-subfilter-criteria" id="input-label-subfilter-mobile">Subfilter Criteria</label>'
    html += '<select id="select-subfilter-criteria-mobile"></select>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<label part="input-label-subfilter-value" id="input-label-subfilter-value-mobile"></label>'
    html += '<select id="select-subfilter-values-mobile"></select>'
    html += '</div>';


    html += '</div>';

    html += '<div class="d-flex w-100">';
    html += '<div class="calendar-left-col desktop-only flex-col justify-start align-end">';

    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label">Start Date</label>'
    html += '<input id="stream-start-date" part="date-range-preselected" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label">End Date</label>'
    html += '<input id="stream-end-date" part="date-range-preselected" type="date" />'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-year-to-date" part="button-range-preselected">Year To Date</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-quarter" part="button-range-preselected">This Quarter</button>'
    html += '</div>';
    html += '<div class="title-item-date">';
    html += '<button id="button-this-year" part="button-range-preselected">This Year</button>'
    html += '</div>';
    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label-filter-criteria" id="input-label-filter">Filter Criteria</label>'
    html += '<select part="input-select-calendar-filter" id="select-filter-criteria"></select>'
    html += '</div>';
    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label-filter-value" id="input-label-criteria"></label>'
    html += '<select part="input-select-calendar-filter" id="select-filter-values"></select>'
    html += '</div>';
    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label-subfilter-criteria" id="input-label-subfilter">Subfilter Criteria</label>'
    html += '<select part="input-select-calendar-subfilter" id="select-subfilter-criteria"></select>'
    html += '</div>';
    html += '<div class="title-item-date d-flex flex-col align-start">';
    html += '<label part="input-label-subfilter-value" id="input-label-subfilter-value"></label>'
    html += '<select part="input-select-calendar-subfilter" id="select-subfilter-values"></select>'

    html += '</div>';


    html += '</div>';

    html += '<div class="calendar-right-data flex-grow">';

    html += '</div>';
    html += '</div>';

    console.log('html', html);
    (this._SfCustomContainer as HTMLDivElement).innerHTML = html;

    this.initCustomRightColViewer();

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date')?.addEventListener('change', (_ev: any) => {
      //console.log('start-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date')?.addEventListener('change', (_ev: any) => {
      //console.log('end-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile')?.addEventListener('change', (_ev: any) => {
      //console.log('start-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile')?.addEventListener('change', (_ev: any) => {
      //console.log('end-date', ev);
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date-mobile')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + ("0" + (new Date().getDate())).slice(-2);;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year-mobile')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      let year = parseInt(this.calendarStartYYYY);
      let month = parseInt(this.calendarStartMM) - 1;

      if (month === 0) {
        month = 12;
        year -= 1;
      }

      // Pad month
      const monthStr = month < 10 ? '0' + month : '' + month;

      // Determine last day of month (safe)
      const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month`
      const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay;
      const finalDate = `${year + 1}-${monthStr}-${dayStr}`;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });
    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-year')?.addEventListener('click', () => {
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = this.calendarStartYYYY + '-' + this.calendarStartMM + '-' + this.calendarStartDD;
      let year = parseInt(this.calendarStartYYYY);
      let month = parseInt(this.calendarStartMM) - 1;

      if (month === 0) {
        month = 12;
        year -= 1;
      }

      // Pad month
      const monthStr = month < 10 ? '0' + month : '' + month;

      // Determine last day of month (safe)
      const lastDay = new Date(year, month, 0).getDate(); // day 0 of next month gives last day of `month`
      const dayStr = lastDay < 10 ? '0' + lastDay : '' + lastDay;
      const finalDate = `${year + 1}-${monthStr}-${dayStr}`;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = finalDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = finalDate;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter-mobile')?.addEventListener('click', () => {

      const mmCurrent = ((new Date().getMonth() + 1));

      let startDate: string = "";
      let endDate: string = "";

      if (mmCurrent >= 4 && mmCurrent <= 6) {

        startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";

      } else if (mmCurrent >= 6 && mmCurrent <= 9) {

        startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";

      } else if (mmCurrent >= 9 && mmCurrent <= 12) {

        startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";

      } else {
        startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01";
      }

      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });
    (this._SfCustomContainer as HTMLDivElement).querySelector('#button-this-quarter')?.addEventListener('click', () => {

      const mmCurrent = ((new Date().getMonth() + 1));

      let startDate: string = "";
      let endDate: string = "";

      if (mmCurrent >= 4 && mmCurrent <= 6) {

        startDate = this.calendarStartYYYY + '-' + '04' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";

      } else if (mmCurrent >= 6 && mmCurrent <= 9) {

        startDate = this.calendarStartYYYY + '-' + '07' + '-' + "01";
        endDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";

      } else if (mmCurrent >= 9 && mmCurrent <= 12) {

        startDate = this.calendarStartYYYY + '-' + '10' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";

      } else {
        startDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '01' + '-' + "01";
        endDate = (parseInt(this.calendarStartYYYY) + 1) + '-' + '04' + '-' + "01";
      }

      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-start-date-mobile') as HTMLInputElement).value = startDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date') as HTMLInputElement).value = endDate;
      ((this._SfCustomContainer as HTMLDivElement).querySelector('#stream-end-date-mobile') as HTMLInputElement).value = endDate;
      this.processDateSelectionViewer((this._SfCustomContainer as HTMLDivElement));
    });

    let selectFilterCriteria = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria') as HTMLSelectElement
    selectFilterCriteria.style.display = 'none'
    let selectFilterValues = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values') as HTMLSelectElement
    selectFilterValues.style.display = 'none'
    let inputLabelFilter = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-filter') as HTMLLabelElement
    inputLabelFilter.style.display = 'none';
    let selectSubfilterCriteria = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria') as HTMLSelectElement
    selectSubfilterCriteria.style.display = 'none'
    let selectSubfilterValues = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values') as HTMLSelectElement
    selectSubfilterValues.style.display = 'none'
    let inputLabelSubfilter = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-subfilter') as HTMLLabelElement
    inputLabelSubfilter.style.display = 'none';

    let selectFilterCriteriaMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-criteria-mobile') as HTMLSelectElement
    selectFilterCriteriaMobile.style.display = 'none'
    let selectFilterValuesMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-filter-values-mobile') as HTMLSelectElement
    selectFilterValuesMobile.style.display = 'none'
    let inputLabelFilterMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-filter-mobile') as HTMLLabelElement
    inputLabelFilterMobile.style.display = 'none';
    let selectSubfilterCriteriaMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-criteria-mobile') as HTMLSelectElement
    selectSubfilterCriteriaMobile.style.display = 'none'
    let selectSubfilterValuesMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#select-subfilter-values-mobile') as HTMLSelectElement
    selectSubfilterValuesMobile.style.display = 'none'
    let inputLabelSubfilterMobile = (this._SfCustomContainer as HTMLDivElement).querySelector('#input-label-subfilter-mobile') as HTMLLabelElement
    inputLabelSubfilterMobile.style.display = 'none';

    ((this._SfCustomContainer as HTMLDivElement).querySelector('#button-year-to-date') as HTMLButtonElement).click();
  }

  renderThis = (index: number = 1, showGraph: boolean = true, showBackgroundButton: boolean) => {

    // this.clearGraphData();
    // this.clearSelectedGraphParam();
    // this.clearSelectedLegend();

    this.streamIndex = index;

    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    var part = "";
    if (index === 0) {
      part = "stream-month-selected";
    } else {
      part = "stream-month-not-selected";
    }
    html += '<div part="' + part + '" id="stream-month-0-mobile" part="month-title" class="title-item ' + part + ' mr-10">Current Week</div>';

    part = "";
    if (index === 1) {
      part = "stream-month-selected";
    } else {
      part = "stream-month-not-selected";
    }
    html += '<div part="' + part + '" id="stream-month-1-mobile" part="month-title" class="title-item ' + part + '">Current Month</div>';

    html += '</div>';

    html += '<div class="d-flex w-100">';
    html += '<div class="calendar-left-col desktop-only flex-col">';

    var part = "";
    if (index === 0) {
      part = "stream-month-selected";
    } else {
      part = "stream-month-not-selected";
    }
    html += '<div part="' + part + '" id="stream-month-0" part="month-title" class="title-item ' + part + '">Week</div>';

    part = "";
    if (index === 1) {
      part = "stream-month-selected";
    } else {
      part = "stream-month-not-selected";
    }
    html += '<div part="' + part + '" id="stream-month-1" part="month-title" class="title-item ' + part + '">Month</div>';

    html += '</div>';


    html += '<div class="calendar-right-data flex-grow">';

    // var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    var startDate = new Date();
    html += this.renderThisEvents(index, startDate, showGraph, showBackgroundButton);
    startDate.setDate(startDate.getDate() + 1);

    html += '</div>';
    html += this.renderSelectAllButtons();
    html += '</div>';

    (this._SfThisContainer as HTMLDivElement).innerHTML = html;
    this.renderButtonRefresh((this._SfThisContainer as HTMLDivElement));
    let backgroundProcessButton = (this._SfThisContainer as HTMLDivElement).querySelector('#button-background-process') as HTMLButtonElement
    if (backgroundProcessButton != null) {
      backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none'
      console.log('backgroundprocessbutton', backgroundProcessButton.style.display);
      if (showBackgroundButton) {
        backgroundProcessButton.addEventListener('click', () => {
          console.log('bulk-progress clicked')
          let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement
          bulkLoader.scrollIntoView();
        })
      }
    }
    const filterButton = (this._SfThisContainer as HTMLDivElement).querySelector('#filter-button') as HTMLButtonElement
    filterButton?.addEventListener('click', () => {
      const filterList = (this._SfThisContainer as HTMLDivElement).querySelector('#filter-list-container') as HTMLDivElement
      filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none')
      filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close')
      const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement
      filterSubmitButton.addEventListener('click', async () => {
        Util.setFeatures(this.selectedFeatures);
        const dateResult = this.calculateStartAndEndDateOfStream(index);
        console.log('dateresult', dateResult, index);
        console.log('selectedfeatures', this.selectedFeatures);
        this.currentColumnIndex = index + "";
        if (dateResult != null) {
          await this.renderWithFeatures(dateResult.startDate, dateResult.endDate);
        }
        this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
        this.renderStream(index, showGraph, showBackgroundButton);
      })
      // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement
      // selectFeatureAll.addEventListener('click',async(ev: any) => {
      //   let target = ev.target;
      //   if(target.checked){
      //     for(let feature of this.getFeatures()){
      //       if(this.selectedFeatures.indexOf(feature) < 0){
      //         this.selectedFeatures.push(feature);
      //       }
      //     }
      //   }else{
      //     this.selectedFeatures = []
      //   }
      //   const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      //   for(let selectFeature of selectFeatures){
      //     let id = selectFeature.id;
      //     let i = id.split('-')[3];
      //     let selectedFeature = this.getFeatures()[parseInt(i)]
      //     selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0
      //   }
      //   filterSubmitButton.style.visibility = 'visible'
      // })
      // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement
      // selectFeatureAllLabel.addEventListener('click',()=>{
      //   selectFeatureAll.checked = !selectFeatureAll.checked
      //   selectFeatureAll.click();
      // })
      const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf<HTMLLabelElement>
      for (let [i, selectFeature] of selectFeatures.entries()) {
        selectFeature.addEventListener('click', async (ev: any) => {
          let target = ev.target;
          let id = target.id;
          let i = id.split('-')[3];
          let selectedFeature = this.getFeatures()[i]
          if (target.checked) {
            if (this.selectedFeatures.indexOf(selectedFeature) < 0) {
              // this.selectedFeatures.push(selectedFeature)
              this.selectedFeatures = [selectedFeature]
            }
          }
          // else{
          //   // selectFeatureAll.checked = false;
          //   if(this.selectedFeatures.indexOf(selectedFeature) >= 0){
          //     this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1);
          //   }
          // }
          // filterSubmitButton.style.visibility = 'visible'
          filterSubmitButton.click();
        })
        selectFeatureLabels[i].addEventListener('click', () => {
          selectFeature.checked = !selectFeature.checked
          selectFeature.click();
        })
      }
    })
    const radioExpander = (this._SfThisContainer as HTMLDivElement).querySelector('#graph-radios-expander') as HTMLButtonElement;
    radioExpander?.addEventListener('click', (e: any) => {

      const button = (e.currentTarget as HTMLButtonElement);
      button.style.display = 'none';

      const arrRadios = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.chart-radio-item-secondary') as NodeListOf<HTMLDivElement>;
      arrRadios.forEach(div => {
        div.style.display = 'block';
      });


    });
    if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) {
      radioExpander?.click();
    }

    const radioCompleteness = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-completeness') as HTMLButtonElement;
    radioCompleteness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement));

    });

    const radioTimeliness = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-timeliness') as HTMLButtonElement;
    radioTimeliness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_TIMELINESS;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderTimelinessGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioCompliance = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement;
    radioCompliance?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLIANCE;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement))

    });

    // const radioCompliance = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement;
    // radioCompliance?.addEventListener('click', () => {

    //   this.flowGraph = this.FLOW_GRAPH_COMPLIANCE;
    //   this.renderStream(index);
    //   this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement))

    // });

    const radioRisk = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-risk') as HTMLButtonElement;
    radioRisk?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKAREAS;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderRiskGraph((this._SfThisContainer as HTMLDivElement))

    });


    const radioFunction = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-function') as HTMLButtonElement;
    radioFunction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FUNCTION;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderFunctionGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioRiskSeverity = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-riskseverity') as HTMLButtonElement;
    radioRiskSeverity?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderRiskSeverityGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioObligationType = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-obligationtype') as HTMLButtonElement;
    radioObligationType?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderObligationTypeGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioJurisdiction = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-jurisdiction') as HTMLButtonElement;
    radioJurisdiction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_JURISDICTION;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderJurisdictionGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioFrequency = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-frequency') as HTMLButtonElement;
    radioFrequency?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FREQUENCY;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderFrequencyGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioSubcategory = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-subcategory') as HTMLButtonElement;
    radioSubcategory?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderSubcategoryGraph((this._SfThisContainer as HTMLDivElement))

    });

    const radioLocation = (this._SfThisContainer as HTMLDivElement).querySelector('#radio-location') as HTMLButtonElement;
    radioLocation?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_LOCATION;
      this.renderThis(index, showGraph, showBackgroundButton);
      this.renderLocationGraph((this._SfThisContainer as HTMLDivElement))

    });

    // const buttonStatusMore = (this._SfThisContainer as HTMLDivElement).querySelector('#button-status-more');
    // buttonStatusMore?.addEventListener('click', () => {

    //   const divStatusList = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf<HTMLDivElement>;
    //   for(var i = 0; i < divStatusList.length; i++) {
    //     divStatusList[i].style.display = 'flex';
    //   }
    //   (buttonStatusMore as HTMLButtonElement).style.display = 'none';

    // });

    for (var i = 0; i < 3; i++) {
      (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', async (ev: any) => {
        const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]);
        //console.log('clicked ', target);
        const dateResult = this.calculateStartAndEndDateOfThis(target);
        console.log('this first date dateresult', dateResult, target);
        this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
        this.currentColumnIndex = target + "";
        await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
        this.renderThis(target, showGraph, showBackgroundButton);
      });

      (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + i + '-mobile')?.addEventListener('click', async (ev: any) => {
        const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]);
        //console.log('clicked ', target);
        this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
        this.currentColumnIndex = target + "";
        const dateResult = this.calculateStartAndEndDateOfThis(target);
        await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
        this.renderThis(target, showGraph, showBackgroundButton);
      })
    }
    const buttonRefresh = (this._SfThisContainer as HTMLDivElement).querySelector('#button-refresh') as HTMLButtonElement
    buttonRefresh.addEventListener('click', async () => {
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.currentColumnIndex = index + "";
      const dateResult = this.calculateStartAndEndDateOfThis(index);
      // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
      await this.renderWithFeatures(dateResult.startDate, dateResult.endDate);
      this.renderThis(index, showGraph, showBackgroundButton);
    })

    const chipSuspense = (this._SfThisContainer as HTMLDivElement).querySelector('#chip-suspense') as HTMLDivElement
    chipSuspense?.addEventListener('click', async () => {
      this.suspenseFlag = !this.suspenseFlag
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.currentColumnIndex = index + "";
      const dateResult = this.calculateStartAndEndDateOfThis(index);
      // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
      await this.renderWithFeatures(dateResult.startDate, dateResult.endDate);
      this.renderThis(index, showGraph, showBackgroundButton);
    })

    const externalInput = (this._SfThisContainer as HTMLDivElement).querySelector('#external-reporting-file-uploader') as HTMLInputElement
    externalInput.addEventListener('change', async () => {
      console.log('trying to upload external file', externalInput.files);
      if (externalInput.files != null) {
        let file = externalInput.files[0]
        if (file != null) {
          let jsonObj = await Util.parseMISExcel(file);
          console.log('parsed JSON', jsonObj, this.events)
          // let externalMapping = await this.fetchExternalMapping()
          // console.log('external mapping', externalMapping);

          // let changeCount = 0
          // let totalCount = 0
          // for (let dateStr of Object.keys(this.events)) {
          //   for (let compliance of this.events[dateStr]) {
          //     let complianceId = compliance.id
          //     totalCount++;
          //     if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //       let externalId = externalMapping.data[complianceId]
          //       if (jsonObj.compliances[externalId] != null) {
          //         console.log('external compliance found', jsonObj.compliances[externalId])
          //         changeCount++
          //       }
          //     }
          //   }
          // }

          // this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [
          //   () => {
          //     for (let dateStr of Object.keys(this.events)) {
          //       for (let [index, compliance] of this.events[dateStr].entries()) {
          //         let complianceId = compliance.id
          //         if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //           let externalId = externalMapping.data[complianceId]
          //           if (jsonObj.compliances[externalId] != null) {
          //             if (jsonObj.compliances[externalId].status == "Complied") {
          //               this.events[dateStr][index].approved = true;
          //               this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() });
          //             }
          //           }
          //         }
          //       }
          //     }
          //     this.renderAppropriateStream(this.sdate, this.edate, true);
          //     this.clearMessages()
          //   },
          //   () => { this.clearMessages() }
          // ])
        }
      }
    })

    this.attachListReportingListeners(this._SfThisContainer as HTMLDivElement);
    this.attachReviewListeners(this._SfThisContainer as HTMLDivElement);
    const buttonArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (i = 0; i < buttonArr.length; i++) {
      let indexPrevNext = i;
      buttonArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id;
                flagPrev = false;
              } else {
                prevString = "";
                indexPrev--
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < buttonArr.length - 1) {
              if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id;
                flagNext = false;
              } else {
                nextString = "";
                indexNext++
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfThisContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfThisContainer as HTMLDivElement, prevString, nextString);
        }
      })

    }

    const titleArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < titleArr.length; i++) {
      let indexPrevNext = i;
      titleArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        const flag = idArr[7];
        if (flag != null && flag == "reportedlocations") {
          return;
        }
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.selectedItems = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id;
                let prevIdArr = prevString.split("-")
                if ((prevIdArr[7] ?? "") == "reportedlocations") {
                  prevString = "";
                  indexPrev--;
                } else {
                  flagPrev = false;
                }
              } else {
                prevString = "";
                indexPrev--;
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < titleArr.length - 1) {
              if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id;
                let nextIdArr = nextString.split("-")
                if ((nextIdArr[7] ?? "") == "reportedlocations") {
                  nextString = "";
                  indexNext++;
                } else {
                  flagNext = false;
                }
              } else {
                indexNext++;
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfThisContainer as HTMLDivElement), prevString, nextString);
        }
      })

    }

    const buttonRenewArr = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonRenewArr.length; i++) {
      buttonRenewArr[i].addEventListener('click', async (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        console.log('idArr', idArr);
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]);
        let renewEvent = this.events[mmdd][j];
        let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true);
        console.log('renew clicked', fullEvent, fullEvent.reportformatvalues);
        this.renewRCMResource(fullEvent, fullEvent.reportformatvalues);
      })
    }

    const streamEventsContainer = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.stream-events-container') as NodeListOf<HTMLDivElement>;
    const buttonSelect = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;
    let selectAllArr = this.attachSelectAllListeners((this._SfThisContainer as HTMLDivElement), buttonSelect)
    const buttonSelectAll = selectAllArr[0]
    const buttonUnselectAll = selectAllArr[1]
    for (i = 0; i < buttonSelect.length; i++) {

      buttonSelect[i].addEventListener('click', (ev: any) => {

        //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length);

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        // const makercheckers = idArr[5];
        const docs = idArr[6];
        const module = idArr[14];

        if ((ev.target as HTMLInputElement).checked) {
          this.selectedItemIds.push(id);
        } else {
          this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1);
          let listReportingContainer = (this._SfThisContainer as HTMLDivElement).querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement
          listReportingContainer.style.display = 'none';
          listReportingContainer.innerHTML = '';
          let buttonListReporting = (this._SfThisContainer as HTMLDivElement).querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement
          buttonListReporting.setAttribute('part', 'button-list-reporting')
          let streamEventTitle = (this._SfThisContainer as HTMLDivElement).querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText
          streamEventTitle.removeAttribute('part')

        }

        if (this.selectedItemIds.length === 0) {

          for (var k = 0; k < buttonSelect.length; k++) {

            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const isbulk = idArr1[15] == "bulk"
            console.log('isBulk button-select1', id1, isbulk)
            if (isbulk) {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'block';
            }
            (streamEventsContainer[k] as HTMLDivElement).style.display = 'block';

          }

          let bulkUploadLables = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
          for (let bulkUploadLable of bulkUploadLables) {
            bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected`
          }

          buttonSelectAll.style.display = 'none';
          buttonUnselectAll.style.display = 'none';

        } else {

          if (this.selectedItemIds.length === 1) {

            const id1 = id;
            const idArr1 = id1.split("-")
            const status = idArr1[13].replace(/_/g, '-');
            this.selectedStatus = status;

          }

          let totalVisibleCount = 0
          for (var k = 0; k < buttonSelect.length; k++) {

            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const docs1 = idArr1[6];
            const status = idArr1[13].replace(/_/g, '-');
            const module1 = idArr1[14]
            const isbulk = idArr1[15] == "bulk"
            if (isbulk) {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
            }

            if (docs == docs1 && status == this.selectedStatus && module == module1) {
              totalVisibleCount++
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
              (streamEventsContainer[k] as HTMLDivElement).style.display = 'none';
            }

          }
          if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) {
            buttonSelectAll.style.display = 'none';
            buttonUnselectAll.style.display = 'flex';
          } else {
            buttonSelectAll.style.display = 'flex';
            buttonUnselectAll.style.display = 'none';
          }

          let bulkUploadLables = (this._SfThisContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
          for (let bulkUploadLable of bulkUploadLables) {
            bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected`
          }
        }

        // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'

        // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + ""));
        if (this.selectedItemIds.length == 1) {
          ev.target.scrollIntoView()
        }
      })

    }


    if (showGraph) {
      switch (this.flowGraph) {
        case this.FLOW_GRAPH_COMPLETENESS:
          this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_TIMELINESS:
          this.renderTimelinessGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_COMPLIANCE:
          this.renderComplianceGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_RISKAREAS:
          this.renderRiskGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_RISKSEVERITY:
          this.renderRiskSeverityGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_LOCATION:
          this.renderLocationGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_FUNCTION:
          this.renderFunctionGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_OBLIGATIONTYPE:
          this.renderObligationTypeGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_JURISDICTION:
          this.renderJurisdictionGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_FREQUENCY:
          this.renderFrequencyGraph((this._SfThisContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_SUBCATEGORY:
          this.renderSubcategoryGraph((this._SfThisContainer as HTMLDivElement));
          break;

        default:
          this.renderCompletenessGraph((this._SfThisContainer as HTMLDivElement));
          break;
      }

    }

  }

  renderButtonRefresh = (eventsContainer: HTMLDivElement) => {
    document.addEventListener('scroll', () => {
      // console.log('scroll',window.scrollY)
      let buttonRefresh = eventsContainer.querySelector('#button-refresh') as HTMLButtonElement
      if (buttonRefresh != null) {
        if (window.scrollY > 720) {
          if (buttonRefresh.style.display == "flex") {

          } else {
            buttonRefresh.style.display = 'flex'
          }
        } else {
          if (buttonRefresh.style.display == "none") {

          } else {
            buttonRefresh.style.display = 'none'
          }
        }
      }
    })
  }

  renderStream = (index: number = 0, showGraph: boolean = true, showBackgroundButton: boolean) => {
    //console.log('flowgraph renderStream', this.flowGraph);

    this.streamIndex = index;

    // this.clearGraphData();
    // this.clearSelectedGraphParam();
    // this.clearSelectedLegend();


    var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);

    var html = '';

    html += '<div class="scroll-x w-100 mobile-only">';

    for (var i = 0; i < 12; i++) {

      var part = "";

      if (i === index) {
        part = "stream-month-selected";
      } else {
        part = "stream-month-not-selected";
      }

      html += '<div part="' + part + '" id="stream-month-' + i + '-mobile" part="month-title" class="title-item ' + part + ' mr-10">' + this.monthNames[startDate.getMonth()] + '&nbsp;' + startDate.getFullYear() % 100 + '</div>';
      startDate.setMonth(startDate.getMonth() + 1);

    }

    html += '</div>';

    html += '<div class="d-flex w-100">';
    html += '<div class="calendar-left-col desktop-only flex-col">';

    var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);

    for (i = 0; i < 12; i++) {

      var part = "";

      if (i === index) {
        part = "stream-month-selected";
      } else {
        part = "stream-month-not-selected";
      }

      html += '<div part="' + part + '" id="stream-month-' + i + '" part="month-title" class="title-item ' + part + '">' + this.monthNames[startDate.getMonth()] + '&nbsp;&nbsp;' + startDate.getFullYear() + '</div>';
      startDate.setMonth(startDate.getMonth() + 1);
    }

    html += '</div>';
    html += '<div class="calendar-right-data">';

    startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);
    for (i = 0; i < 12; i++) {
      if (i === index) {
        //console.log(i, index)
        html += this.renderStreamEvents(i, startDate.getMonth(), startDate.getFullYear(), showGraph, showBackgroundButton)
      }
      startDate.setMonth(startDate.getMonth() + 1);
    }
    html += '</div>';
    html += this.renderSelectAllButtons();
    html += '</div>';

    (this._SfStreamContainer as HTMLDivElement).innerHTML = html;
    this.renderButtonRefresh((this._SfStreamContainer as HTMLDivElement));
    this.attachTimelineFilterHandlers((this._SfStreamContainer as HTMLDivElement));
    const filterButton = (this._SfStreamContainer as HTMLDivElement).querySelector('#filter-button') as HTMLButtonElement
    filterButton?.addEventListener('click', () => {
      const filterList = (this._SfStreamContainer as HTMLDivElement).querySelector('#filter-list-container') as HTMLDivElement
      filterList.style.display = (filterList.style.display != 'block' ? 'block' : 'none')
      filterButton.innerHTML = (filterList.style.display != 'block' ? 'category' : 'close')
      const filterSubmitButton = filterList.querySelector('#button-submit-features') as HTMLButtonElement
      filterSubmitButton.addEventListener('click', async () => {
        Util.setFeatures(this.selectedFeatures);
        const dateResult = this.calculateStartAndEndDateOfStream(index);
        const monthResult = this.calculateMonthFromIndex(index);
        console.log('monthResult', monthResult);
        console.log('dateresult', dateResult, index);
        console.log('selectedfeatures', this.selectedFeatures);
        this.currentColumnIndex = index + "";

        if (this.selectedFeatures.indexOf('contracts') >= 0) {

          this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
          this.enableCustom();
          this.renderTabs(this.TAB_CUSTOM);
          console.log('stats clicked');
          if (this.myRole == this.TAB_VIEWER) {
            this.renderCustomViewer()
          } else {
            this.renderCustom();
          }
        } else {
          if (dateResult != null) {
            await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "no", ("0" + monthResult).slice(-2));
          }
          this.renderTabs(this.TAB_STREAM);
          this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
          this.renderStream(index, showGraph, showBackgroundButton);
        }
      })
      // const selectFeatureAll = filterList.querySelector('.input-select-feature-all') as HTMLInputElement
      // selectFeatureAll?.addEventListener('click',async(ev: any) => {
      //   let target = ev.target;
      //   if(target.checked){
      //     for(let feature of this.getFeatures()){
      //       if(this.selectedFeatures.indexOf(feature) < 0){
      //         this.selectedFeatures.push(feature);
      //       }
      //     }
      //   }else{
      //     this.selectedFeatures = []
      //   }
      //   const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      //   for(let selectFeature of selectFeatures){
      //     let id = selectFeature.id;
      //     let i = id.split('-')[3];
      //     let selectedFeature = this.getFeatures()[parseInt(i)]
      //     selectFeature.checked = this.selectedFeatures.indexOf(selectedFeature) >= 0
      //   }
      //   filterSubmitButton.style.visibility = 'visible'
      // })
      // const selectFeatureAllLabel = filterList.querySelector('#input-select-feature-label-all') as HTMLLabelElement
      // selectFeatureAllLabel?.addEventListener('click',()=>{
      //   selectFeatureAll.checked = !selectFeatureAll.checked;
      //   selectFeatureAll.click();
      // })
      const selectFeatures = filterList.querySelectorAll('.input-select-feature') as NodeListOf<HTMLInputElement>
      const selectFeatureLabels = filterList.querySelectorAll('.input-select-feature-label') as NodeListOf<HTMLLabelElement>
      for (let [i, selectFeature] of selectFeatures.entries()) {
        selectFeature.addEventListener('click', async (ev: any) => {
          let target = ev.target;
          let id = target.id;
          let i = id.split('-')[3];
          let selectedFeature = this.getFeatures()[i]
          if (target.checked) {
            if (this.selectedFeatures.indexOf(selectedFeature) < 0) {
              // this.selectedFeatures.push(selectedFeature)
              this.selectedFeatures = [selectedFeature]
            }
          }
          // else{
          //   // selectFeatureAll.checked = false;
          //   if(this.selectedFeatures.indexOf(selectedFeature) >= 0){
          //     this.selectedFeatures.splice(this.selectedFeatures.indexOf(selectedFeature),1);
          //   }
          // }
          // filterSubmitButton.style.visibility = 'visible'
          filterSubmitButton.click();
        })
        selectFeatureLabels[i].addEventListener('click', () => {
          selectFeature.checked = !selectFeature.checked
          selectFeature.click()
        })
      }
    })

    const radioExpander = (this._SfStreamContainer as HTMLDivElement).querySelector('#graph-radios-expander') as HTMLButtonElement;
    radioExpander?.addEventListener('click', (e: any) => {

      const button = (e.currentTarget as HTMLButtonElement);
      button.style.display = 'none';

      const arrRadios = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.chart-radio-item-secondary') as NodeListOf<HTMLDivElement>;
      arrRadios.forEach(div => {
        div.style.display = 'block';
      });


    });
    if (this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]] != null && this.CHARTS_LIST_BY_MODULES[this.selectedFeatures[0]].length <= 4) {
      radioExpander?.click();
    }
    const radioCompleteness = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-completeness') as HTMLButtonElement;
    radioCompleteness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement));

    });

    const radioTimeliness = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-timeliness') as HTMLButtonElement;
    radioTimeliness?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_TIMELINESS;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderTimelinessGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioCompliance = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-compliance') as HTMLButtonElement;
    radioCompliance?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_COMPLIANCE;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderComplianceGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioRisk = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-risk') as HTMLButtonElement;
    radioRisk?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKAREAS;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderRiskGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioRiskSeverity = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-riskseverity') as HTMLButtonElement;
    radioRiskSeverity?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_RISKSEVERITY;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderRiskSeverityGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioFunction = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-function') as HTMLButtonElement;
    radioFunction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FUNCTION;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderFunctionGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioObligationType = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-obligationtype') as HTMLButtonElement;
    radioObligationType?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_OBLIGATIONTYPE;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderObligationTypeGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioJurisdiction = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-jurisdiction') as HTMLButtonElement;
    radioJurisdiction?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_JURISDICTION;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderJurisdictionGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioFrequency = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-frequency') as HTMLButtonElement;
    radioFrequency?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_FREQUENCY;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderFrequencyGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioSubcategory = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-subcategory') as HTMLButtonElement;
    radioSubcategory?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_SUBCATEGORY;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderSubcategoryGraph((this._SfStreamContainer as HTMLDivElement))

    });

    const radioLocation = (this._SfStreamContainer as HTMLDivElement).querySelector('#radio-location') as HTMLButtonElement;
    radioLocation?.addEventListener('click', () => {

      this.flowGraph = this.FLOW_GRAPH_LOCATION;
      this.renderStream(index, showGraph, showBackgroundButton);
      this.renderLocationGraph((this._SfStreamContainer as HTMLDivElement))

    });
    let backgroundProcessButton = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-background-process') as HTMLButtonElement
    if (showBackgroundButton) {
      backgroundProcessButton.style.display = showBackgroundButton ? 'flex' : 'none'
      console.log('backgroundprocessbutton', backgroundProcessButton.style.display);
      if (showBackgroundButton) {
        backgroundProcessButton.addEventListener('click', () => {
          console.log('bulk-progress clicked')
          let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement
          bulkLoader.scrollIntoView();
        })
      }
    }

    // const buttonStatusMore = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-status-more');
    // buttonStatusMore?.addEventListener('click', () => {

    //   const divStatusList = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.late-statuses') as NodeListOf<HTMLDivElement>;
    //   for(var i = 0; i < divStatusList.length; i++) {
    //     divStatusList[i].style.display = 'flex';
    //   }
    //   (buttonStatusMore as HTMLButtonElement).style.display = 'none';

    // });

    for (var i = 0; i < 12; i++) {
      (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + i)?.addEventListener('click', async (ev: any) => {

        const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]);
        const dateResult = this.calculateStartAndEndDateOfStream(target);
        const monthResult = this.calculateMonthFromIndex(target);
        // console.log('monthResult', monthResult);
        //console.log('dateresult', dateResult);
        this.currentColumnIndex = target + "";
        if (dateResult != null) {
          await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
          // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2));
        }
        this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
        this.renderStream(target, showGraph, showBackgroundButton);

      });

      (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + i + '-mobile')?.addEventListener('click', async (ev: any) => {

        const target = parseInt((ev.target as HTMLDivElement).id.split('-')[2]);
        const dateResult = this.calculateStartAndEndDateOfStream(target);
        const monthResult = this.calculateMonthFromIndex(target);
        if (dateResult != null) {
          await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
          // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2));
        }
        this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
        this.currentColumnIndex = target + "";
        this.renderStream(target, showGraph, showBackgroundButton);

      })
    }
    const buttonRefresh = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-refresh') as HTMLButtonElement
    buttonRefresh?.addEventListener('click', async () => {
      const dateResult = this.calculateStartAndEndDateOfStream(index);
      const monthResult = this.calculateMonthFromIndex(index);
      console.log('monthResult', monthResult);
      console.log('dateresult', dateResult);
      this.currentColumnIndex = index + "";
      if (dateResult != null) {
        await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
        // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2));
      }
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.renderStream(index, showGraph, showBackgroundButton);
    })

    const chipSuspense = (this._SfStreamContainer as HTMLDivElement).querySelector('#chip-suspense') as HTMLDivElement
    chipSuspense?.addEventListener('click', async () => {
      this.suspenseFlag = !this.suspenseFlag
      const dateResult = this.calculateStartAndEndDateOfStream(index);
      const monthResult = this.calculateMonthFromIndex(index);
      console.log('monthResult', monthResult);
      console.log('dateresult', dateResult);
      this.currentColumnIndex = index + "";
      if (dateResult != null) {
        await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
        // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2));
      }
      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.renderStream(index, showGraph, showBackgroundButton);
    })

    const externalInput = (this._SfStreamContainer as HTMLDivElement).querySelector('#external-reporting-file-uploader') as HTMLInputElement
    externalInput.addEventListener('change', async () => {
      console.log('trying to upload external file', externalInput.files);
      if (externalInput.files != null) {
        let file = externalInput.files[0]
        if (file != null) {
          let jsonObj = await Util.parseMISExcel(file);
          console.log('parsed JSON', jsonObj, this.events)
          // let externalMapping = await this.fetchExternalMapping()
          // console.log('external mapping', externalMapping);

          // let changeCount = 0
          // let totalCount = 0
          // for (let dateStr of Object.keys(this.events)) {
          //   for (let compliance of this.events[dateStr]) {
          //     let complianceId = compliance.id
          //     totalCount++;
          //     if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //       let externalId = externalMapping.data[complianceId]
          //       if (jsonObj.compliances[externalId] != null) {
          //         console.log('external compliance found', jsonObj.compliances[externalId])
          //         changeCount++
          //       }
          //     }
          //   }
          // }

          // this.setSuccessBtn("Total " + changeCount + " out of " + totalCount + " compliances will be updated. Continue?", ["yes", "no"], [
          //   () => {
          //     for (let dateStr of Object.keys(this.events)) {
          //       for (let [index, compliance] of this.events[dateStr].entries()) {
          //         let complianceId = compliance.id
          //         if (externalMapping.data != null && externalMapping.data[complianceId] != null) {
          //           let externalId = externalMapping.data[complianceId]
          //           if (jsonObj.compliances[externalId] != null) {
          //             if (jsonObj.compliances[externalId].status == "Complied") {
          //               this.events[dateStr][index].approved = true;
          //               this.events[dateStr][index].comments.push({ author: "External Tool", comment: "Approved on External Tool", timestamp: new Date() });
          //             }
          //           }
          //         }
          //       }
          //     }
          //     this.renderAppropriateStream(this.sdate, this.edate, true);
          //     this.clearMessages()
          //   },
          //   () => { this.clearMessages() }
          // ])
        }
      }
    })


    this.attachListReportingListeners(this._SfStreamContainer as HTMLDivElement);
    this.attachReviewListeners(this._SfStreamContainer as HTMLDivElement);
    const buttonArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (i = 0; i < buttonArr.length; i++) {
      let indexPrevNext = i;
      buttonArr[i].addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            console.log('selectedItems', this.selectedItemIds[k], idArr[3] + '-' + idArr[4] + '-' + idArr[5], this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]));
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

          //console.log('commentsinlist', (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement, this.events[mmdd][j].comments, mmdd, j);


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id;
                flagPrev = false;
              } else {
                prevString = "";
                indexPrev--
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < buttonArr.length - 1) {
              if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id;
                flagNext = false;
              } else {
                nextString = "";
                indexNext++
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement);
          // console.log('errorFetchEvent', mmdd, j, buttonArr[i].outerHTML, idArr);
          console.log('previous event clicked', buttonArr[indexPrevNext - 1], prevString, indexPrevNext);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfStreamContainer as HTMLDivElement, prevString, nextString);
        }

      })

    }

    const titleArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < titleArr.length; i++) {
      let indexPrevNext = i;
      titleArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        const flag = idArr[7];
        if (flag != null && flag == "reportedlocations") {
          return;
        }
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.selectedItems = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id;
                let prevIdArr = prevString.split("-")
                if ((prevIdArr[7] ?? "") == "reportedlocations") {
                  prevString = "";
                  indexPrev--;
                } else {
                  flagPrev = false;
                }
              } else {
                prevString = "";
                indexPrev--;
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < titleArr.length - 1) {
              if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id;
                let nextIdArr = nextString.split("-")
                if ((nextIdArr[7] ?? "") == "reportedlocations") {
                  nextString = "";
                  indexNext++;
                } else {
                  flagNext = false;
                }
              } else {
                indexNext++;
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfStreamContainer as HTMLDivElement), prevString, nextString);
        }
      })

    }

    const buttonRenewArr = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonRenewArr.length; i++) {
      buttonRenewArr[i].addEventListener('click', async (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        console.log('idArr', idArr);
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]);
        let renewEvent = this.events[mmdd][j];
        let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true);
        console.log('renew clicked', fullEvent, fullEvent.reportformatvalues);
        this.renewRCMResource(fullEvent, fullEvent.reportformatvalues);
      })
    }

    const streamEventsContainer = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.stream-events-container') as NodeListOf<HTMLDivElement>;
    const buttonSelect = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;
    let selectAllArr = this.attachSelectAllListeners((this._SfStreamContainer as HTMLDivElement), buttonSelect)
    const buttonSelectAll = selectAllArr[0]
    const buttonUnselectAll = selectAllArr[1]

    for (i = 0; i < buttonSelect.length; i++) {

      buttonSelect[i].addEventListener('click', (ev: any) => {

        //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length);

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        // const makercheckers = idArr[5];
        const docs = idArr[6];
        const module = idArr[14];
        if ((ev.target as HTMLInputElement).checked) {
          this.selectedItemIds.push(id);
        } else {
          this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1);
          let listReportingContainer = (this._SfStreamContainer as HTMLDivElement).querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement
          listReportingContainer.style.display = 'none';
          listReportingContainer.innerHTML = '';
          let buttonListReporting = (this._SfStreamContainer as HTMLDivElement).querySelector('#button-list-reporting-' + mmdd.replace(/\//g, '-') + '-' + j + '-') as HTMLButtonElement
          buttonListReporting.setAttribute('part', 'button-list-reporting')
          let streamEventTitle = (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-event-title-' + mmdd.replace(/\//g, '-') + '-' + j + '-' + module + '-') as SfIElasticText
          streamEventTitle.removeAttribute('part')
        }

        if (this.selectedItemIds.length === 0) {

          for (var k = 0; k < buttonSelect.length; k++) {
            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const isbulk = idArr1[15] == "bulk"
            console.log('isBulk button-select2', id1, isbulk)
            if (isbulk) {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'block';
            }
            (streamEventsContainer[k] as HTMLDivElement).style.display = 'block';

          }

          let bulkUploadLables = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
          for (let bulkUploadLable of bulkUploadLables) {
            bulkUploadLable.innerHTML = ``
          }

          buttonSelectAll.style.display = 'none';
          buttonUnselectAll.style.display = 'none';

        } else {

          if (this.selectedItemIds.length === 1) {

            const id1 = id;
            const idArr1 = id1.split("-")
            const status = idArr1[13].replace(/_/g, '-');
            this.selectedStatus = status;

          }
          let totalVisibleCount = 0
          for (var k = 0; k < buttonSelect.length; k++) {

            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const docs1 = idArr1[6];
            const status = idArr1[13].replace(/_/g, '-');
            const module1 = idArr1[14]
            const isbulk = idArr1[15] == "bulk"
            console.log('isBulk button-select', id1, isbulk)
            if (isbulk) {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
            }

            if (docs == docs1 && status == this.selectedStatus && module == module1) {
              totalVisibleCount++
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
              (streamEventsContainer[k] as HTMLDivElement).style.display = 'none';
            }

          }

          let bulkUploadLables = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.bulk-upload-label') as NodeListOf<HTMLHeadingElement>
          for (let bulkUploadLable of bulkUploadLables) {
            bulkUploadLable.innerHTML = `${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected`
          }

          if (this.selectedItemIds.length >= parseInt(this.selectallblock) || this.selectedItemIds.length >= totalVisibleCount) {
            buttonSelectAll.style.display = 'none';
            buttonUnselectAll.style.display = 'flex';
          } else {
            buttonSelectAll.style.display = 'flex';
            buttonUnselectAll.style.display = 'none';

          }
        }



        // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'

        // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + ((new Date()).getFullYear() + ""));
        if (this.selectedItemIds.length == 1) {
          ev.target.scrollIntoView()
        }
      })

    }

    if (showGraph) {
      console.log('showing graph', showGraph, this.flowGraph)
      switch (this.flowGraph) {
        case this.FLOW_GRAPH_COMPLETENESS:
          this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_TIMELINESS:
          this.renderTimelinessGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_COMPLIANCE:
          this.renderComplianceGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_RISKAREAS:
          this.renderRiskGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_RISKSEVERITY:
          this.renderRiskSeverityGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_LOCATION:
          this.renderLocationGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_FUNCTION:
          this.renderFunctionGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_OBLIGATIONTYPE:
          this.renderObligationTypeGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_JURISDICTION:
          this.renderJurisdictionGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_FREQUENCY:
          this.renderFrequencyGraph((this._SfStreamContainer as HTMLDivElement));
          break;
        case this.FLOW_GRAPH_SUBCATEGORY:
          this.renderSubcategoryGraph((this._SfStreamContainer as HTMLDivElement));
          break;

        default:
          this.renderCompletenessGraph((this._SfStreamContainer as HTMLDivElement));
          break;
      }
    }

  }

  attachTimelineFilterHandlers = (divContainer: HTMLDivElement) => {

    const divs = divContainer.querySelectorAll('.chip') as NodeListOf<HTMLDivElement>;
    divs.forEach(div => {
      div.addEventListener('click', () => {

        // const spans = div.querySelectorAll('span') as NodeListOf<HTMLSpanElement>;
        // if(spans[2].innerHTML == "0") {
        //   this.setError('No items present for the selected filter!')
        //   setTimeout(() => {
        //     this.clearMessages();
        //   }, 2000);
        // } else {
        //   this.clickOnPie(false, parseInt(div.id.split('-')[2]))
        //   this.chart.update();
        // }

      })

    });

  }

  getFinancialYear = (mmddyyyy: string): string => {
    const date = new Date(mmddyyyy);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // getMonth() is 0-indexed

    let finYear: number;
    if (month >= 4) {
      // April to December → Financial year starts in this year
      finYear = year;
    } else {
      // January to March → Financial year started in previous year
      finYear = year - 1;
    }

    return `${finYear}`;
  }

  getYearFromMonthBetween = (startDateStr: string, endDateStr: string, monthStr: string): string => {
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    const month = parseInt(monthStr, 10); // Ensure month is a number
    console.log('getting date', startDate, endDate, month);
    if (isNaN(month) || month < 1 || month > 12) {
      return this.calendarStartYYYY
    }

    let current = new Date(startDate.getFullYear(), startDate.getMonth(), 1);

    while (current <= endDate) {
      if (current.getMonth() + 1 === month) { // getMonth() is 0-indexed
        return current.getFullYear() + "";
      }
      // Move to next month
      current.setMonth(current.getMonth() + 1);
    }

    // If no matching month found in the range
    return this.calendarStartYYYY;
  }

  getCurrentYearGeneric = () => {
    if (new Date().getMonth() >= 3) {
      return new Date().getFullYear() + ""
    }
    return (new Date().getFullYear() - 1) + ""
  }

  getCurrentYear = (mm: string) => {

    // var currMonth = new Date().getMonth() + 1;

    // // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    // //   yyyy = new Date().getFullYear() + "";
    // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() - 1) + "";
    // // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() + 1) + "";
    // // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    // //   yyyy = (new Date().getFullYear() + 1) + "";
    // // }

    // if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth < parseInt(this.calendarStartMM)) {
    //   yyyy = parseInt(this.calendarStartYYYY) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth <= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) - 1) + "";
    // } else if(parseInt(mm) < parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    // } else if(parseInt(mm) >= parseInt(this.calendarStartMM) && currMonth >= parseInt(this.calendarStartMM)) {
    //   yyyy = (parseInt(this.calendarStartYYYY) + 1) + "";
    // }

    // if(parseInt(mm) >= 4){
    //   return new Date().getFullYear() + ""
    // }else{
    //   return (new Date().getFullYear() + 1) + ""
    // }

    var yyyy = this.getYearFromMonthAndCalendarStart(mm);

    return yyyy;
  }

  clearButtonSelection = () => {

    const buttonSelect = (this._SfStreamContainer as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;

    for (var i = 0; i < buttonSelect.length; i++) {

      (buttonSelect[i] as HTMLInputElement).checked = false;

    }

  }

  clearGraphData = () => {
    this.chart = null;
    this.chart2 = null;
    this.chart3 = null;
    this.chart4 = null;
    this.riskAreasData = null;
    this.riskAreasPartStatusData = null;
    this.riskAreasLateStatusData = null;
    this.riskAreasComplianceStatusData = null;
    this.riskSeverityData = null;
    this.riskSeverityLateStatusData = null;
    this.riskSeverityPartStatusData = null;
    this.riskSeverityComplianceStatusData = null;
    this.functionData = null;
    this.functionLateStatusData = null;
    this.functionPartStatusData = null;
    this.functionComplianceStatusData = null;
    this.locationData = null;
    this.locationLateStatusData = null;
    this.locationPartStatusData = null;
    this.locationComplianceStatusData = null;
    this.obligationTypeData = null;
    this.obligationTypeLateStatusData = null;
    this.obligationTypePartStatusData = null;
    this.obligationTypeComplianceStatusData = null;
    this.jurisdictionData = null;
    this.jurisdictionPartStatusData = null;
    this.jurisdictionLateStatusData = null;
    this.jurisdictionComplianceStatusData = null;
    this.subcategoryData = null;
    this.subcategoryLateStatusData = null;
    this.subcategoryPartStatusData = null;
    this.subcategoryComplianceStatusData = null;
    this.frequencyData = null;
    this.frequencyLateStatusData = null;
    this.frequencyPartStatusData = null;
    this.frequencyComplianceStatusData = null;
  }

  showGraph = (divContainer: HTMLDivElement, index: number) => {
    console.log('showingGraph', index);
    if (index == 1) {

      (divContainer.querySelector('#myChart') as HTMLCanvasElement).parentElement!.style.display = 'block';

    }

    if (index == 4) {

      (divContainer.querySelector('#myChart4') as HTMLCanvasElement).parentElement!.style.display = 'block';

    }

    if (index == 2) {

      (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.display = 'block';
      // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).classList.add('gone');
      // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.height = '0px';
      // if(this.chart2 != null) {
      //   (this.chart2 as Chart).destroy();
      // }
      // this.chart2 = null;

    }

    if (index == 3) {

      (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.display = 'block';
      // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).classList.add('gone');
      // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.height = '0px';
      // if(this.chart3 != null) {
      //   (this.chart3 as Chart).destroy();
      // }
      // this.chart3 = null;

    }

  }

  clearGraph = (divContainer: HTMLDivElement, index: number) => {
    console.log('showingGraph clear', index)
    if (index == 1) {

      (divContainer.querySelector('#myChart') as HTMLCanvasElement).parentElement!.style.display = 'none';

    }

    if (index == 4) {

      (divContainer.querySelector('#myChart4') as HTMLCanvasElement).parentElement!.style.display = 'none';

    }

    if (index == 2) {

      (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.display = 'none';
      // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).classList.add('gone');
      // (divContainer.querySelector('#myChart2') as HTMLCanvasElement).parentElement!.style.height = '0px';
      // if(this.chart2 != null) {
      //   (this.chart2 as Chart).destroy();
      // }
      // this.chart2 = null;

    }

    if (index == 3) {

      (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.display = 'none';
      // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).classList.add('gone');
      // (divContainer.querySelector('#myChart3') as HTMLCanvasElement).parentElement!.style.height = '0px';
      // if(this.chart3 != null) {
      //   (this.chart3 as Chart).destroy();
      // }
      // this.chart3 = null;

    }

  }

  renderCompletenessCsvForGraph = (dataBar: any, parameter: string) => {

    this.csvCompletenessStats = parameter + ",Not Started,In Progress,Complete,Rejected\n";
    for (var i = 0; i < dataBar['labels'].length; i++) {
      this.csvCompletenessStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : "");
    }

    console.log('rendering csv completeness', dataBar, this.csvCompletenessStats);

  }

  renderTimelinessCsvForGraph = (dataBar: any, parameter: string) => {

    //console.log('dataBar', dataBar);

    this.csvTimelinessStats = parameter + ",In Time,Past Due Date,Late Approved,Late Executed,Late Reported\n";
    for (var i = 0; i < dataBar['labels'].length; i++) {
      this.csvTimelinessStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + "\",\"" + dataBar['datasets'][4]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : "");
    }

    //console.log('rendering csv csvTimelinessStats', this.csvTimelinessStats);

  }

  renderComplianceCsvForGraph = (dataBar: any, parameter: string) => {

    this.csvComplianceStats = parameter + ",Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance\n";
    for (var i = 0; i < dataBar['labels'].length; i++) {
      this.csvComplianceStats += "\"" + dataBar['labels'][i].join(" ") + "\",\"" + dataBar['datasets'][0]['data'][i] + "\",\"" + dataBar['datasets'][1]['data'][i] + "\",\"" + dataBar['datasets'][2]['data'][i] + "\",\"" + dataBar['datasets'][3]['data'][i] + "\",\"" + dataBar['datasets'][4]['data'][i] + "\",\"" + dataBar['datasets'][5]['data'][i] + (i < (dataBar['labels'].length - 1) ? "\"\n" : "");
    }

    //console.log('rendering csv csvComplianceStats', this.csvComplianceStats);

  }

  renderCompletenessGraph = (divContainer: HTMLDivElement, selectedTab: number = -1, selectedSummary: number = -1, title: string | string[] = "Completeness", fromStats: boolean = false) => {

    this.clearSelectedGraphParam();
    // this.clearSelectedLegend();

    this.csvGraphStats = "";
    this.csvCompletenessStats = "";
    this.csvTimelinessStats = "";
    this.csvComplianceStats = "";

    if ((divContainer.querySelector('#graph-approved') as HTMLSpanElement) == null) return;

    var dataApproved = (divContainer.querySelector('#graph-approved') as HTMLSpanElement).innerHTML;
    var dataNotStarted = (divContainer.querySelector('#graph-not-started') as HTMLSpanElement).innerHTML;
    var dataPendingApproval = (divContainer.querySelector('#graph-pending-approval') as HTMLSpanElement).innerHTML;
    var dataRejected = (divContainer.querySelector('#graph-rejected') as HTMLSpanElement).innerHTML;

    const ctx = divContainer.querySelector('#myChart') as ChartItem;
    this.showGraph(divContainer, 1);
    if (!fromStats) {
      this.clearGraph(divContainer, 2);
      this.clearGraph(divContainer, 3);
      this.clearGraph(divContainer, 4);
    }

    if (this.fill == "pattern") {

      const data = {
        labels: ['Approved', 'Not Started', 'Pending Approval', 'Rejected'],
        datasets: [{
          label: 'Compliances',
          data: [dataApproved, dataNotStarted, dataPendingApproval, dataRejected],
          borderWidth: 1,
          backgroundColor: [
            Util.createDiagonalPattern3(this.COLOR_APPROVED),
            Util.createDiagonalPattern2(this.COLOR_NOT_STARTED),
            Util.createDiagonalPattern1(this.COLOR_PENDING_APPROVAL),
            Util.createDiagonalPattern1(this.COLOR_REJECTED)
          ]
        }]
      }

      this.renderChartSettings(divContainer, selectedTab, selectedSummary, ctx);
      this.renderChart(ctx, 'doughnut', data, title, false)

    }
    const data = {
      labels: ['Approved', 'Not Started', 'Pending Approval', 'Rejected'],
      datasets: [{
        label: 'Compliances',
        data: [dataApproved, dataNotStarted, dataPendingApproval, dataRejected],
        borderWidth: 1,
        backgroundColor: [
          this.COLOR_APPROVED,
          this.COLOR_NOT_STARTED,
          this.COLOR_PENDING_APPROVAL,
          this.COLOR_REJECTED
        ]
      }]
    }

    this.csvGraphStats += 'Completeness,Approved,Not Started,Pending Approval,Rejected,Total\n';
    this.csvGraphStats += 'Total,' + dataApproved + ',' + dataNotStarted + ',' + dataPendingApproval + ',' + dataRejected + ',' + (parseInt(dataApproved) + parseInt(dataNotStarted) + parseInt(dataPendingApproval) + parseInt(dataRejected)) + '\n';

    const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsTimeliness.length; i++) {
      itemsTimeliness[i].style.display = 'none';
    }
    const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompleteness.length; i++) {
      itemsCompleteness[i].style.display = 'flex';
    }
    const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompliance.length; i++) {
      itemsCompliance[i].style.display = 'none';
    }
    let flagFilterFound = false;
    for (let label of data.labels) {
      if (label.toLowerCase().replace(/ /g, "-").replace('status-', '') === this.graphFilter) {
        flagFilterFound = true;
        break;
      }
    }
    if (!flagFilterFound) {
      this.graphFilter = ""
    }
    this.renderChartSettings(divContainer, selectedTab, selectedSummary, ctx, fromStats);
    this.renderChart(ctx, 'doughnut', data, title, false, false, fromStats)

  }

  renderComplianceGraph = (divContainer: HTMLDivElement) => {

    //console.log('Rendering compliance graph...');

    this.clearSelectedGraphParam();
    // this.clearSelectedLegend();

    this.csvGraphStats = "";
    this.csvCompletenessStats = "";
    this.csvTimelinessStats = "";
    this.csvComplianceStats = "";
    console.log('contracts')
    let data: any = null;
    let ctx: any = null;
    if (this.selectedFeatures.indexOf('contracts') >= 0) {
      var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML;
      var dataActive = (divContainer.querySelector('#graph-active') as HTMLSpanElement).innerHTML;
      var dataAboutToExpire = (divContainer.querySelector('#graph-about-to-expire') as HTMLSpanElement).innerHTML;
      var dataExpired = (divContainer.querySelector('#graph-expired') as HTMLSpanElement).innerHTML;
      var dataTerminated = (divContainer.querySelector('#graph-terminated') as HTMLSpanElement).innerHTML;

      ctx = divContainer.querySelector('#myChart') as ChartItem;
      this.showGraph(divContainer, 1);
      this.clearGraph(divContainer, 2);
      this.clearGraph(divContainer, 3);
      this.clearGraph(divContainer, 4);

      data = {
        labels: ['Active', 'About To Expire', 'Expired', 'Terminated'],
        datasets: [{
          label: 'Compliances',
          data: [dataActive, dataAboutToExpire, dataExpired, dataTerminated],
          borderWidth: 1,
          backgroundColor: [
            this.COLOR_SCHEDULED,
            this.COLOR_PARTIALLY_COMPLIED,
            this.COLOR_NOT_COMPLIED,
            // this.COLOR_COMPLIED,
            // this.COLOR_COMPLIED_WITH_EXCEPTION,
            this.COLOR_REPORTED_NON_COMPLIANCE
          ]
        }]
      }

      this.csvGraphStats += 'Compliance,Active,About To Expire,Expired,Terminated,Total\n';
      this.csvGraphStats += 'Count,' + parseInt(dataActive) + ',' + parseInt(dataAboutToExpire) + ',' + parseInt(dataExpired) + ',' + parseInt(dataTerminated) + ',' + parseInt(dataTotal) + '\n';
    } else {
      var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML;
      var dataNotComplied = (divContainer.querySelector('#graph-not-complied') as HTMLSpanElement).innerHTML;
      var dataScheduled = (divContainer.querySelector('#graph-scheduled') as HTMLSpanElement).innerHTML;
      var dataPartiallyComplied = (divContainer.querySelector('#graph-partially-complied') as HTMLSpanElement).innerHTML;
      var dataComplied = (divContainer.querySelector('#graph-complied') as HTMLSpanElement).innerHTML;
      var dataCompliedWithGaps = (divContainer.querySelector('#graph-complied-with-gaps') as HTMLSpanElement).innerHTML;
      var dataReportedNonComplaince = (divContainer.querySelector('#graph-reported-non-compliance') as HTMLSpanElement).innerHTML;

      ctx = divContainer.querySelector('#myChart') as ChartItem;
      this.showGraph(divContainer, 1);
      this.clearGraph(divContainer, 2);
      this.clearGraph(divContainer, 3);
      this.clearGraph(divContainer, 4);

      data = {
        labels: ['Scheduled', 'Not Complied', 'Partially Complied', 'Complied', 'Complied With Gaps', 'Reported Non Compliance'],
        datasets: [{
          label: 'Compliances',
          data: [dataScheduled, dataNotComplied, dataPartiallyComplied, dataComplied, dataCompliedWithGaps, dataReportedNonComplaince],
          borderWidth: 1,
          backgroundColor: [
            this.COLOR_SCHEDULED,
            this.COLOR_NOT_COMPLIED,
            this.COLOR_PARTIALLY_COMPLIED,
            this.COLOR_COMPLIED,
            this.COLOR_COMPLIED_WITH_EXCEPTION,
            this.COLOR_REPORTED_NON_COMPLIANCE
          ]
        }]
      }

      this.csvGraphStats += 'Compliance,Scheduled,Not Complied,Partially Complied,Complied,Complied With Gaps,Reported Non Compliance,Total\n';
      this.csvGraphStats += 'Count,' + parseInt(dataScheduled) + ',' + parseInt(dataNotComplied) + ',' + parseInt(dataPartiallyComplied) + ',' + parseInt(dataCompliedWithGaps) + ',' + parseInt(dataComplied) + ',' + parseInt(dataReportedNonComplaince) + ',' + parseInt(dataTotal) + '\n';
    }

    //console.log('rendering timeliness graph', this.csvGraphStats);

    const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsTimeliness.length; i++) {
      itemsTimeliness[i].style.display = 'none';
    }
    const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompleteness.length; i++) {
      itemsCompleteness[i].style.display = 'none';
    }
    const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompliance.length; i++) {
      itemsCompliance[i].style.display = 'flex';
    }
    let flagFilterFound = false;
    for (let label of data.labels) {
      console.log('finding flag', this.graphFilter, label.toLowerCase());
      if (label.toLowerCase() === this.graphFilter) {
        flagFilterFound = true;
        break;
      }
    }
    if (!flagFilterFound) {
      console.log('resetting flagFilter', this.graphFilter);
      this.graphFilter = ""
    }
    this.renderChartSettings(divContainer, -1, -1, ctx);
    this.renderChart(ctx, 'doughnut', data, "Compliance", false)

  }

  renderTimelinessGraph = (divContainer: HTMLDivElement) => {

    this.clearSelectedGraphParam();
    // this.clearSelectedLegend();

    this.csvGraphStats = "";
    this.csvCompletenessStats = "";
    this.csvTimelinessStats = "";
    this.csvComplianceStats = "";

    var dataTotal = (divContainer.querySelector('#graph-total') as HTMLSpanElement).innerHTML;
    var dataPastDueDate = (divContainer.querySelector('#graph-past-due-date') as HTMLSpanElement).innerHTML;
    var dataLateApproved = (divContainer.querySelector('#graph-late-approved') as HTMLSpanElement).innerHTML;
    var dataLateExecuted = (divContainer.querySelector('#graph-late-executed') as HTMLSpanElement).innerHTML;
    var dataLateReported = (divContainer.querySelector('#graph-late-reported') as HTMLSpanElement).innerHTML;

    const ctx = divContainer.querySelector('#myChart') as ChartItem;
    this.showGraph(divContainer, 1);
    this.clearGraph(divContainer, 2);
    this.clearGraph(divContainer, 3);
    this.clearGraph(divContainer, 4);

    const data = {
      labels: ['In Time', 'Past Due Date', 'Late Approved', 'Late Executed', 'Late Reported'],
      datasets: [{
        label: 'Compliances',
        data: [(parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted) + parseInt(dataLateReported))) + "", dataPastDueDate, dataLateApproved, dataLateExecuted, dataLateReported],
        borderWidth: 1,
        backgroundColor: [
          this.COLOR_NOT_STARTED,
          this.COLOR_PAST_DUE_DATE,
          this.COLOR_LATE_APPROVED,
          this.COLOR_LATE_EXECUTED,
          this.COLOR_LATE_REPORTED
        ]
      }]
    }

    this.csvGraphStats += 'Completeness,In Time,Past Due Date,Late Approved,Late Executed,Late Reported,Total\n';
    this.csvGraphStats += 'Count,' + (parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted))) + ',' + (parseInt(dataPastDueDate) + ',' + parseInt(dataLateApproved) + ',' + parseInt(dataLateExecuted) + ',' + parseInt(dataLateReported) + ',' + (parseInt(dataTotal) - (parseInt(dataPastDueDate) + parseInt(dataLateApproved) + parseInt(dataLateExecuted) + parseInt(dataLateReported)))) + '\n';

    //console.log('rendering timeliness graph', this.csvGraphStats);

    const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsTimeliness.length; i++) {
      itemsTimeliness[i].style.display = 'flex';
    }
    const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompleteness.length; i++) {
      itemsCompleteness[i].style.display = 'none';
    }
    const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompliance.length; i++) {
      itemsCompliance[i].style.display = 'none';
    }
    let flagFilterFound = false;
    for (let label of data.labels) {
      if (label.toLowerCase().replace(/ /g, "-").replace('status-', '') === this.graphFilter) {
        flagFilterFound = true;
        break;
      }
    }
    if (!flagFilterFound) {
      this.graphFilter = ""
    }
    this.renderChartSettings(divContainer, -1, -1, ctx);
    this.renderChart(ctx, 'doughnut', data, "Timeliness", false)

  }

  renderRiskSeverityGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    //console.log('Rendering risk severity', this.riskSeverityComplianceStatusData);

    this.renderGraph(divContainer, this.riskSeverityData, this.riskSeverityPartStatusData, this.riskSeverityLateStatusData, this.riskSeverityComplianceStatusData, 'RiskSeverity', flagBarChart, flagInModal);

  }

  renderObligationTypeGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.obligationTypeData, this.obligationTypePartStatusData, this.obligationTypeLateStatusData, this.obligationTypeComplianceStatusData, 'ObligationType', flagBarChart, flagInModal);

  }

  renderFunctionGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {
    console.log('renderingFunctionsGraph', this.functionData, this.functionPartStatusData, this.functionLateStatusData, this.functionComplianceStatusData);
    this.renderGraph(divContainer, this.functionData, this.functionPartStatusData, this.functionLateStatusData, this.functionComplianceStatusData, 'Function', flagBarChart, flagInModal);

  }

  renderLocationGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.locationData, this.locationPartStatusData, this.locationLateStatusData, this.locationComplianceStatusData, 'Location', flagBarChart, flagInModal);

  }

  renderJurisdictionGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.jurisdictionData, this.jurisdictionPartStatusData, this.jurisdictionLateStatusData, this.jurisdictionComplianceStatusData, 'Jurisdiction', flagBarChart, flagInModal);

  }

  renderSubcategoryGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.subcategoryData, this.subcategoryPartStatusData, this.subcategoryLateStatusData, this.subcategoryComplianceStatusData, 'SubCategory', flagBarChart, flagInModal);

  }

  renderFrequencyGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.frequencyData, this.frequencyPartStatusData, this.frequencyLateStatusData, this.frequencyComplianceStatusData, 'Frequency', flagBarChart, flagInModal);

  }

  renderRiskGraph = (divContainer: HTMLDivElement, flagBarChart: boolean = false, flagInModal: boolean = false) => {

    this.renderGraph(divContainer, this.riskAreasData, this.riskAreasPartStatusData, this.riskAreasLateStatusData, this.riskAreasComplianceStatusData, 'RiskAreas', flagBarChart, flagInModal);

  }

  populateGraphDataBarPart = (partData: any) => {

    const dataBar: any = {};

    dataBar['labels'] = [];
    for (var i = 0; i < Object.keys(partData).length; i++) {
      dataBar['labels'].push(this.formatLabel(Object.keys(partData)[i], 15));
    }
    dataBar['datasets'] = [];
    dataBar['datasets'].push({});
    dataBar['datasets'].push({});
    dataBar['datasets'].push({});
    dataBar['datasets'].push({});

    dataBar['datasets'][0]['label'] = 'Approved';
    dataBar['datasets'][0]['data'] = [];
    for (i = 0; i < Object.keys(partData).length; i++) {
      dataBar['datasets'][0]['data'].push(partData[Object.keys(partData)[i]]['approved']);
    }
    dataBar['datasets'][0]['backgroundColor'] = this.COLOR_APPROVED;

    dataBar['datasets'][1]['label'] = 'Pending Approval';
    dataBar['datasets'][1]['data'] = [];
    for (i = 0; i < Object.keys(partData).length; i++) {
      dataBar['datasets'][1]['data'].push(partData[Object.keys(partData)[i]]['pending-approval']);
    }
    dataBar['datasets'][1]['backgroundColor'] = this.COLOR_PENDING_APPROVAL;


    dataBar['datasets'][2]['label'] = 'Rejected';
    dataBar['datasets'][2]['data'] = [];
    for (i = 0; i < Object.keys(partData).length; i++) {
      dataBar['datasets'][2]['data'].push(partData[Object.keys(partData)[i]]['rejected']);
    }
    dataBar['datasets'][2]['backgroundColor'] = this.COLOR_REJECTED;

    dataBar['datasets'][3]['label'] = 'Not Started';
    dataBar['datasets'][3]['data'] = [];
    for (i = 0; i < Object.keys(partData).length; i++) {
      dataBar['datasets'][3]['data'].push(partData[Object.keys(partData)[i]]['not-started']);
    }
    dataBar['datasets'][3]['backgroundColor'] = this.COLOR_NOT_STARTED;

    return dataBar;

  }

  populateGraphDataBarLate = (lateData: any) => {

    const dataBar2: any = {};

    dataBar2['labels'] = [];
    for (var i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['labels'].push(this.formatLabel(Object.keys(lateData)[i], 15));
    }
    dataBar2['datasets'] = [];
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});

    dataBar2['datasets'][0]['label'] = 'In Time';
    dataBar2['datasets'][0]['data'] = [];
    for (i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['datasets'][0]['data'].push(lateData[Object.keys(lateData)[i]]['in-time']);
    }
    dataBar2['datasets'][0]['backgroundColor'] = '#888888';

    dataBar2['datasets'][1]['label'] = 'Past Due Date';
    dataBar2['datasets'][1]['data'] = [];
    for (i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['datasets'][1]['data'].push(lateData[Object.keys(lateData)[i]]['past-due-date']);
    }
    dataBar2['datasets'][1]['backgroundColor'] = this.COLOR_PAST_DUE_DATE;

    dataBar2['datasets'][2]['label'] = 'Late Executed';
    dataBar2['datasets'][2]['data'] = [];
    for (i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['datasets'][2]['data'].push(lateData[Object.keys(lateData)[i]]['late-executed']);
    }
    dataBar2['datasets'][2]['backgroundColor'] = this.COLOR_LATE_EXECUTED;

    dataBar2['datasets'][3]['label'] = 'Late Approved';
    dataBar2['datasets'][3]['data'] = [];
    for (i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['datasets'][3]['data'].push(lateData[Object.keys(lateData)[i]]['late-approved']);
    }
    dataBar2['datasets'][3]['backgroundColor'] = this.COLOR_LATE_APPROVED;

    dataBar2['datasets'][4]['label'] = 'Late Reported';
    dataBar2['datasets'][4]['data'] = [];
    for (i = 0; i < Object.keys(lateData).length; i++) {
      dataBar2['datasets'][4]['data'].push(lateData[Object.keys(lateData)[i]]['late-reported']);
    }
    dataBar2['datasets'][4]['backgroundColor'] = this.COLOR_LATE_REPORTED;

    return dataBar2;

  }

  populateGraphDataBarCompliance = (complianceData: any) => {

    const dataBar2: any = {};

    dataBar2['labels'] = [];
    for (var i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['labels'].push(this.formatLabel(Object.keys(complianceData)[i], 15));
    }
    dataBar2['datasets'] = [];
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});
    dataBar2['datasets'].push({});

    dataBar2['datasets'][0]['label'] = 'Scheduled';
    dataBar2['datasets'][0]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][0]['data'].push(complianceData[Object.keys(complianceData)[i]]['scheduled']);
    }
    dataBar2['datasets'][0]['backgroundColor'] = this.COLOR_SCHEDULED;

    dataBar2['datasets'][1]['label'] = 'Not Complied';
    dataBar2['datasets'][1]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][1]['data'].push(complianceData[Object.keys(complianceData)[i]]['not-complied']);
    }
    dataBar2['datasets'][1]['backgroundColor'] = this.COLOR_NOT_COMPLIED;

    dataBar2['datasets'][2]['label'] = 'Partially Complied';
    dataBar2['datasets'][2]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][2]['data'].push(complianceData[Object.keys(complianceData)[i]]['partially-complied']);
    }
    dataBar2['datasets'][2]['backgroundColor'] = this.COLOR_PARTIALLY_COMPLIED;

    dataBar2['datasets'][3]['label'] = 'Complied';
    dataBar2['datasets'][3]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][3]['data'].push(complianceData[Object.keys(complianceData)[i]]['complied']);
    }
    dataBar2['datasets'][3]['backgroundColor'] = this.COLOR_COMPLIED;

    dataBar2['datasets'][4]['label'] = 'Complied With Gaps';
    dataBar2['datasets'][4]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][4]['data'].push(complianceData[Object.keys(complianceData)[i]]['complied-with-gaps']);
    }
    dataBar2['datasets'][4]['backgroundColor'] = this.COLOR_COMPLIED_WITH_EXCEPTION;

    dataBar2['datasets'][5]['label'] = 'Reported Non Compliance';
    dataBar2['datasets'][5]['data'] = [];
    for (i = 0; i < Object.keys(complianceData).length; i++) {
      dataBar2['datasets'][5]['data'].push(complianceData[Object.keys(complianceData)[i]]['reported-non-compliance']);
    }
    dataBar2['datasets'][5]['backgroundColor'] = this.COLOR_REPORTED_NON_COMPLIANCE;

    return dataBar2;

  }

  populateGraphDataPie = (pieData: any) => {

    const data: any = {};
    data['labels'] = [];
    data['datasets'] = [];
    data['datasets'].push({});
    data['datasets'][0]['data'] = [];
    data['datasets'][0]['backgroundColor'] = [];
    data['datasets'][0]['borderWidth'] = 1;
    for (var i = 0; i < Object.keys(pieData).length; i++) {
      data['labels'].push(Object.keys(pieData)[i]);
    }
    for (var i = 0; i < Object.keys(pieData).length; i++) {
      data['datasets'][0]['data'].push(pieData[Object.keys(pieData)[i]]);
      data['datasets'][0]['backgroundColor'].push(Util.getRandomColor(i));
    }

    return data;
  }

  renderPieCsv = (pieData: any, csv: string, param: string) => {

    csv += '"' + param + '",'
    for (var i = 0; i < Object.keys(pieData).length; i++) {
      csv += '"' + (Object.keys(pieData)[i]) + '"'
      if (i < (Object.keys(pieData).length - 1)) {
        csv += ','
      }
    }
    csv += '\n'

    csv += '"Count",'
    for (var i = 0; i < Object.keys(pieData).length; i++) {
      csv += '"' + (pieData[Object.keys(pieData)[i]]) + '"'
      if (i < (Object.keys(pieData).length - 1)) {
        csv += ','
      }
    }
    csv += '\n'

    return csv;

  }

  renderGraph = (divContainer: HTMLDivElement, pieData: any, partData: any, lateData: any, complianceData: any, param: string, flagBarChart: boolean, flagInModal: boolean) => {
    console.log('rendering graph chart2', pieData, partData);
    this.clearSelectedGraphParam();
    // this.clearSelectedLegend();

    this.csvGraphStats = "";
    this.csvCompletenessStats = "";
    this.csvTimelinessStats = "";
    this.csvComplianceStats = "";

    if (pieData == null) return;

    // this.clearGraph(divContainer, 4);

    const data: any = this.populateGraphDataPie(pieData);

    this.csvGraphStats = this.renderPieCsv(pieData, this.csvGraphStats, param);

    const ctx = divContainer.querySelector('#myChart') as ChartItem;
    this.renderChartSettings(divContainer, -1, -1, ctx);
    if (flagBarChart) {
      this.renderChart(ctx, 'bar', data, param + " Distribution", true, flagInModal)
    } else {
      this.renderChart(ctx, 'pie', data, param + " Distribution", true, flagInModal)
    }

    // 2

    const dataBar: any = this.populateGraphDataBarPart(partData);
    const ctx2 = divContainer.querySelector('#myChart2') as ChartItem;
    this.showGraph(divContainer, 2);
    this.renderChart2(ctx2, 'bar', dataBar, param + " vs Completeness")
    this.renderCompletenessCsvForGraph(dataBar, param + " Completeness Breakdown")

    // 3

    const dataBar2: any = this.populateGraphDataBarLate(lateData);
    const ctx3 = divContainer.querySelector('#myChart3') as ChartItem;
    this.showGraph(divContainer, 3);
    this.renderChart3(ctx3, 'bar', dataBar2, param + " vs Timeliness")
    this.renderTimelinessCsvForGraph(dataBar2, param + " Timeliness Breakdown")

    // 4

    //console.log('rendering compliance matrix', complianceData);

    const dataBar3: any = this.populateGraphDataBarCompliance(complianceData);

    console.log('rendering compliance matrix', dataBar3);

    const ctx4 = divContainer.querySelector('#myChart4') as ChartItem;
    this.showGraph(divContainer, 4);
    this.renderChart4(ctx4, 'bar', dataBar3, param + " vs Compliance")
    this.renderComplianceCsvForGraph(dataBar3, param + " Compliance Breakdown")

    const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsTimeliness.length; i++) {
      itemsTimeliness[i].style.display = 'flex';
    }
    const itemsCompleteness = divContainer.querySelectorAll('.stat-completeness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompleteness.length; i++) {
      itemsCompleteness[i].style.display = 'flex';
    }
    const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompliance.length; i++) {
      itemsCompliance[i].style.display = 'flex';
    }
    let flagFilterFound = false;
    for (let label of data.labels) {
      if (label.toLowerCase() === this.graphFilter) {
        flagFilterFound = true;
        break;
      }
    }
    if (!flagFilterFound) {
      this.graphFilter = ""
    }

  }

  renderStatisticsGraph = (divContainer: HTMLDivElement, functionStatsData: any, locationStatsData: any, reporterStatsData: any) => {
    console.log('rendering statistics graph', functionStatsData);

    // 2

    const dataBar: any = this.populateGraphDataBarPart(functionStatsData);
    const ctx2 = divContainer.querySelector('#myChart2') as ChartItem;
    this.showGraph(divContainer, 2);
    this.renderChart2(ctx2, 'bar', dataBar, "Functionwise Statistics", true)

    // 3

    const dataBar2: any = this.populateGraphDataBarPart(locationStatsData);
    const ctx3 = divContainer.querySelector('#myChart3') as ChartItem;
    this.showGraph(divContainer, 3);
    this.renderChart3(ctx3, 'bar', dataBar2, "Locationwise Statistics", true)

    // 4


    const dataBar3: any = this.populateGraphDataBarPart(reporterStatsData);

    console.log('rendering compliance matrix', dataBar3);

    const ctx4 = divContainer.querySelector('#myChart4') as ChartItem;
    this.showGraph(divContainer, 4);
    this.renderChart4(ctx4, 'bar', dataBar3, "Reporterwise Statistics", true)
  }

  renderStatisticsDetails = async (filter: string, filterid: string, filtervalue: string, filterstatus: string = "", removeFilterOnClose: boolean = false) => {


    let userid = this.userProfileId
    // let username = this.userName;
    let filterString = `countryid="${this.countryId}" locationid="${this.locationId}" entityid="${this.entityId}" tagid="${this.tagId}" selectedcriteria="${this.selectedCriteria}"`;
    console.log('FilterString', filterString, filterstatus)
    let rolestr = "viewer";
    if (filter == "all") {
      await this.fetchStatisticsEvents(this.sdate, this.edate, filter)
      if (Object.keys(this.events).length == 0) {
        await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, this.userProfileId, rolestr, this.entityId, "", "", "allevents", this.functionId);
      }
      // filterString = `tagid="${filterid}" selectedcriteria="Tag - ${filtervalue}"`;
      filterString = `${Util.titleCase(filterstatus)}`;
    } else if (filter == "reporter" || filter == "approver" || filter == "functionhead") {
      await this.fetchStatisticsEvents(this.sdate, this.edate, filter, filterid)
      if (Object.keys(this.events).length == 0) {
        userid = filterid;
        // username = filtervalue;
        rolestr = filter
        await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, userid, rolestr, this.entityId, this.countryId, this.locationId, this.tagId, this.functionId);
      }
      filterString = `${filter} - ${filtervalue}`;
    } else if (filter == "function") {
      await this.fetchStatisticsEvents(this.sdate, this.edate, filter, filterid)
      if (Object.keys(this.events).length == 0) {
        await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, this.userProfileId, rolestr, this.entityId, "", "", filterid, this.functionId);
        // filterString = `tagid="${filterid}" selectedcriteria="Tag - ${filtervalue}"`;
      }
      filterString = `Function - ${filtervalue}`;
    } else if (filter == "location") {
      await this.fetchStatisticsEvents(this.sdate, this.edate, filter, filterid)
      if (Object.keys(this.events).length == 0) {
        await this.fetchOnlyYearlyUserCalendar(this.sdate, this.edate, "", "yes", "00", this.calendarStartYYYY, this.userProfileId, rolestr, this.entityId, "", filterid, this.tagId, this.functionId);
      }
      // filterString = `locationid="${filterid}" selectedcriteria="Location - ${filtervalue}"`;
      filterString = `Location - ${filtervalue}`;
    }

    var html = `
    
      <div class="d-flex justify-between m-20">
        <button part="button-icon" class="material-icons invisible">close</button>
        <h3 part="results-title" class="m-0">Statistics Details: <strong>${filterString}</strong></h3>
        <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
      </div>
    
    `;
    html += `
      
      <div id="list-container" class="list-container m-20 pb-20" part="list-container">
      <div id="chart-settings-controls" class="mt-20"></div>
      <div id="chart-settings"></div>
      </div>
    `;
    (this._SfDetailListContainer as HTMLDivElement).style.display = 'block';
    (this._SfDetailListContainer as HTMLDivElement).innerHTML = html;

    const lastDay = ((new Date(this.edate).getTime()) - new Date(this.sdate).getTime()) / (1000 * 60 * 60 * 24)
    let firstDay = new Date((new Date(this.sdate)).getFullYear(), (new Date(this.sdate)).getMonth(), (new Date(this.sdate)).getDate());
    let endDay = new Date((new Date(this.sdate)).getFullYear(), (new Date(this.sdate)).getMonth(), (new Date(this.sdate)).getDate());
    endDay?.setDate(endDay.getDate() + lastDay);
    console.log('firstday', firstDay, endDay)
    var period = ("0" + (firstDay.getMonth() + 1)).slice(-2) + "/" + ("0" + firstDay.getDate()).slice(-2) + '/' + firstDay.getFullYear() + ' - ' + ("0" + (endDay.getMonth() + 1)).slice(-2) + "/" + ("0" + endDay.getDate()).slice(-2) + '/' + endDay.getFullYear();

    console.log('rangeperiod', period, lastDay);

    var htmlEvents = `<div id="chart-settings-controls" class="mt-20"></div>
      <div id="chart-settings"></div>`
    htmlEvents += this.renderEvents(firstDay, endDay, 0, lastDay, false, 0, ((new Date(this.sdate)).getMonth()), period, (new Date(this.sdate)), "From " + firstDay.toLocaleDateString('en-IN') + " To " + endDay.toLocaleDateString('en-IN'), false, true);

    ((this._SfDetailListContainer as HTMLDivElement).querySelector('#list-container') as HTMLDivElement).innerHTML = htmlEvents;
    let divContainer = ((this._SfDetailListContainer as HTMLDivElement).querySelector('#list-container') as HTMLDivElement)

    this.renderChartSettings(divContainer, -1, 3, null, false);
    const itemsTimeliness = divContainer.querySelectorAll('.stat-timeliness') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsTimeliness.length; i++) {
      itemsTimeliness[i].style.display = 'none';
    }
    const itemsCompliance = divContainer.querySelectorAll('.stat-compliance') as NodeListOf<HTMLElement>;
    for (var i = 0; i < itemsCompliance.length; i++) {
      itemsCompliance[i].style.display = 'none';
    }
    if (filterstatus != "") {
      console.log('processGraphFilter calling', filterstatus, divContainer)
      this.graphParam = "";
      this.processGraphFilter(filterstatus, divContainer);
    } else {
      this.selectedFilters = null;
    }
    (this._SfDetailListContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      if (removeFilterOnClose) {
        this.graphParam = ""
      }
      (this._SfDetailListContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailListContainer as HTMLDivElement).style.display = 'none';

    });

    const buttonArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (i = 0; i < buttonArr.length; i++) {
      let indexPrevNext = i;
      buttonArr[i].addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            console.log('selectedItems', this.selectedItemIds[k], idArr[3] + '-' + idArr[4] + '-' + idArr[5], this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]));
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

          //console.log('commentsinlist', (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement, this.events[mmdd][j].comments, mmdd, j);


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((buttonArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (buttonArr[indexPrev - 1] as HTMLButtonElement).id;
                flagPrev = false;
              } else {
                prevString = "";
                indexPrev--
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < buttonArr.length - 1) {
              if (Util.isVisible((buttonArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (buttonArr[indexNext + 1] as HTMLButtonElement).id;
                flagNext = false;
              } else {
                nextString = "";
                indexNext++
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-'+this.currentColumnIndex) as HTMLButtonElement);
          // console.log('errorFetchEvent', mmdd, j, buttonArr[i].outerHTML, idArr);
          console.log('previous event clicked', buttonArr[indexPrevNext - 1], prevString, indexPrevNext);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, (this._SfStreamContainer as HTMLDivElement).querySelector('#stream-month-' + this.currentColumnIndex) as HTMLButtonElement, this._SfStreamContainer as HTMLDivElement, prevString, nextString, false, null, null, null, null, null, null, null, true);
        }

      })

    }

    const titleArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-event-title') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < titleArr.length; i++) {
      let indexPrevNext = i;
      titleArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        const module = idArr[6];
        const flag = idArr[7];
        if (flag != null && flag == "reportedlocations") {
          return;
        }
        var yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[3]);
        if (module === "notice") {
          this.renderNoticeDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "contract") {
          this.fetchContractDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "license") {
          this.fetchLicenseDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else if (module === "rcmresource") {
          this.fetchRCMResourceDetails(this.events[mmdd][j], mmdd + "/" + yyyy)
        } else {
          let found = false;
          for (var k = 0; k < this.selectedItemIds.length; k++) {
            if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
              found = true;
            }
          }
          if (!found) {
            this.selectedItemIds = [];
            this.selectedItems = [];
            this.clearButtonSelection();
          }

          // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'


          let prevString = "";
          let flagPrev = true;
          let indexPrev = indexPrevNext
          while (flagPrev) {
            if (indexPrev > 0) {
              if (Util.isVisible((titleArr[indexPrev - 1] as HTMLButtonElement))) {
                prevString = (titleArr[indexPrev - 1] as HTMLButtonElement).id;
                let prevIdArr = prevString.split("-")
                if ((prevIdArr[7] ?? "") == "reportedlocations") {
                  prevString = "";
                  indexPrev--;
                } else {
                  flagPrev = false;
                }
              } else {
                prevString = "";
                indexPrev--;
              }
            } else {
              flagPrev = false;
            }
          }
          let nextString = "";
          let flagNext = true;
          let indexNext = indexPrevNext
          while (flagNext) {
            if (indexNext < titleArr.length - 1) {
              if (Util.isVisible((titleArr[indexNext + 1] as HTMLButtonElement))) {
                nextString = (titleArr[indexNext + 1] as HTMLButtonElement).id;
                let nextIdArr = nextString.split("-")
                if ((nextIdArr[7] ?? "") == "reportedlocations") {
                  nextString = "";
                  indexNext++;
                } else {
                  flagNext = false;
                }
              } else {
                indexNext++;
              }
            } else {
              flagNext = false;
            }
          }
          // this.renderEventDetail(this.events[mmdd][j], mmdd + "/" + yyyy, null);
          this.fetchEventDetails(this.events[mmdd][j], mmdd + "/" + yyyy, null, (this._SfStreamContainer as HTMLDivElement), prevString, nextString, false, null, null, null, null, null, null, null, true);
        }
      })

    }

    const buttonRenewArr = (this._SfDetailListContainer as HTMLDivElement).querySelectorAll('.button-renew') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonRenewArr.length; i++) {
      buttonRenewArr[i].addEventListener('click', async (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        console.log('idArr', idArr);
        const mmdd = idArr[2] + "/" + idArr[3];
        const j = idArr[4];
        const yyyy = this.getYearFromMonthBetween(this.sdate, this.edate, idArr[2]);
        let renewEvent = this.events[mmdd][j];
        let fullEvent = await this.fetchRCMResourceDetails(renewEvent, mmdd + "/" + yyyy, true);
        console.log('renew clicked', fullEvent, fullEvent.reportformatvalues);
        this.renewRCMResource(fullEvent, fullEvent.reportformatvalues);
      })
    }

  }
  renderEventDetailShort = (compliance: any, selectedCountry: string, selectedStatute: string) => {
    var html = `
    
      <div class="d-flex justify-between m-20">
        <button part="button-icon" class="material-icons invisible">close</button>
        <h3 part="results-title" class="m-0">Compliance Details</h3>
        <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
      </div>
    
    `;

    let shortId: string = "";
    console.log('shoiwing compliance', compliance);
    const data = JSON.parse(compliance.data);
    console.log('compliance data', data)
    const cols = JSON.parse(compliance.cols);
    const configHome = Util.getProjectConfigHome();
    const showUnderstood = (configHome.features == null || (configHome.features.indexOf('hide-understood') < 0)) && (this.myRole == this.TAB_REPORTER)
    html += '<div part="obligation-title-top" class="d-flex">'
    html += data[cols.indexOf('obligationtitle')].replace(/\\n|\r?\n/g, ' ')
    html += '</div>'
    html += '<div part="applicability-top-container" class="d-flex flex-wrap">'
    const understood = compliance.understood ?? -1;


    html += '<div part="understood-container" class="d-flex flex-col flex-wrap align-start">'
    html += '<div part="understood-title">Review this compliance</div>'
    if (showUnderstood) {

      html += `
      <div part="understood-input-container">
          <label part="understood-radio-label">Understood Compliance?</label><br>
          <input type="radio" name="compliance" value="1" id="understood-radio-1"><label for="understood-radio-1" part="understood-radio-sub-label">Yes</label>
          <input type="radio" name="compliance" value="0" id="understood-radio-0"><label for="understood-radio-0" part="understood-radio-sub-label">No</label>
      </div>
      <div part="understood-input-container" id="understood-radio-container-1"${(understood < 1) ? ' class="hide"' : ''}>
          <label part="understood-radio-label">Understood Applicability?</label><br>
          <input type="radio" name="applicability" value="3" id="understood-radio-3"><label for="understood-radio-3" part="understood-radio-sub-label">Yes</label>
          <input type="radio" name="applicability" value="2" id="understood-radio-2"><label for="understood-radio-2" part="understood-radio-sub-label">No</label>
      </div>
      <div part="understood-input-container" id="understood-radio-container-2"${(understood < 3) ? ' class="hide"' : ''}>
          <label part="understood-radio-label">Applicable to?</label><br>
          <input type="radio" name="someoneElse" value="4" id="understood-radio-4"><label for="understood-radio-4" part="understood-radio-sub-label">Me</label>
          <input type="radio" name="someoneElse" value="5" id="understood-radio-5"><label for="understood-radio-5" part="understood-radio-sub-label">Someone Else</label>
      </div>
      <button part="button-lg-short" id="button-save-understood" class="d-flex justify-center align-center hide"><span class="material-symbols-outlined">grading</span><span>&nbsp;&nbsp;Save Review</span></button>
      `
    }

    html += '<div class="d-flex justify-end align-start mt-10 w-100">'
    html += '<textarea part="input" id="feedback-message" class="flex-grow mb-10" placeholder="Type your feedback message here..."></textarea>'
    // html += '</div>'
    // html += '<div class="d-flex justify-end w-100">'
    html += ('<button part="button-lg-short" id="button-feedback" class="hide d-flex justify-center align-center"><span class="material-symbols-outlined">comment</span><span>&nbsp;&nbsp;Send Feedback</span></button>');
    html += ('<button part="button-lg-short-secondary" id="button-feedback-cancel" class="hide d-flex justify-center align-center mr-10"><span class="material-symbols-outlined">close</span><span>&nbsp;&nbsp;Cancel</span></button>');
    html += ('<button part="button" id="button-feedback-confirm" class="d-flex justify-center align-center ml-10" disabled><span class="material-symbols-outlined">commentcheck</span><span>&nbsp;&nbsp;Submit</span></button>');
    html += '</div>';

    html += '</div>';


    html += '<div part="applicability-container" class="d-flex flex-col align-start">'
    html += '<div part="obligation-title">Your obligation is:</div>'
    html += '<div part="obligation-content">' + data[cols.indexOf('obligation')].replace(/\\n|\r?\n/g, '<br />') + '</div>'
    html += '</div>'

    html += '<div part="applicability-container" class="d-flex flex-col align-start">'
    html += '<div part="applicability-title">This is applicable to:</div>'
    html += '<div part="applicability-content">' + data[cols.indexOf('applicability')] + '</div>'

    html += '<div part="applicability-title" class="mt-20">This is mapped to Entities:</div>'
    let entities = []
    for (let entity of compliance.entities ?? []) {
      entities.push(entity.split(';')[0].replace(/\([^)]*\)/g, ""))
    }
    html += '<div part="applicability-content">' + entities.join(', ') + '</div>'

    html += '<div part="applicability-title" class="mt-20">This is mapped to Locations:</div>'
    let locations = []
    for (let location of compliance.locations ?? []) {
      locations.push(location.split(';')[0].replace(/\([^)]*\)/g, ""))
    }
    html += '<div part="applicability-content">' + locations.join(', ') + '</div>'
    html += '</div>'

    html += '</div>'



    html += '<div class="accordian-container m-20 pb-20" part="accordian-container">';

    html += '<div class="accordian-section section-basic pl-20 pr-20" part="accordian-section">';

    html += '<div class="d-flex flex-wrap accordian-body body-basic" part="accordian-body">';


    //console.log('cols', cols, cols.length);

    for (var k = 0; k < cols.length; k++) {
      if (!this.EXCLUDE_COLS_FROM_REGS.includes(cols[k].toLowerCase())) {

        if (cols[k].toLowerCase() == "attachment") {

          console.log('attachments', data[k]);
          if (typeof data[k] === "string") {
            let attachmentArr = JSON.parse(data[k].toString());
            if (attachmentArr.length > 0) {
              html += '<div class="m-20">';
              html += '<div part="detail-head"><strong>' + cols[k] + '</strong></div>'
              for (let attachment of attachmentArr) {

                html += `<sf-i-uploader class="event-attachment" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": attachment.key, "ext": attachment.ext }]).replace(/"/g, '&quot;')}" extract="no" mode="view" maximize="yes" hidepreview="yes" displaydetail="yes"></sf-i-uploader>`
              }
              html += '</div>';
            }
          } else {
            html += '<div class="m-20">';
            html += '<div part="detail-head"><strong>' + cols[k] + '</strong></div>'
            for (let attachmentStr of data[k]) {
              let attachment: any = {};
              if (typeof attachmentStr === "object") {
                attachment = attachmentStr;
              } else {
                attachment = JSON.parse(attachmentStr.toString());
              }
              html += `<sf-i-uploader class="event-attachment" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": attachment.key, "ext": attachment.ext }]).replace(/"/g, '&quot;')}" extract="no" mode="view" maximize="yes" hidepreview="yes" displaydetail="yes"></sf-i-uploader>`
            }
            html += '</div>';
          }
          // html += '</div>';
        } else {
          html += '<div class="m-20">';
          html += '<div part="detail-head"><strong>' + cols[k] + '</strong></div>'
          html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + data[k].toString().replace(/\\n|\r?\n/g, '<br />') + '" minLength="80" lineSize="6"></sf-i-elastic-text>';
          html += '</div>';
        }

      }
      if (cols[k].toLowerCase() == "shortid") {

        shortId = (data[k]);

        if (Util.isJSONParsable(shortId)) {
          shortId = JSON.parse(shortId)[0]
        }

      }
    }

    console.log('shortid', shortId);
    html += '</div>';



    // html += '<div class="d-flex justify-end flex-wrap">'
    // html += '<div class="d-flex justify-end w-100 mb-10">'
    // html += '<textarea part="input" id="feedback-message" class="w-100 mt-10 mb-10 hide" placeholder="Type your feedback message here..."></textarea>'
    // html += '</div>'
    // html += '<div class="d-flex justify-end w-100">'
    // html += ('<button part="button-lg-short" id="button-feedback" class="d-flex justify-center align-center"><span class="material-symbols-outlined">comment</span><span>&nbsp;&nbsp;Send Feedback</span></button>');
    // html += ('<button part="button-lg-short-secondary" id="button-feedback-cancel" class="hide d-flex justify-center align-center mr-10"><span class="material-symbols-outlined">close</span><span>&nbsp;&nbsp;Cancel</span></button>');
    // html += ('<button part="button-lg-short" id="button-feedback-confirm" class="hide d-flex justify-center align-center"><span class="material-symbols-outlined">commentcheck</span><span>&nbsp;&nbsp;Submit Feedback</span></button>');
    // html += '</div>'
    // html += '</div>'

    html += '</div>';

    html += '</div>';

    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';
    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    let radios = ((this._SfDetailContainer as HTMLDivElement).querySelectorAll("input[type=radio]") as NodeListOf<HTMLInputElement>)
    for (let radio of radios) {
      if (understood >= 2 && parseInt(radio.value) == 1) {
        radio.checked = true;
      } else if (understood >= 4 && parseInt(radio.value) == 3) {
        radio.checked = true;
      } else if (understood === parseInt(radio.value)) {
        radio.checked = true;
      }

      radio.addEventListener('change', async () => {
        let understood = parseInt(radio.value) ?? -1;
        let radioContainerDiv1 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-1') as HTMLDivElement
        if (understood >= 1) {
          if (radioContainerDiv1 != null) {
            radioContainerDiv1.classList.remove('hide')
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-2') as HTMLInputElement).checked && understood < 3) {
            understood = 2
          } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-3') as HTMLInputElement).checked && understood < 3) {
            understood = 3
          }
        } else {
          if (radioContainerDiv1 != null) {
            radioContainerDiv1.classList.add('hide')
          }
        }
        let radioContainerDiv2 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-2') as HTMLDivElement
        if (understood >= 3) {
          if (radioContainerDiv2 != null) {
            radioContainerDiv2.classList.remove('hide')
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-4') as HTMLInputElement).checked) {
            understood = 4
          } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-5') as HTMLInputElement).checked) {
            understood = 5
          }
        } else {
          if (radioContainerDiv2 != null) {
            radioContainerDiv2.classList.add('hide')
          }
        }

        if (understood != 1 && understood != 3) {
          let resultMarkUnderstood = await this.markUnderstood(compliance.id, this.userProfileId, understood);
          console.log('mark understood result', resultMarkUnderstood, selectedCountry, selectedStatute, this.registerEvents)
          if (resultMarkUnderstood.result) {
            this.registerEvents[selectedCountry][selectedStatute][compliance.id].understood = understood;
            this.renderRegisterEvents(this.registerEvents);
          }
        }
        // const buttonSaveUnderstood = (this._SfDetailContainer as HTMLDivElement).querySelector('#button-save-understood') as HTMLButtonElement
        // if (buttonSaveUnderstood != null) {
        //   console.log('understood', understood)
        //   if (understood != 1 && understood != 3) {
        //     buttonSaveUnderstood.classList.remove('hide')
        //   } else {
        //     buttonSaveUnderstood.classList.add('hide')
        //   }
        // }
      })
    };

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-save-understood')?.addEventListener('click', async () => {
      let understood = -1;
      if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-0') as HTMLInputElement).checked) {
        understood = 0
      } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-1') as HTMLInputElement).checked) {
        understood = 1
      }
      let radioContainerDiv1 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-1') as HTMLDivElement
      if (!radioContainerDiv1.classList.contains('hide')) {
        if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-2') as HTMLInputElement).checked) {
          understood = 2
        } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-3') as HTMLInputElement).checked) {
          understood = 3
        }
      }
      let radioContainerDiv2 = (this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-container-2') as HTMLDivElement
      if (!radioContainerDiv2.classList.contains('hide')) {
        if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-4') as HTMLInputElement).checked) {
          understood = 4
        } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#understood-radio-5') as HTMLInputElement).checked) {
          understood = 5
        }
      }
      console.log('understood save', understood);
      let resultMarkUnderstood = await this.markUnderstood(compliance.id, this.userProfileId, understood);
      console.log('mark understood result', resultMarkUnderstood, selectedCountry, selectedStatute, this.registerEvents)
      if (resultMarkUnderstood.result) {
        this.registerEvents[selectedCountry][selectedStatute][compliance.id].understood = understood,
          this.renderRegisterEvents(this.registerEvents);
        const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement);
        buttonClose.click()
      }
    });


    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback')?.addEventListener('click', () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);

      console.log(buttonConfirm.classList);

      if (feedbackMessage.classList.contains('hide')) {
        feedbackMessage.classList.remove('hide');
      }

      if (buttonConfirm.classList.contains('hide')) {
        buttonConfirm.classList.remove('hide');
      }

      if (buttonCancel.classList.contains('hide')) {
        buttonCancel.classList.remove('hide');
      }

      if (!buttonFeedback.classList.contains('hide')) {
        buttonFeedback.classList.add('hide');
      }

      // const body = {
      //   projectid: this.projectId,
      //   complianceid: compliance.id
      // }
      // console.log(body);

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel')?.addEventListener('click', () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);

      console.log(buttonConfirm.classList);

      if (!feedbackMessage.classList.contains('hide')) {
        feedbackMessage.classList.add('hide');
      }

      if (!buttonConfirm.classList.contains('hide')) {
        buttonConfirm.classList.add('hide');
      }

      if (!buttonCancel.classList.contains('hide')) {
        buttonCancel.classList.add('hide');
      }

      if (buttonFeedback.classList.contains('hide')) {
        buttonFeedback.classList.remove('hide');
      }

    });

    // ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement).addEventListener('change', (e) => {

    // });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm')?.addEventListener('click', async () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement);

      if (feedbackMessage.value.length === 0) {
        feedbackMessage.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important');
      } else {
        feedbackMessage.setAttribute('style', 'border:');
        const cols = JSON.parse(compliance.cols) as Array<string>;
        const data = JSON.parse(compliance.data)
        console.log(compliance, cols, data);
        this.uploadTriggerMyEvent(
          compliance.id + " - " + shortId,
          feedbackMessage.value,
          compliance.countries.join(",").replace(/ *\([^)]*\) */g, ""),
          compliance.entities.join(',').replace(/ *\([^)]*\) */g, ""),
          compliance.locations.join(',').replace(/ *\([^)]*\) */g, ""),
          data[cols.indexOf('statute')][0],
          data[cols.indexOf('subcategory')][0],
          {
            obligationtitle: data[cols.indexOf('obligationtitle')],
            obligation: data[cols.indexOf('obligation')],
            reference: data[cols.indexOf('reference')]
          }
        );
        buttonCancel.click();
        buttonClose.click();
      }

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message')?.addEventListener('keyup', (e: any) => {
      let feedbackMessage = e.currentTarget as HTMLInputElement
      if (feedbackMessage != null && feedbackMessage.value != null && feedbackMessage.value.length !== 0 && ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement) != null) {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement).disabled = false
      } else if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement) != null) {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement).disabled = true
      }
      if (e.code == "Enter") {

        const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);
        buttonConfirm.click();

      }

    })

  }
  fetchNoticeDetails = async (listEvent: any) => {
    console.log('listEvent', listEvent, listEvent.id)
    let url = "https://" + this.apiIdNotices + "/details";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "noticeid": listEvent.id };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose notice details', jsonRespose);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  renderNoticeDetails = async (listEvent: any, mmddyyyy: string) => {
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let comments = listEvent['comments'];
    let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']);
    let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved'];
    let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'];
    let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; let html: string = '';
    let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0];
    html += `
        <div part="compliance-detail-title" class="d-flex justify-between">
          <button part="button-icon" class="material-icons invisible">close</button>
          <h3 part="results-title" class="m-0">Notice Details</h3>
          <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
        </div>
      `
    html += `
        <div class="box-large" id="shimmer-container-notices" part="shimmer-container-notices">
        </div>
    `
    html += '<sf-i-reporting id="detail-reporting" class="hide" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container, checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:repoortiinig-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:repoortiinig-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected, " name="Notice Details" apiiduploader="1peg5170d3" apiid="' + this.apiIdNotices + '" mode="admin" flow="details" projectid="' + this.projectId + '" projectname="' + this.projectName + '" editdisable="true" formviewclass="flex-wrap"></sf-i-reporting>';
    if (this.mode != "viewer") {
      html += '<div part="reporting-view-container" class="m-20">'
      html += this.renderReporting(listEvent, mmddyyyy);
      html += "</div>"
    }

    html += '<div class="d-flex justify-between m-20">';
    html += '<h3 part="results-title" class="m-0"><br />Comments</h3>';
    html += '</div>';

    html += '<div class="m-20">';

    html += '<div class="d-flex flex-col">';

    for (var i = 0; i < comments.length; i++) {
      html += '<div part="commentbox" class="d-flex commentbox ' + (comments[i].author + "").toLowerCase() + 'box">';
      html += '<div class="mr-20 d-flex flex-col align-end"><span part="comment-username">' + (comments[i].username != null ? comments[i].username : '') + '</span><span part="td-head">' + comments[i].author + '</span>' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '<br /><button class="mt-5 button-delete" part="button">Delete</button>' : '') + '</div>';

      const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim();
      try {

        const jsonComments = JSON.parse(onlyCommentText);

        if (Util.isInteger(jsonComments)) {
          html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        } else {
          //console.log('json comments', jsonComments);
          var htmlTable = '';
          for (var j = 0; j < Object.keys(jsonComments).length; j++) {
            htmlTable += '<div class="mb-20">';
            htmlTable += ('<div part="detail-head">' + Object.keys(jsonComments)[j] + '</div>');
            htmlTable += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonComments[Object.keys(jsonComments)[j]] + '" minLength="20"></sf-i-elastic-text>');
            htmlTable += '</div>';
          }
          html += '<div class="">' + htmlTable + '<small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        }

      } catch (e: any) {
        //console.log('json comments exception', comments[i]);
        html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
      }

      html += '</div>';
    }
    if (comments.length === 0) {
      html += '<div><strong>No comments yet!</strong></div>';
    }

    html += '</div>';

    html += '</div>';

    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;
    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

    let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting
    sfireporting.selectedItem = listEvent;
    sfireporting.loadMode();

    sfireporting.addEventListener('valueChanged', () => {
      sfireporting.classList.remove('hide');
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-notices') as HTMLDivElement).classList.add('hide');
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => {

      // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId);
      // this.setSuccess('Deleted successfully!')
      // setTimeout(() => {
      //   this.clearMessages()
      // }, 3000);
      // //console.log('deleted', resultDelete);
      // if(this.getCurrentTab() == this.TAB_CUSTOM) {
      //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      // } else {
      //   if(currentColumnButton != null) {
      //     currentColumnButton.click();
      //   }
      // }

      console.log('delete review clicked')

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });
    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length === 0) {
        // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], "Auto approved", true);
        // this.setSuccess('Auto-Approved successfully!')
        // setTimeout(() => {
        //   this.clearMessages()
        // }, 3000);
        console.log('audto approve single')
      } else {
        // let bulkBodyReview = []
        // for(var k = 0; k < this.selectedItemIds.length; k++) {

        //   const selectedId = this.selectedItemIds[k];
        //   //console.log('selectedid', selectedId);
        //   entityId = selectedId.split('-')[7].replace(/_/g, '-');
        //   locationId = selectedId.split('-')[8].replace(/_/g, '-');
        //   const eventId = selectedId.split('-')[9].replace(/_/g, '-');
        //   mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

        //   //console.log(entityId, locationId, eventId, mmddyyyy);
        //   bulkBodyReview.push({ 
        //     "mmddyyyy": mmddyyyy,
        //     "projectid": this.projectId, 
        //     "type": "review",
        //     "eventid": eventId,
        //     "comments": "Auto approved",
        //     "approved": true,
        //     "entityid": entityId,
        //     "locationid": locationId,
        //     "username": this.userName,
        //     "userid": this.userProfileId,
        //     "userrole": this.myRole,
        //     "year": this.calendarStartYYYY
        //   })
        // }
        // await this.uploadReviewsBulk(bulkBodyReview);
        console.log('auto approve bulk')
      }
      //console.log('deleted', resultDelete);
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });

    if (this.mode == "consumer" || this.mode == "next") {

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        var clickEvent = new MouseEvent("click", {
          "view": window,
          "bubbles": true,
          "cancelable": false
        });
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

        // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved)
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('mmddyyyy', mmddyyyy)
          if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                this.events[mmdd][p].lastupdated = new Date().toString()
              }
            }
            if (this.recentlyReported[mmdd] == null) {
              this.recentlyReported[mmdd] = []
            }
            this.recentlyReported[mmdd].push(listEvent)
            console.log('review single')
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityId,
              "locationid": locationId,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": listEvent.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                this.events[mmdd][p].isbulk = true
                flagBulk = true;
                if (this.recentlyReported[mmdd] == null) {
                  this.recentlyReported[mmdd] = []
                }
                this.recentlyReported[mmdd].push(this.events[mmdd][p])
              }
            }
          }
          console.log('review bulk')
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          this.renderRoleTabsNext(this.nextPage)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
            var clickEvent = new MouseEvent("click", {
              "view": window,
              "bubbles": true,
              "cancelable": false
            });
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

            // if(currentColumnButton != null) {
            //   currentColumnButton.click();
            // }
          }
        }

      });

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {

            if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(listEvent)
            }
            console.log('uploadaudit single')
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              entityId = selectedId.split('-')[7].replace(/_/g, '-');
              locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": listEvent.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true;
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }

            console.log('uploadAudit bulk')

          }

          var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
          });
          ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
          if (this.mode == "next") {
            this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {

        if (approved) {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }


        } else {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              const reporterdoc = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);
              let percentage: string = "100";
              if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }
              // if(docsOptional.length === 0) {
              docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }
              let flag = false;
              do {
                if (docs.length > 0 && docsOptional != null && docsOptional.length === 0 && parseInt(percentage) > 0) {
                  for (let doc of docs) {
                    if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) {
                      flag = false
                    } else {
                      flag = true;
                    }
                  }
                } else {
                  flag = true;
                }
                if (flag === false) {
                  await this.sleep(1000);
                  console.log('waiting for docs', docs);
                  docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
                }
              } while (flag === false);
              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (this._SfReporting[0] != null) {
                reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? "";
                reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? "";
              }


              if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) {

                //console.log('reporter comments 3', reportercomments);
                buttonClick.innerHTML = "Save"
                this.setError('Invalid Percentage!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {
                if (docs.length === 0 && docsOptional.length === 0) {

                  //console.log('reporter comments 3', reportercomments);
                  buttonClick.innerHTML = "Save"
                  this.setError('No documents uploaded!');
                  setTimeout(() => {
                    this.clearMessages();
                  }, 3000);

                } else {

                  //console.log('reporterdoc', reporterdoc);

                  if (reporterdoc.length === 0) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion not selected!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else if ((new Date(mmddyyyy).getTime() - (this.reportingLimitDays * 24 * 60 * 60 * 1000)) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError(`Reporting allowed only within ${this.reportingLimitDays} days before due date`);
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);
                  } else if ((new Date(mmddyyyy).getTime() - (this.reportingLimitDays * 24 * 60 * 60 * 1000)) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Notice cannot be reported more than ' + this.reportingLimitDays + ' days before due date!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);
                  } else if (parseInt(reporterdoc) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion cannot be in future!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else {

                    //console.log('makerscheckers 1', reportercomments);

                    if (reportercomments.trim().length === 0) {
                      buttonClick.innerHTML = "Save"
                      this.setError('Comments cannot be blank!');
                      setTimeout(() => {
                        this.clearMessages();
                      }, 3000);

                    } else {


                      var clickEvent = new MouseEvent("click", {
                        "view": window,
                        "bubbles": true,
                        "cancelable": false
                      });

                      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
                      let flagBulk = false;
                      if (this.selectedItemIds.length <= 1) {

                        if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) {
                          console.log('this.events', this.events);
                          for (var p = 0; p < this.events[mmdd].length; p++) {
                            if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                              this.events[mmdd][p].documents = docs
                              this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                              this.events[mmdd][p].lastupdated = new Date().toString()
                            }
                          }
                          console.log('uploadReport single')
                          if (makercheckers.length > 0) {

                            // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices");
                            for (var p = 0; p < this.events[mmdd].length; p++) {
                              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                                this.events[mmdd][p].approved = true
                                // this.events[mmdd][p].documents = docs
                                this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                                this.events[mmdd][p].lastupdated = new Date().toString()
                              }
                            }
                            console.log('upload report auto approve single')
                          }
                          if (this.recentlyReported[mmdd] == null) {
                            this.recentlyReported[mmdd] = []
                          }
                          this.recentlyReported[mmdd].push(listEvent)
                        }
                      } else {
                        let bulkBody = []
                        let bulkBodyReview = []
                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);

                          const makercheckersL = selectedId.split('-')[5];
                          entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                          //console.log(entityId, locationId, eventId, mmddyyyy);

                          // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null)
                          // if(parseInt(makercheckersL) > 0) {
                          //   bulkBodyReview.push({ 
                          //     "mmddyyyy": mmddyyyy,
                          //     "projectid": this.projectId, 
                          //     "type": "report",
                          //     "eventid": eventId,
                          //     "comments": reportercomments,
                          //     "dateofcompletion": reporterdoc,
                          //     "percentage": percentage,
                          //     "entityid": entityId,
                          //     "locationid": locationId,
                          //     "event": null,
                          //     "docs": JSON.stringify(docs),
                          //     "approved": true,
                          //     "username": this.userName,
                          //     "reportformatvalues": reportformatvalues,
                          //     "reportformatschema": reportformatschema,
                          //     "userid": this.userProfileId,
                          //     "userrole": this.myRole,
                          //     "year": this.calendarStartYYYY,
                          //     "module": listEvent.module ?? "compliance"
                          //   } )
                          //   // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true);

                          // }else{
                          let yearStr = this.getFinancialYear(mmddyyyy)
                          bulkBody.push({
                            "mmddyyyy": mmddyyyy,
                            "projectid": this.projectId,
                            "type": "report",
                            "eventid": eventId,
                            "comments": reportercomments,
                            "dateofcompletion": reporterdoc,
                            "percentage": percentage,
                            "entityid": entityId,
                            "locationid": locationId,
                            "event": null,
                            "docs": JSON.stringify(docs),
                            "username": this.userName,
                            "reportformatvalues": reportformatvalues,
                            "reportformatschema": reportformatschema,
                            "userid": this.userProfileId,
                            "userrole": this.myRole,
                            "year": yearStr,
                            "module": listEvent.module ?? "compliance",
                            "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                          })
                          // }

                          // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
                          // await this.sleep(2000);
                          // this.clearMessages();

                        }

                        // await this.uploadReportsBulk(bulkBody);
                        // await this.fetchBulkReportingData();
                        if (bulkBody.length > 0) {
                          await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                        }

                        // if(bulkBodyReview.length > 0){
                        //   await this.uploadReportsReviewsBulk(bulkBodyReview)
                        // }
                        await this.fetchBulkReportingData();
                        console.log('uploadReport bulk')
                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);
                          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                          let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                          for (var p = 0; p < this.events[mmdd].length; p++) {
                            if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                              this.events[mmdd][p].isbulk = true
                              flagBulk = true;
                              if (this.recentlyReported[mmdd] == null) {
                                this.recentlyReported[mmdd] = []
                              }
                              this.recentlyReported[mmdd].push(this.events[mmdd][p])
                            }
                          }
                        }

                      }

                      if (this.mode == "next") {
                        this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                      } else {
                        // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                        //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                        // } else 
                        if (this.getCurrentTab() == this.TAB_FIND) {
                          const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                          this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                        } else {
                          if (this.selectedItemIds.length > 0) {
                            await this.fetchBulkReportingData();
                          }
                          this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                          // if(currentColumnButton != null) {
                          //   currentColumnButton.click();
                          // }
                        }
                      }

                    }


                  }
                }
              }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        });


        //console.log('documentType checking', documentType);

        if (documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType;
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: listEvent.entityid,
          locationId: listEvent.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: listEvent['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (listEvent["approved"] != null) {
          if (listEvent["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }

        }
      }

    }
  }
  fetchContractDetails = async (listEvent: any, mmddyyyy: string) => {
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let url = "https://" + this.apiIdAgreements + "/getallobjectdetails";

    //console.log('fetch calendar url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement details', jsonRespose);
      this.renderContractDetails(jsonRespose.object, mmddyyyy)
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  renewContract = async (listEvent: any, reportformatvalues: any) => {

    let url = "https://" + this.apiIdAgreements + "/reopen";

    console.log('renewing', reportformatvalues)
    //console.log('fetch calendar url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) };
    // console.log('reopen body', url, urlBody)
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement reopen', jsonRespose);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }
  renderContractDetails = async (listEvent: any, mmddyyyy: string) => {
    // await this.fetchAgreementDetails(listEvent, mmddyyyy);
    // return;
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let comments = listEvent['comments'];
    let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']);
    let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved'];
    let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'];
    // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; 
    let html: string = '';
    let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0];
    html += `
        <div part="compliance-detail-title" class="d-flex justify-between">
          <button part="button-icon" class="material-icons invisible">close</button>
          <h3 part="results-title" class="m-0">Agreement Details</h3>
          <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
        </div>
      `
    html += `
        <div class="box-large" id="shimmer-container-agreements" part="shimmer-container-agreements">
        </div>
    `
    html += '<sf-i-reporting id="detail-reporting" class="hide" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container,checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected" name="Contract Details" apiiduploader="1peg5170d3" apiid="' + this.apiIdAgreements + '" mode="admin" flow="details" projectid="' + this.projectId + '" projectname="' + this.projectName + '" editdisable="true" formviewclass="flex-wrap"></sf-i-reporting>';
    if (this.mode != "viewer") {
      html += '<div part="reporting-view-container" class="m-20">'

      html += this.renderReporting(listEvent, mmddyyyy);
      html += "</div>"
    }

    html += '<div class="d-flex justify-between m-20">';
    html += '<h3 part="results-title" class="m-0"><br />Comments</h3>';
    html += '</div>';

    html += '<div class="m-20">';

    html += '<div class="d-flex flex-col">';

    for (var i = 0; i < comments.length; i++) {
      html += '<div part="commentbox" class="d-flex commentbox ' + (comments[i].author + "").toLowerCase() + 'box">';
      html += '<div class="mr-20 d-flex flex-col align-end"><span part="comment-username">' + (comments[i].username != null ? comments[i].username : '') + '</span><span part="td-head">' + comments[i].author + '</span>' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '<br /><button class="mt-5 button-delete" part="button">Delete</button>' : '') + '</div>';

      const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim();
      try {

        const jsonComments = JSON.parse(onlyCommentText);

        if (Util.isInteger(jsonComments)) {
          html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        } else {
          //console.log('json comments', jsonComments);
          var htmlTable = '';
          for (var j = 0; j < Object.keys(jsonComments).length; j++) {
            htmlTable += '<div class="mb-20">';
            htmlTable += ('<div part="detail-head">' + Object.keys(jsonComments)[j] + '</div>');
            htmlTable += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonComments[Object.keys(jsonComments)[j]] + '" minLength="20"></sf-i-elastic-text>');
            htmlTable += '</div>';
          }
          html += '<div class="">' + htmlTable + '<small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        }

      } catch (e: any) {
        //console.log('json comments exception', comments[i]);
        html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
      }

      html += '</div>';
    }
    if (comments.length === 0) {
      html += '<div><strong>No comments yet!</strong></div>';
    }

    html += '</div>';

    html += '</div>';
    console.log('selected event', JSON.stringify(listEvent));
    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;
    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

    let usermap = Util.getUsermap();

    let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting
    sfireporting.usermap = JSON.stringify(usermap);
    sfireporting.selectedItem = listEvent;
    sfireporting.editdisable = "true"
    setTimeout(() => {
      console.log('sfireporting', sfireporting._SfReportingContainer);
      sfireporting.loadMode();
    }, 500);

    sfireporting.addEventListener('valueChanged', () => {
      sfireporting.classList.remove('hide');
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide');
    });
    let reportingSchemaJson = "";
    let reportingSchemaValues = ""
    if (listEvent.reportformatschema != null) {
      reportingSchemaJson = listEvent.reportformatschema
      reportingSchemaValues = listEvent.reportformatvalues
    } else if (listEvent.customreporting != null) {
      reportingSchemaJson = listEvent.customreporting
    }
    if (listEvent.customreporting != null || listEvent.reportformatschema != null) {
      let reportingHtml = '<sf-i-reporting class="reporting-reporting" id="reporting-reporting-[INDEX]" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container,checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected" mode="edit" flow="reporting" name="Contract Reporting" formviewclass="flex-wrap" showterminate="true" projectid="' + this.projectId + '"></sf-i-reporting>'

      let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf<HTMLDivElement>;
      for (let [indexContainer, reportFormatContainer] of Array.from(reportFormatContainers).entries()) {
        if (reportFormatContainer != null) {
          reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer.toString());
        }
      }

    }
    let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf<SfIReporting>
    for (let reportingReporting of reportingReportings) {
      if (reportingSchemaJson != "" && reportingReporting != null) {
        reportingReporting.configjson = reportingSchemaJson;
        if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues
        reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view"
        reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true"
        reportingReporting.flow = "reporting"
        setTimeout(() => {
          reportingReporting.loadMode();
          console.log('list-customreporting', reportingSchemaJson);
          console.log('list-customreporting1', reportingSchemaValues);
          console.log('list-customreporting2', reportingReporting.mode);
        }, 500)
      }
    }

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => {

      // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId);
      // this.setSuccess('Deleted successfully!')
      // setTimeout(() => {
      //   this.clearMessages()
      // }, 3000);
      // //console.log('deleted', resultDelete);
      // if(this.getCurrentTab() == this.TAB_CUSTOM) {
      //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      // } else {
      //   if(currentColumnButton != null) {
      //     currentColumnButton.click();
      //   }
      // }

      console.log('delete review clicked')

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });
    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length === 0) {
        console.log('audto approve single')
      } else {
        console.log('auto approve bulk')
      }
      //console.log('deleted', resultDelete);
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });

    if (this.mode == "consumer" || this.mode == "next") {

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        let reportformatvalues = ""
        let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
        console.log('renew reporting', reportingReporting)
        if (reportingReporting != null) {
          reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? "";
        }
        var clickEvent = new MouseEvent("click", {
          "view": window,
          "bubbles": true,
          "cancelable": false
        });
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

        // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved)
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('mmddyyyy', mmddyyyy)
          if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
            if (approved) {
              await this.renewContract(listEvent, reportformatvalues);
            } else {
              console.log('renew reporting', reportformatvalues)
            }
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                this.events[mmdd][p].approved = approved
                this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false
                this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                this.events[mmdd][p].lastupdated = new Date().toString()
              }
            }
            if (this.recentlyReported[mmdd] == null) {
              this.recentlyReported[mmdd] = []
            }
            this.recentlyReported[mmdd].push(listEvent)
            console.log('review single')
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityId,
              "locationid": locationId,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": listEvent.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                this.events[mmdd][p].isbulk = true
                flagBulk = true;
                if (this.recentlyReported[mmdd] == null) {
                  this.recentlyReported[mmdd] = []
                }
                this.recentlyReported[mmdd].push(this.events[mmdd][p])
              }
            }
          }
          console.log('review bulk')
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          this.renderRoleTabsNext(this.nextPage)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
            var clickEvent = new MouseEvent("click", {
              "view": window,
              "bubbles": true,
              "cancelable": false
            });
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent);

            // if(currentColumnButton != null) {
            //   currentColumnButton.click();
            // }
          }
        }

      });

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {

            if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(listEvent)
            }
            console.log('uploadaudit single')
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              entityId = selectedId.split('-')[7].replace(/_/g, '-');
              locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": listEvent.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true;
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }

            console.log('uploadAudit bulk')

          }

          var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
          });
          ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
          if (this.mode == "next") {
            this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {

        if (approved) {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }


        } else {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              const reporterdoc = new Date().getTime() + "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);

              // if(docsOptional.length === 0) {
              // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }

              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (listEvent.customreporting != null) {
                let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting
                if (reportingReporting == null) {
                  reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
                }
                console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues()))
                reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? "";
                reportformatschema = reportingReporting!.configjson ?? "";
              }

              let percentage: string = "100";
              if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }
              // if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) {

              //   //console.log('reporter comments 3', reportercomments);
              //   buttonClick.innerHTML = "Save"
              //   this.setError('Invalid Percentage!');
              //   setTimeout(() => {
              //     this.clearMessages();
              //   }, 3000);

              // } else {
              //   if (docs.length === 0 && docsOptional.length === 0) {

              //     //console.log('reporter comments 3', reportercomments);
              //     buttonClick.innerHTML = "Save"
              //     this.setError('No documents uploaded!');
              //     setTimeout(() => {
              //       this.clearMessages();
              //     }, 3000);

              //   } else {

              //     //console.log('reporterdoc', reporterdoc);

              //     if (reporterdoc.length === 0) {
              //       buttonClick.innerHTML = "Save"
              //       this.setError('Date of completion not selected!');
              //       setTimeout(() => {
              //         this.clearMessages();
              //       }, 3000);

              //     } else if (parseInt(reporterdoc) > new Date().getTime()) {
              //       buttonClick.innerHTML = "Save"
              //       this.setError('Date of completion cannot be in future!');
              //       setTimeout(() => {
              //         this.clearMessages();
              //       }, 3000);

              //     } else {

              //console.log('makerscheckers 1', reportercomments);

              if (reportercomments.trim().length === 0) {
                buttonClick.innerHTML = "Save"
                this.setError('Comments cannot be blank!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {


                var clickEvent = new MouseEvent("click", {
                  "view": window,
                  "bubbles": true,
                  "cancelable": false
                });

                ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
                let flagBulk = false;
                if (this.selectedItemIds.length <= 1) {

                  if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) {
                    console.log('this.events', this.events);
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                        this.events[mmdd][p].documents = docs
                        this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                        this.events[mmdd][p].lastupdated = new Date().toString()
                      }
                    }
                    console.log('uploadReport single')
                    if (makercheckers.length > 0) {

                      // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices");
                      for (var p = 0; p < this.events[mmdd].length; p++) {
                        if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                          this.events[mmdd][p].approved = true
                          this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false
                          // this.events[mmdd][p].documents = docs
                          this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                          this.events[mmdd][p].lastupdated = new Date().toString()
                        }
                      }
                      await this.renewContract(listEvent, reportformatvalues);
                      console.log('upload report auto approve single')
                    }
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(listEvent)
                  }
                } else {
                  let bulkBody = []
                  let bulkBodyReview = []
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);

                    const makercheckersL = selectedId.split('-')[5];
                    entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                    //console.log(entityId, locationId, eventId, mmddyyyy);

                    // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null)
                    // if(parseInt(makercheckersL) > 0) {
                    //   bulkBodyReview.push({ 
                    //     "mmddyyyy": mmddyyyy,
                    //     "projectid": this.projectId, 
                    //     "type": "report",
                    //     "eventid": eventId,
                    //     "comments": reportercomments,
                    //     "dateofcompletion": reporterdoc,
                    //     "percentage": percentage,
                    //     "entityid": entityId,
                    //     "locationid": locationId,
                    //     "event": null,
                    //     "docs": JSON.stringify(docs),
                    //     "approved": true,
                    //     "username": this.userName,
                    //     "reportformatvalues": reportformatvalues,
                    //     "reportformatschema": reportformatschema,
                    //     "userid": this.userProfileId,
                    //     "userrole": this.myRole,
                    //     "year": this.calendarStartYYYY,
                    //     "module": listEvent.module ?? "compliance"
                    //   } )
                    //   // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true);

                    // }else{
                    let yearStr = this.getFinancialYear(mmddyyyy)
                    bulkBody.push({
                      "mmddyyyy": mmddyyyy,
                      "projectid": this.projectId,
                      "type": "report",
                      "eventid": eventId,
                      "comments": reportercomments,
                      "dateofcompletion": reporterdoc,
                      "percentage": percentage,
                      "entityid": entityId,
                      "locationid": locationId,
                      "event": null,
                      "docs": JSON.stringify(docs),
                      "username": this.userName,
                      "reportformatvalues": reportformatvalues,
                      "reportformatschema": reportformatschema,
                      "userid": this.userProfileId,
                      "userrole": this.myRole,
                      "year": yearStr,
                      "module": listEvent.module ?? "compliance",
                      "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                    })
                    // }

                    // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
                    // await this.sleep(2000);
                    // this.clearMessages();

                  }

                  // await this.uploadReportsBulk(bulkBody);
                  // await this.fetchBulkReportingData();
                  if (bulkBody.length > 0) {
                    await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                  }

                  // if(bulkBodyReview.length > 0){
                  //   await this.uploadReportsReviewsBulk(bulkBodyReview)
                  // }
                  await this.fetchBulkReportingData();
                  console.log('uploadReport bulk')
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);
                    let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                        this.events[mmdd][p].isbulk = true
                        flagBulk = true;
                        if (this.recentlyReported[mmdd] == null) {
                          this.recentlyReported[mmdd] = []
                        }
                        this.recentlyReported[mmdd].push(this.events[mmdd][p])
                      }
                    }
                  }

                }

                if (this.mode == "next") {
                  this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                } else {
                  // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                  //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                  // } else 
                  if (this.getCurrentTab() == this.TAB_FIND) {
                    const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                    this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                  } else {
                    if (this.selectedItemIds.length > 0) {
                      await this.fetchBulkReportingData();
                    }
                    this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                    // if(currentColumnButton != null) {
                    //   currentColumnButton.click();
                    // }
                  }
                }

              }


              //     }
              //   }
              // }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        });


        //console.log('documentType checking', documentType);

        if (documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType;
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: listEvent.entityid,
          locationId: listEvent.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: listEvent['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (listEvent["approved"] != null) {
          if (listEvent["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }

        }
      }

    }
  }

  fetchLicenseDetails = async (listEvent: any, mmddyyyy: string) => {
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let url = "https://" + this.apiIdLicenses + "/getallobjectdetails";

    console.log('fetch license details url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy };

    console.log('fetch license details urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement details', jsonRespose);
      this.renderLicenseDetails(jsonRespose.object, mmddyyyy)
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  renewLicense = async (listEvent: any, reportformatvalues: any) => {

    let url = "https://" + this.apiIdLicenses + "/reopen";

    console.log('renewing', reportformatvalues)
    //console.log('fetch calendar url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) };
    // console.log('reopen body', url, urlBody)
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement reopen', jsonRespose);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }
  renderLicenseDetails = async (listEvent: any, mmddyyyy: string) => {
    // await this.fetchAgreementDetails(listEvent, mmddyyyy);
    // return;
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let comments = listEvent['comments'];
    let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']);
    let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved'];
    let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'];
    // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; 
    let html: string = '';
    let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0];
    html += `
        <div part="compliance-detail-title" class="d-flex justify-between">
          <button part="button-icon" class="material-icons invisible">close</button>
          <h3 part="results-title" class="m-0">License Details</h3>
          <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
        </div>
      `
    html += `
        <div class="box-large" id="shimmer-container-agreements" part="shimmer-container-agreements">
        </div>
    `
    html += '<sf-i-reporting id="detail-reporting" class="hide" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container,checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected" name="License Details" apiiduploader="1peg5170d3" apiid="' + this.apiIdLicenses + '" mode="admin" flow="details" projectid="' + this.projectId + '" projectname="' + this.projectName + '" editdisable="true" formviewclass="flex-wrap"></sf-i-reporting>';
    if (this.mode != "viewer") {
      html += '<div part="reporting-view-container" class="m-20">'

      html += this.renderReporting(listEvent, mmddyyyy);
      html += "</div>"
    }

    html += '<div class="d-flex justify-between m-20">';
    html += '<h3 part="results-title" class="m-0"><br />Comments</h3>';
    html += '</div>';

    html += '<div class="m-20">';

    html += '<div class="d-flex flex-col">';

    for (var i = 0; i < comments.length; i++) {
      html += '<div part="commentbox" class="d-flex commentbox ' + (comments[i].author + "").toLowerCase() + 'box">';
      html += '<div class="mr-20 d-flex flex-col align-end"><span part="comment-username">' + (comments[i].username != null ? comments[i].username : '') + '</span><span part="td-head">' + comments[i].author + '</span>' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '<br /><button class="mt-5 button-delete" part="button">Delete</button>' : '') + '</div>';

      const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim();
      try {

        const jsonComments = JSON.parse(onlyCommentText);

        if (Util.isInteger(jsonComments)) {
          html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        } else {
          //console.log('json comments', jsonComments);
          var htmlTable = '';
          for (var j = 0; j < Object.keys(jsonComments).length; j++) {
            htmlTable += '<div class="mb-20">';
            htmlTable += ('<div part="detail-head">' + Object.keys(jsonComments)[j] + '</div>');
            htmlTable += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonComments[Object.keys(jsonComments)[j]] + '" minLength="20"></sf-i-elastic-text>');
            htmlTable += '</div>';
          }
          html += '<div class="">' + htmlTable + '<small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        }

      } catch (e: any) {
        //console.log('json comments exception', comments[i]);
        html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
      }

      html += '</div>';
    }
    if (comments.length === 0) {
      html += '<div><strong>No comments yet!</strong></div>';
    }

    html += '</div>';

    html += '</div>';
    console.log('selected event', JSON.stringify(listEvent));
    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;
    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

    let usermap = Util.getUsermap();

    let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting
    sfireporting.usermap = JSON.stringify(usermap);
    sfireporting.selectedItem = listEvent;
    sfireporting.editdisable = "true"
    setTimeout(() => {
      console.log('sfireporting', sfireporting._SfReportingContainer);
      console.log('sfireporting', sfireporting.selectedItem);
      sfireporting.loadMode();
    }, 500);

    sfireporting.addEventListener('valueChanged', () => {
      sfireporting.classList.remove('hide');
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide');
    });
    let reportingSchemaJson = "";
    let reportingSchemaValues = ""
    if (listEvent.reportformatschema != null) {
      reportingSchemaJson = listEvent.reportformatschema
      reportingSchemaValues = listEvent.reportformatvalues
    } else if (listEvent.customreporting != null) {
      reportingSchemaJson = listEvent.customreporting
    }
    if (listEvent.customreporting != null || listEvent.reportformatschema != null) {
      let reportingHtml = '<sf-i-reporting class="reporting-reporting" id="reporting-reporting-[INDEX]" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container,checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, list-container:reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected" mode="edit" flow="reporting" name="License Reporting" formviewclass="flex-wrap" showterminate="true" projectid="' + this.projectId + '"></sf-i-reporting>'

      let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf<HTMLDivElement>;
      for (let [indexContainer, reportFormatContainer] of reportFormatContainers.entries()) {
        if (reportFormatContainer != null) {
          reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer + '');
        }
      }

    }
    let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf<SfIReporting>
    for (let reportingReporting of reportingReportings) {
      if (reportingSchemaJson != "" && reportingReporting != null) {
        reportingReporting.configjson = reportingSchemaJson;
        if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues
        reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view"
        reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true"
        reportingReporting.flow = "reporting"
        setTimeout(() => {
          reportingReporting.loadMode();
          console.log('list-customreporting', reportingSchemaJson);
          console.log('list-customreporting1', reportingSchemaValues);
          console.log('list-customreporting2', reportingReporting.mode);
        }, 500)
      }
    }

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => {

      // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId);
      // this.setSuccess('Deleted successfully!')
      // setTimeout(() => {
      //   this.clearMessages()
      // }, 3000);
      // //console.log('deleted', resultDelete);
      // if(this.getCurrentTab() == this.TAB_CUSTOM) {
      //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      // } else {
      //   if(currentColumnButton != null) {
      //     currentColumnButton.click();
      //   }
      // }

      console.log('delete review clicked')

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });
    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length === 0) {
        console.log('audto approve single')
      } else {
        console.log('auto approve bulk')
      }
      //console.log('deleted', resultDelete);
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });

    if (this.mode == "consumer" || this.mode == "next") {

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        let reportformatvalues = ""
        let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
        console.log('renew reporting', reportingReporting)
        if (reportingReporting != null) {
          reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? "";
        }
        var clickEvent = new MouseEvent("click", {
          "view": window,
          "bubbles": true,
          "cancelable": false
        });
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

        // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved)
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('mmddyyyy', mmddyyyy)
          if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
            if (approved) {
              await this.renewLicense(listEvent, reportformatvalues);
            } else {
              console.log('renew reporting', reportformatvalues)
            }
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                this.events[mmdd][p].approved = approved
                this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false
                this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                this.events[mmdd][p].lastupdated = new Date().toString()
              }
            }
            if (this.recentlyReported[mmdd] == null) {
              this.recentlyReported[mmdd] = []
            }
            this.recentlyReported[mmdd].push(listEvent)
            console.log('review single')
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityId,
              "locationid": locationId,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": listEvent.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                this.events[mmdd][p].isbulk = true
                flagBulk = true;
                if (this.recentlyReported[mmdd] == null) {
                  this.recentlyReported[mmdd] = []
                }
                this.recentlyReported[mmdd].push(this.events[mmdd][p])
              }
            }
          }
          console.log('review bulk')
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          this.renderRoleTabsNext(this.nextPage)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
            var clickEvent = new MouseEvent("click", {
              "view": window,
              "bubbles": true,
              "cancelable": false
            });
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent);

            // if(currentColumnButton != null) {
            //   currentColumnButton.click();
            // }
          }
        }

      });

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {

            if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(listEvent)
            }
            console.log('uploadaudit single')
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              entityId = selectedId.split('-')[7].replace(/_/g, '-');
              locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": listEvent.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true;
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }

            console.log('uploadAudit bulk')

          }

          var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
          });
          ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
          if (this.mode == "next") {
            this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {

        if (approved) {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }


        } else {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              const reporterdoc = new Date().getTime() + "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);

              // if(docsOptional.length === 0) {
              // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }

              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (listEvent.customreporting != null) {
                let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting
                if (reportingReporting == null) {
                  reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
                }
                console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues()))
                reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? "";
                reportformatschema = reportingReporting!.configjson ?? "";
              }

              let percentage: string = "100";
              if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }
              // if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) {

              //   //console.log('reporter comments 3', reportercomments);
              //   buttonClick.innerHTML = "Save"
              //   this.setError('Invalid Percentage!');
              //   setTimeout(() => {
              //     this.clearMessages();
              //   }, 3000);

              // } else {
              //   if (docs.length === 0 && docsOptional.length === 0) {

              //     //console.log('reporter comments 3', reportercomments);
              //     buttonClick.innerHTML = "Save"
              //     this.setError('No documents uploaded!');
              //     setTimeout(() => {
              //       this.clearMessages();
              //     }, 3000);

              //   } else {

              //     //console.log('reporterdoc', reporterdoc);

              //     if (reporterdoc.length === 0) {
              //       buttonClick.innerHTML = "Save"
              //       this.setError('Date of completion not selected!');
              //       setTimeout(() => {
              //         this.clearMessages();
              //       }, 3000);

              //     } else if (parseInt(reporterdoc) > new Date().getTime()) {
              //       buttonClick.innerHTML = "Save"
              //       this.setError('Date of completion cannot be in future!');
              //       setTimeout(() => {
              //         this.clearMessages();
              //       }, 3000);

              //     } else {

              //console.log('makerscheckers 1', reportercomments);

              if (reportercomments.trim().length === 0) {
                buttonClick.innerHTML = "Save"
                this.setError('Comments cannot be blank!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {


                var clickEvent = new MouseEvent("click", {
                  "view": window,
                  "bubbles": true,
                  "cancelable": false
                });

                ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
                let flagBulk = false;
                if (this.selectedItemIds.length <= 1) {

                  if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) {
                    console.log('this.events', this.events);
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                        this.events[mmdd][p].documents = docs
                        this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                        this.events[mmdd][p].lastupdated = new Date().toString()
                      }
                    }
                    console.log('uploadReport single')
                    if (makercheckers.length > 0) {

                      // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices");
                      for (var p = 0; p < this.events[mmdd].length; p++) {
                        if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                          this.events[mmdd][p].approved = true
                          this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false
                          // this.events[mmdd][p].documents = docs
                          this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                          this.events[mmdd][p].lastupdated = new Date().toString()
                        }
                      }
                      await this.renewLicense(listEvent, reportformatvalues);
                      console.log('upload report auto approve single')
                    }
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(listEvent)
                  }
                } else {
                  let bulkBody = []
                  let bulkBodyReview = []
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);

                    const makercheckersL = selectedId.split('-')[5];
                    entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                    //console.log(entityId, locationId, eventId, mmddyyyy);

                    // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null)
                    // if(parseInt(makercheckersL) > 0) {
                    //   bulkBodyReview.push({ 
                    //     "mmddyyyy": mmddyyyy,
                    //     "projectid": this.projectId, 
                    //     "type": "report",
                    //     "eventid": eventId,
                    //     "comments": reportercomments,
                    //     "dateofcompletion": reporterdoc,
                    //     "percentage": percentage,
                    //     "entityid": entityId,
                    //     "locationid": locationId,
                    //     "event": null,
                    //     "docs": JSON.stringify(docs),
                    //     "approved": true,
                    //     "username": this.userName,
                    //     "reportformatvalues": reportformatvalues,
                    //     "reportformatschema": reportformatschema,
                    //     "userid": this.userProfileId,
                    //     "userrole": this.myRole,
                    //     "year": this.calendarStartYYYY,
                    //     "module": listEvent.module ?? "compliance"
                    //   } )
                    //   // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true);

                    // }else{
                    let yearStr = this.getFinancialYear(mmddyyyy)
                    bulkBody.push({
                      "mmddyyyy": mmddyyyy,
                      "projectid": this.projectId,
                      "type": "report",
                      "eventid": eventId,
                      "comments": reportercomments,
                      "dateofcompletion": reporterdoc,
                      "percentage": percentage,
                      "entityid": entityId,
                      "locationid": locationId,
                      "event": null,
                      "docs": JSON.stringify(docs),
                      "username": this.userName,
                      "reportformatvalues": reportformatvalues,
                      "reportformatschema": reportformatschema,
                      "userid": this.userProfileId,
                      "userrole": this.myRole,
                      "year": yearStr,
                      "module": listEvent.module ?? "compliance",
                      "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                    })
                    // }

                    // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
                    // await this.sleep(2000);
                    // this.clearMessages();

                  }

                  // await this.uploadReportsBulk(bulkBody);
                  // await this.fetchBulkReportingData();
                  if (bulkBody.length > 0) {
                    await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                  }

                  // if(bulkBodyReview.length > 0){
                  //   await this.uploadReportsReviewsBulk(bulkBodyReview)
                  // }
                  await this.fetchBulkReportingData();
                  console.log('uploadReport bulk')
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);
                    let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                        this.events[mmdd][p].isbulk = true
                        flagBulk = true;
                        if (this.recentlyReported[mmdd] == null) {
                          this.recentlyReported[mmdd] = []
                        }
                        this.recentlyReported[mmdd].push(this.events[mmdd][p])
                      }
                    }
                  }

                }

                if (this.mode == "next") {
                  this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                } else {
                  // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                  //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                  // } else 
                  if (this.getCurrentTab() == this.TAB_FIND) {
                    const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                    this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                  } else {
                    if (this.selectedItemIds.length > 0) {
                      await this.fetchBulkReportingData();
                    }
                    this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                    // if(currentColumnButton != null) {
                    //   currentColumnButton.click();
                    // }
                  }
                }

              }


              //     }
              //   }
              // }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        });


        //console.log('documentType checking', documentType);

        if (documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType;
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: listEvent.entityid,
          locationId: listEvent.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: listEvent['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (listEvent["approved"] != null) {
          if (listEvent["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }

        }
      }

    }
  }

  fetchRCMResourceDetails = async (listEvent: any, mmddyyyy: string, flagReturn: boolean = false) => {
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let url = "https://" + this.apiIdRCMResources + "/getallobjectdetails";

    console.log('fetch rcm resource details url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, entityid: entityId, locationid: locationId, userprofileid: this.userProfileId, role: this.myRole, year: this.calendarStartYYYY, mmddyyyy: mmddyyyy };

    console.log('fetch rcm resource details urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement details', jsonRespose);
      if (flagReturn) {
        return jsonRespose.object;
      } else {
        this.renderRCMResourceDetails(jsonRespose.object, mmddyyyy)
      }
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  renewRCMResource = async (listEvent: any, reportformatvalues: any) => {

    let url = "https://" + this.apiIdRCMResources + "/reopen1";

    console.log('renewing', reportformatvalues)
    //console.log('fetch calendar url', url);
    let urlBody: any = { projectid: this.projectId, objectid: listEvent.id, newvalues: reportformatvalues == "" ? null : JSON.parse(reportformatvalues), published: true, terminated: (JSON.parse(reportformatvalues).terminated ?? false) };
    console.log('reopen body', url, urlBody)
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Renewing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose agreement reopen', jsonRespose);
      this.setSuccess("Renewal successful");
      setTimeout(() => {
        this.clearMessages()
      }, 3000)
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }
  renderRCMResourceDetails = async (listEvent: any, mmddyyyy: string) => {
    // await this.fetchAgreementDetails(listEvent, mmddyyyy);
    // return;
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
    let entityId = listEvent.entityid;
    let locationId = listEvent.locationid;
    let comments = listEvent['comments'];
    let docs = listEvent['documents'] == null ? [] : listEvent['documents'] == null ? [] : (listEvent['documents']);
    let approved = listEvent['approved'] == null ? false : listEvent['approved'] == null ? false : listEvent['approved'];
    let makercheckers = listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'] == null ? [] : listEvent['makercheckers'];
    // let docsOptional = listEvent['docs'] == null ? [] : listEvent['docs'] == null ? [] : listEvent['docs']; 
    let html: string = '';
    let documentType = listEvent['documenttype'] == null ? null : listEvent['documenttype'][0] == null ? null : listEvent['documenttype'][0].split(" ")[0];
    html += `
        <div part="compliance-detail-title" class="d-flex justify-between">
          <button part="button-icon" class="material-icons invisible">close</button>
          <h3 part="results-title" class="m-0">RCM Resource Details</h3>
          <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
        </div>
      `
    html += `
        <div class="box-large" id="shimmer-container-agreements" part="shimmer-container-agreements">
        </div>
    `
    html += '<sf-i-reporting id="detail-reporting" class="hide" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select, list-container:reporting-list-container,checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected, reporting-select-input-select:reporting-reporting-select-input-select, reporting-sub-select-input-select:reporting-reporting-sub-select-input-select" name="RCM Resource Details" apiiduploader="1peg5170d3" apiid="' + this.apiIdRCMResources + '" mode="admin" flow="details" projectid="' + this.projectId + '" projectname="' + this.projectName + '" editdisable="true" formviewclass="flex-wrap"></sf-i-reporting>';
    if (this.mode != "viewer") {
      html += '<div part="reporting-view-container" class="m-20">'

      html += this.renderReporting(listEvent, mmddyyyy);
      html += "</div>"
    }

    html += '<div class="d-flex justify-between m-20">';
    html += '<h3 part="results-title" class="m-0"><br />Comments</h3>';
    html += '</div>';

    html += '<div class="m-20">';

    html += '<div class="d-flex flex-col">';

    for (var i = 0; i < comments.length; i++) {
      html += '<div part="commentbox" class="d-flex commentbox ' + (comments[i].author + "").toLowerCase() + 'box">';
      html += '<div class="mr-20 d-flex flex-col align-end"><span part="comment-username">' + (comments[i].username != null ? comments[i].username : '') + '</span><span part="td-head">' + comments[i].author + '</span>' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '<br /><button class="mt-5 button-delete" part="button">Delete</button>' : '') + '</div>';

      const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim();
      try {

        const jsonComments = JSON.parse(onlyCommentText);

        if (Util.isInteger(jsonComments)) {
          html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        } else {
          //console.log('json comments', jsonComments);
          var htmlTable = '';
          for (var j = 0; j < Object.keys(jsonComments).length; j++) {
            htmlTable += '<div class="mb-20">';
            htmlTable += ('<div part="detail-head">' + Object.keys(jsonComments)[j] + '</div>');
            htmlTable += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonComments[Object.keys(jsonComments)[j]] + '" minLength="20"></sf-i-elastic-text>');
            htmlTable += '</div>';
          }
          html += '<div class="">' + htmlTable + '<small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        }

      } catch (e: any) {
        //console.log('json comments exception', comments[i]);
        html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
      }

      html += '</div>';
    }
    if (comments.length === 0) {
      html += '<div><strong>No comments yet!</strong></div>';
    }

    html += '</div>';

    html += '</div>';
    console.log('selected event', JSON.stringify(listEvent));
    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;
    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';

    let usermap = Util.getUsermap();

    let sfireporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#detail-reporting') as SfIReporting
    sfireporting.usermap = JSON.stringify(usermap);
    sfireporting.selectedItem = listEvent;
    sfireporting.editdisable = "true"
    setTimeout(() => {
      console.log('sfireporting', sfireporting._SfReportingContainer);
      console.log('sfireporting', sfireporting.selectedItem);
      sfireporting.loadMode();
    }, 500);

    sfireporting.addEventListener('valueChanged', () => {
      sfireporting.classList.remove('hide');
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#shimmer-container-agreements') as HTMLDivElement).classList.add('hide');
    });
    let reportingSchemaJson = "";
    let reportingSchemaValues = ""
    if (listEvent.reportformatschema != null && listEvent.reportformatschema != "") {
      reportingSchemaJson = listEvent.reportformatschema
      reportingSchemaValues = listEvent.reportformatvalues
    } else if (listEvent.customreporting != null) {
      reportingSchemaJson = listEvent.customreporting
    }
    // console.log('reporting schema', reportingSchemaJson)
    if (listEvent.customreporting != null || listEvent.reportformatschema != null) {
      let reportingHtml = '<sf-i-reporting class="reporting-reporting" id="reporting-reporting-[INDEX]" exportparts="uploader-extracted-text:reporting-uploader-extracted-text, uploader-sf-upload-message:reporting-uploader-sf-upload-message, uploader-sf-upload-submessage:reporting-uploader-sf-upload-submessage, uploader-extracted-text-chip:reporting-uploader-extracted-text-chip, uploader-extracted-text-chip-failed:reporting-uploader-extracted-text-chip-failed, uploader-doctype-verify-badge:reporting-uploader-doctype-verify-badge,span-submit-published:reporting-span-submit-published, span-submit-unpublished:reporting-span-submit-unpublished, reporting-container:reporting-reporting-container, button-icon:reporting-button-icon, uploader-button-icon:reporting-uploader-button-icon, sf-i-form-modal-container:reporting-sf-i-form-modal-container, next-calendar-date:reporting-next-calendar-date, last-calendar-date:reporting-last-calendar-date, input-publish-checkbox:reporting-input-publish-checkbox, button-icon-light:reporting-button-icon-light, button-icon-small:reporting-button-icon-small, uploader-input-label:reporting-uploader-input-label, input-radio:reporting-input-radio, radio-label:reporting-radio-label, input-textarea:reporting-input-textarea, input-textarea-disabled:reporting-input-textarea-disabled, input-date:reporting-input-date, input-date-disabled:reporting-input-date-disabled, input-select-single:reporting-input-select-single, textarea-container:reporting-textarea-container, section-body:reporting-section-body, section-container:reporting-section-container, subsection-container:reporting-subsection-container, date-container:reporting-date-container, input-sf-i-uploader:reporting-input-sf-i-uploader, published-container:reporting-published-container, selected-option:reporting-selected-option, input-select-multi-option:reporting-input-select-multi-option, select-option-label:reporting-select-option-label, input-sf-i-form:reporting-input-sf-i-form, input-sf-i-bricks:reporting-input-sf-i-bricks, uploader-input:reporting-uploader-input, form-container:reporting-form-container, published-container:reporting-published-container, form-container-published:reporting-form-container-published, subsection:reporting-subsection, results-title:reporting-results-title, td-head:reporting-td-head, td-action:reporting-td-action, td-body:reporting-td-body, td-body-2:reporting-td-body-2, add-button:reporting-add-button, remove-child-button:reporting-remove-child-button, uploader-button:reporting-uploader-button, section-head-collapsed:reporting-section-head-collapsed, section-title-expanded:reporting-section-title-expanded, section-title-collapsed:reporting-section-title-collapsed, section-head-expanded:reporting-section-head-expanded, progress-bar-finished:reporting-progress-bar-finished, progress-bar-complete:reporting-progress-bar-complete, progress-bar-incomplete:reporting-progress-bar-incomplete, section-success-icon:reporting-section-success-icon, section-body:reporting-section-body, title-section:reporting-title-section, button-lg:reporting-button-lg, uploader-detail-container:reporting-uploader-detail-container, textarea-label:reporting-textarea-label, date-label:reporting-date-label, commentbox:reporting-commentbox, comment-username:reporting-comment-username, detail-head:reporting-detail-head, reporting-uploader-extracted-text:reporting-reporting-uploader-extracted-text, reporting-uploader-sf-upload-message:reporting-reporting-uploader-sf-upload-message, reporting-uploader-sf-upload-submessage:reporting-reporting-uploader-sf-upload-submessage, reporting-uploader-extracted-text-chip:reporting-reporting-uploader-extracted-text-chip, reporting-uploader-extracted-text-chip-failed:reporting-reporting-uploader-extracted-text-chip-failed, reporting-uploader-doctype-verify-badge:reporting-reporting-uploader-doctype-verify-badge, reporting-span-submit-published:reporting-reporting-span-submit-published, reporting-span-submit-unpublished:reporting-reporting-span-submit-unpublished, reporting-reporting-container:reporting-reporting-reporting-container, reporting-button-icon:reporting-reporting-button-icon, reporting-uploader-button-icon:reporting-reporting-uploader-button-icon, reporting-sf-i-form-modal-container:reporting-reporting-sf-i-form-modal-container, reporting-next-calendar-date:reporting-reporting-next-calendar-date, reporting-last-calendar-date:reporting-reporting-last-calendar-date, reporting-input-publish-checkbox:reporting-reporting-input-publish-checkbox, reporting-button-icon-light:reporting-reporting-button-icon-light, reporting-button-icon-small:reporting-reporting-button-icon-small, reporting-uploader-input-label:reporting-reporting-uploader-input-label, reporting-input-radio:reporting-reporting-input-radio, reporting-radio-label:reporting-reporting-radio-label, reporting-input-textarea:reporting-reporting-input-textarea, reporting-input-textarea-disabled:reporting-reporting-input-textarea-disabled, reporting-input-date:reporting-reporting-input-date, reporting-input-date-disabled:reporting-reporting-input-date-disabled, reporting-input-select-single:reporting-reporting-input-select-single, reporting-textarea-container:reporting-reporting-textarea-container, reporting-section-body:reporting-reporting-section-body, reporting-section-container:reporting-reporting-section-container, reporting-subsection-container:reporting-reporting-subsection-container, reporting-date-container:reporting-reporting-date-container, reporting-input-sf-i-uploader:reporting-reporting-input-sf-i-uploader, reporting-published-container:reporting-reporting-published-container, reporting-selected-option:reporting-reporting-selected-option, reporting-input-select-multi-option:reporting-reporting-input-select-multi-option, reporting-select-option-label:reporting-reporting-select-option-label, reporting-input-sf-i-form:reporting-reporting-input-sf-i-form, reporting-input-sf-i-bricks:reporting-reporting-input-sf-i-bricks, reporting-uploader-input:reporting-reporting-uploader-input, reporting-form-container:reporting-reporting-form-container, reporting-published-container:reporting-reporting-published-container, reporting-form-container-published:reporting-reporting-form-container-published, reporting-subsection:reporting-reporting-subsection, reporting-results-title:reporting-reporting-results-title, reporting-td-head:reporting-reporting-td-head, reporting-td-action:reporting-reporting-td-action, reporting-td-body:reporting-reporting-td-body, reporting-td-body-2:reporting-reporting-td-body-2, reporting-add-button:reporting-reporting-add-button, reporting-remove-child-button:reporting-reporting-remove-child-button, reporting-uploader-button:reporting-reporting-uploader-button, reporting-section-head-collapsed:reporting-reporting-section-head-collapsed, reporting-section-title-expanded:reporting-reporting-section-title-expanded, reporting-section-title-collapsed:reporting-reporting-section-title-collapsed, reporting-section-head-expanded:reporting-reporting-section-head-expanded, reporting-progress-bar-finished:reporting-reporting-progress-bar-finished, reporting-progress-bar-complete:reporting-reporting-progress-bar-complete, reporting-progress-bar-incomplete:reporting-reporting-progress-bar-incomplete, reporting-section-success-icon:reporting-reporting-section-success-icon, reporting-section-body:reporting-reporting-section-body, reporting-title-section:reporting-reporting-title-section, reporting-button-lg:reporting-reporting-button-lg, reporting-uploader-detail-container:reporting-reporting-uploader-detail-container, reporting-textarea-label:reporting-reporting-textarea-label, reporting-date-label:reporting-reporting-date-label, reporting-commentbox:reporting-reporting-commentbox, reporting-comment-username:reporting-reporting-comment-username, reporting-detail-head:reporting-reporting-detail-head, input-sf-i-select:reporting-input-sf-i-select,reporting-input-sf-i-select:reporting-reporting-input-sf-i-select, input-sf-i-sub-select:reporting-input-sf-i-sub-select,reporting-input-sf-i-sub-select:reporting-reporting-input-sf-i-sub-select, select-input-select:reporting-select-input-select, sub-select-input-select:reporting-sub-select-input-select,list-container:reporting-list-container, checklist-container:reporting-checklist-container, checklist-title:reporting-checklist-title, checklist-list:reporting-checklist-list, checklist-item:reporting-checklist-item, checklist-checkbox:reporting-checklist-checkbox, checklist-checkbox-label:reporting-checklist-checkbox-label, reporting-list-container:reporting-reporting-list-container,reporting-checklist-container:reporting-reporting-checklist-container, reporting-checklist-title:reporting-reporting-checklist-title, reporting-checklist-list:reporting-reporting-checklist-list, reporting-checklist-item:reporting-reporting-checklist-item, reporting-checklist-checkbox:reporting-reporting-checklist-checkbox, reporting-checklist-checkbox-label:reporting-reporting-checklist-checkbox-label, checklist-add-input:reporting-checklist-add-input, checklist-add-button:reporting-checklist-add-button, terminate-container:reporting-terminate-container, terminate-container-terminated:reporting-terminate-container-terminated, terminate-container-active:reporting-terminate-container-active, input-terminate-checkbox: reporting-input-terminate-checkbox, reporting-terminate-container:reporting-reporting-terminate-container, reporting-terminate-container-terminated:reporting-reporting-terminate-container-terminated, reporting-terminate-container-active:reporting-reporting-terminate-container-active, reporting-input-terminate-checkbox: reporting-reporting-input-terminate-checkbox, uploader-container:reporting-uploader-container, reporting-uploader-container:reporting-reporting-uploader-container, not-selected:reporting-not-selected, reporting-not-selected:reportinig-reporting-not-selected, reporting-select-input-select:reporting-reporting-select-input-select, reporting-sub-select-input-select:reporting-reporting-sub-select-input-select" mode="edit" flow="reporting" name="RCM Resource Reporting" formviewclass="flex-wrap" showterminate="true" projectid="' + this.projectId + '"></sf-i-reporting>'

      let reportFormatContainers = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.report-format-container') as NodeListOf<HTMLDivElement>;
      for (let [indexContainer, reportFormatContainer] of reportFormatContainers.entries()) {
        if (reportFormatContainer != null) {
          reportFormatContainer.innerHTML = reportingHtml.replace('[INDEX]', indexContainer.toString());
        }
      }

    }
    let reportingReportings = (this._SfDetailContainer as HTMLDivElement).querySelectorAll('.reporting-reporting') as NodeListOf<SfIReporting>
    for (let reportingReporting of reportingReportings) {
      if (reportingSchemaJson != "" && reportingReporting != null) {
        reportingReporting.configjson = reportingSchemaJson;
        if (reportingSchemaValues != "") reportingReporting.prepopulateValJson = reportingSchemaValues
        // reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view"
        // reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true"
        reportingReporting.mode = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) ? "edit" : "view"
        reportingReporting.editdisable = (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_FUNCTION_HEAD) ? "false" : "true"
        reportingReporting.flow = "reporting"
        setTimeout(() => {
          reportingReporting.loadMode();
          console.log('list-customreporting', reportingSchemaJson);
          console.log('list-customreporting1', reportingSchemaValues);
          console.log('list-customreporting2', reportingReporting.mode);
          console.log('list-customreporting3', this.myRole);
        }, 500)
      }
    }

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.button-delete')?.addEventListener('click', async () => {

      // await this.fetchDeleteReview(listEvent["id"], mmddyyyy, entityId, locationId);
      // this.setSuccess('Deleted successfully!')
      // setTimeout(() => {
      //   this.clearMessages()
      // }, 3000);
      // //console.log('deleted', resultDelete);
      // if(this.getCurrentTab() == this.TAB_CUSTOM) {
      //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      // } else {
      //   if(currentColumnButton != null) {
      //     currentColumnButton.click();
      //   }
      // }

      console.log('delete review clicked')

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });
    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length === 0) {
        console.log('audto approve single')
      } else {
        console.log('auto approve bulk')
      }
      //console.log('deleted', resultDelete);
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

    });

    if (this.mode == "consumer" || this.mode == "next") {

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approver-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        let reportformatvalues: any = {}
        // let reportformatvaluesStr: string = ""
        let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
        console.log('renew reporting', reportingReporting)
        if (reportingReporting != null) {
          reportformatvalues = reportingReporting!.selectedValues()
          // reportformatvaluesStr = JSON.stringify(reportingReporting!.selectedValues())
        }
        let comparedObj = Util.compareObjects(reportformatvalues, JSON.parse(listEvent.reportformatvalues))
        console.log('reportformatvalues', reportformatvalues, JSON.parse(listEvent.reportformatvalues), comparedObj)
        if (Object.keys(comparedObj).length > 0) {
          await this.sendSuggestions(listEvent.id, comparedObj);
        }
        // return;
        var clickEvent = new MouseEvent("click", {
          "view": window,
          "bubbles": true,
          "cancelable": false
        });
        ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);

        // await this.uploadReview(entityId, locationId, mmddyyyy, event["id"], comments, approved)
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('mmddyyyy', mmddyyyy)
          if (await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
            if (approved) {
              // await this.renewRCMResource(listEvent, reportformatvaluesStr);
            } else {
              console.log('renew reporting', reportformatvalues)
            }
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                this.events[mmdd][p].approved = approved
                this.events[mmdd][p].terminated = (reportformatvalues.terminated) ?? false
                this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                this.events[mmdd][p].lastupdated = new Date().toString()
              }
            }
            if (this.recentlyReported[mmdd] == null) {
              this.recentlyReported[mmdd] = []
            }
            this.recentlyReported[mmdd].push(listEvent)
            console.log('review single')
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityId,
              "locationid": locationId,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": listEvent.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            entityId = selectedId.split('-')[7].replace(/_/g, '-');
            locationId = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                this.events[mmdd][p].isbulk = true
                flagBulk = true;
                if (this.recentlyReported[mmdd] == null) {
                  this.recentlyReported[mmdd] = []
                }
                this.recentlyReported[mmdd].push(this.events[mmdd][p])
              }
            }
          }
          console.log('review bulk')
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          this.renderRoleTabsNext(this.nextPage)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
            var clickEvent = new MouseEvent("click", {
              "view": window,
              "bubbles": true,
              "cancelable": false
            });
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)?.dispatchEvent(clickEvent);

            // if(currentColumnButton != null) {
            //   currentColumnButton.click();
            // }
          }
        }

      });

      (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(listEvent);
        let newEvent = { ...listEvent };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {

            if (await this.uploadAudit(entityId, locationId, mmddyyyy, listEvent["id"], comments, approved, listEvent.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(listEvent)
            }
            console.log('uploadaudit single')
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              entityId = selectedId.split('-')[7].replace(/_/g, '-');
              locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": listEvent.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true;
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }

            console.log('uploadAudit bulk')

          }

          var clickEvent = new MouseEvent("click", {
            "view": window,
            "bubbles": true,
            "cancelable": false
          });
          ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
          if (this.mode == "next") {
            this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {

        if (approved) {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }


        } else {

          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            (this._SfDetailContainer as HTMLDivElement).querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              // const reporterdoc = ((((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement) != null) && ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0) ? (new Date(((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              const reporterdoc = new Date().getTime() + "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);

              // if(docsOptional.length === 0) {
              // docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }

              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (listEvent.customreporting != null) {
                let reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-1') as SfIReporting
                if (reportingReporting == null) {
                  reportingReporting = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-reporting-0') as SfIReporting
                }
                console.log('reportformatvalues', JSON.stringify(reportingReporting.selectedValues()))
                reportformatvalues = JSON.stringify(reportingReporting!.selectedValues()) ?? "";
                reportformatschema = reportingReporting!.configjson ?? "";
              }

              let percentage: string = "100";
              if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }

              if (reportercomments.trim().length === 0) {
                buttonClick.innerHTML = "Save"
                this.setError('Comments cannot be blank!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {


                var clickEvent = new MouseEvent("click", {
                  "view": window,
                  "bubbles": true,
                  "cancelable": false
                });

                ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement)!.dispatchEvent(clickEvent);
                let flagBulk = false;
                if (this.selectedItemIds.length <= 1) {

                  if (await this.uploadReport(entityId, locationId, mmddyyyy, listEvent["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, listEvent.module, percentage, makercheckers)) {
                    console.log('this.events', this.events);
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                        this.events[mmdd][p].documents = docs
                        this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                        this.events[mmdd][p].lastupdated = new Date().toString()
                      }
                    }
                    console.log('uploadReport single')
                    if (makercheckers.length > 0) {

                      // await this.uploadReview(entityId, locationId, mmddyyyy, listEvent["id"], "Auto approved", true, "notices");
                      for (var p = 0; p < this.events[mmdd].length; p++) {
                        if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                          this.events[mmdd][p].approved = true
                          this.events[mmdd][p].terminated = (JSON.parse(reportformatvalues).terminated) ?? false
                          // this.events[mmdd][p].documents = docs
                          this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                          this.events[mmdd][p].lastupdated = new Date().toString()
                        }
                      }
                      // await this.renewRCMResource(listEvent, reportformatvalues);
                      console.log('upload report auto approve single')
                    }
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(listEvent)
                  }
                } else {
                  let bulkBody = []
                  let bulkBodyReview = []
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);

                    const makercheckersL = selectedId.split('-')[5];
                    entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                    //console.log(entityId, locationId, eventId, mmddyyyy);

                    // await this.uploadReport(entityId, locationId, mmddyyyy, eventId, reportercomments, reporterdoc, docs, null)
                    // if(parseInt(makercheckersL) > 0) {
                    //   bulkBodyReview.push({ 
                    //     "mmddyyyy": mmddyyyy,
                    //     "projectid": this.projectId, 
                    //     "type": "report",
                    //     "eventid": eventId,
                    //     "comments": reportercomments,
                    //     "dateofcompletion": reporterdoc,
                    //     "percentage": percentage,
                    //     "entityid": entityId,
                    //     "locationid": locationId,
                    //     "event": null,
                    //     "docs": JSON.stringify(docs),
                    //     "approved": true,
                    //     "username": this.userName,
                    //     "reportformatvalues": reportformatvalues,
                    //     "reportformatschema": reportformatschema,
                    //     "userid": this.userProfileId,
                    //     "userrole": this.myRole,
                    //     "year": this.calendarStartYYYY,
                    //     "module": listEvent.module ?? "compliance"
                    //   } )
                    //   // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, "Auto approved", true);

                    // }else{
                    let yearStr = this.getFinancialYear(mmddyyyy)
                    bulkBody.push({
                      "mmddyyyy": mmddyyyy,
                      "projectid": this.projectId,
                      "type": "report",
                      "eventid": eventId,
                      "comments": reportercomments,
                      "dateofcompletion": reporterdoc,
                      "percentage": percentage,
                      "entityid": entityId,
                      "locationid": locationId,
                      "event": null,
                      "docs": JSON.stringify(docs),
                      "username": this.userName,
                      "reportformatvalues": reportformatvalues,
                      "reportformatschema": reportformatschema,
                      "userid": this.userProfileId,
                      "userrole": this.myRole,
                      "year": yearStr,
                      "module": listEvent.module ?? "compliance",
                      "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                    })
                    // }

                    // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
                    // await this.sleep(2000);
                    // this.clearMessages();

                  }

                  // await this.uploadReportsBulk(bulkBody);
                  // await this.fetchBulkReportingData();
                  if (bulkBody.length > 0) {
                    await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                  }

                  // if(bulkBodyReview.length > 0){
                  //   await this.uploadReportsReviewsBulk(bulkBodyReview)
                  // }
                  await this.fetchBulkReportingData();
                  console.log('uploadReport bulk')
                  for (var k = 0; k < this.selectedItemIds.length; k++) {

                    const selectedId = this.selectedItemIds[k];
                    //console.log('selectedid', selectedId);
                    let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                    let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                    const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                    mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                    for (var p = 0; p < this.events[mmdd].length; p++) {
                      if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                        this.events[mmdd][p].isbulk = true
                        flagBulk = true;
                        if (this.recentlyReported[mmdd] == null) {
                          this.recentlyReported[mmdd] = []
                        }
                        this.recentlyReported[mmdd].push(this.events[mmdd][p])
                      }
                    }
                  }

                }

                if (this.mode == "next") {
                  this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                } else {
                  // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                  //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                  // } else 
                  if (this.getCurrentTab() == this.TAB_FIND) {
                    const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                    this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                  } else {
                    if (this.selectedItemIds.length > 0) {
                      await this.fetchBulkReportingData();
                    }
                    this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                    // if(currentColumnButton != null) {
                    //   currentColumnButton.click();
                    // }
                  }
                }

              }


              //     }
              //   }
              // }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          (this._SfDetailContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        });


        //console.log('documentType checking', documentType);

        if (documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = documentType;
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: listEvent.entityid,
          locationId: listEvent.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: listEvent['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (listEvent["approved"] != null) {
          if (listEvent["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
              ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if (((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement) != null) {
            ((this._SfDetailContainer as HTMLDivElement).querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }

        }
      }

    }
  }

  fetchEventDetails = async (listEvent: any, mmddyyyy: any, currentColumnButton: HTMLButtonElement | null, eventsContainer: HTMLDivElement, previousId: string = "", nextId: string = "", flagUploadGuidance: boolean = false, listEventContainer: HTMLDivElement | null = null, reportercomments: string | null = null, approvercomments: string | null = null, inputReportingPercentage: string | null = null, selectReportedLocation: string | null = null, documents: any | null = null, dateOfCompletion: string | null = null, fromDrilldown: boolean = false, flagFromListReporting: boolean = false) => {
    console.log('listEvent', listEvent, listEvent.id)
    let url = "https://" + this.apiId + "/getalleventdetails";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "eventid": listEvent.id, "entityid": listEvent.entityid, "locationid": listEvent.locationid, "mmddyyyy": mmddyyyy, "year": this.getFinancialYear(mmddyyyy) };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      if (flagUploadGuidance) {
        if (listEventContainer != null) {
          let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
          if (this.events[mmdd] != null) {
            for (var p = 0; p < this.events[mmdd].length; p++) {
              if (this.events[mmdd][p].id == listEvent.id && this.events[mmdd][p].locationid == listEvent.locationid && this.events[mmdd][p].entityid == listEvent.entityid) {
                if (flagFromListReporting) {
                  this.events[mmdd][p] = jsonRespose.data
                } else {
                  this.events[mmdd][p].uploadguidance = jsonRespose.data.uploadguidance
                }
              }
            }
          }
          let data = jsonRespose.data;
          if (reportercomments != null) {
            data.reportercomments = reportercomments;
          } else if (approvercomments != null) {
            data.approvercomments = approvercomments;
          }
          if (inputReportingPercentage != null) {
            data.percentage = inputReportingPercentage;
          }
          console.log('dateOfCompletion', dateOfCompletion, dateOfCompletion == null, dateOfCompletion == "");
          data.dateofcompletion = dateOfCompletion;
          data.reportedlocations = selectReportedLocation;
          if (documents != null) {
            data.documents = documents;
          }
          console.log('rendering list container', data);
          this.renderListReporting(listEventContainer, data, mmddyyyy, eventsContainer)
        }
      } else {
        this.renderEventDetail(jsonRespose.data, mmddyyyy, currentColumnButton, eventsContainer, previousId, nextId, fromDrilldown);
      }

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  renderEventDetail = (event: any, mmddyyyy: any, currentColumnButton: HTMLButtonElement | null, eventsContainer: HTMLDivElement, previousId: string, nextId: string, fromDrilldown: boolean) => {
    console.log('event details', event, mmddyyyy, currentColumnButton == null ? "null currentColumnButton" : currentColumnButton.id);
    console.log('previousid', previousId, 'nextid', nextId);
    console.log('confighome', Util.getProjectConfigHome())
    let comments, docs, approved /*,dateOfCompletion, makercheckers: Array<string>, docsOptional: boolean | any, documentType: string | any*/;
    let entityId: string = "";
    let locationId: string = "";
    let statuteName: string = "";
    let reportformatName: string = "";
    // let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
    entityId = event.entityid;
    locationId = event.locationid;
    // let completeness = this.getCompletenessStatus(event);
    comments = event['comments'] == null ? [] : (event['comments']);
    docs = event['documents'] == null ? [] : event['documents'] == null ? [] : (event['documents']);
    approved = event['approved'] == null ? false : event['approved'] == null ? false : event['approved'];
    // dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion'] == null ? '' : event['dateofcompletion'];
    // makercheckers = event['makercheckers'] == null ? [] : event['makercheckers'] == null ? [] : event['makercheckers'];
    // docsOptional = event['docs'] == null ? [] : event['docs'] == null ? [] : event['docs'];
    // documentType = event['documenttype'] == null ? null : event['documenttype'][0] == null ? null : event['documenttype'][0].split(" ")[0];

    statuteName = event['statute'][0].trim();
    if (event['reportformat'] != null) {
      reportformatName = (event['reportformat'][0] ?? "").trim().replace('&amp;', '&');
    }

    console.log('event detail', event, statuteName);
    //console.log('event detail comments', comments);
    //console.log('event dateofcompletion', dateOfCompletion);
    //console.log('event detail documenttype', documentType);
    const basicFields = ['id', 'shortid', 'entityname', 'locationname', 'functions'];
    const statuteFields = ['jurisdiction', 'country', 'state', 'category', 'subcategory', 'statute'];
    const complianceFields = ['specificity', 'reference', 'obligation', 'penalty', 'authority', 'frequency', 'subfrequency', 'obligationtype', 'duedate', 'applicability', 'form', 'additionalurls', 'adhocquestion', 'adhocquestionschedule', 'adhocinstances', 'uploadguidance', 'attachment'];
    const grcFields = ['internalcontrols', 'firstlineofdefence', 'secondlineofdefence', 'thirdlineofdefence', 'risk', 'riskarea'];

    let listReportingContainers = eventsContainer.querySelectorAll('.list-reporting-container') as NodeListOf<HTMLDivElement>
    for (let tempReportingContainer of listReportingContainers) {
      tempReportingContainer.style.display = 'none';
      tempReportingContainer.innerHTML = '';
    }
    let buttonListReportings = eventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
    for (let buttonListReporting of buttonListReportings) {
      buttonListReporting.setAttribute('part', 'button-list-reporting')
    }
    let streamEventTitles = eventsContainer.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
    for (let streamEventTitle of streamEventTitles) {
      streamEventTitle.removeAttribute('part')
    }
    var html = `
    
      <div part="compliance-detail-title" class="d-flex justify-between">
        ${(previousId != "" || nextId != "") ? `
          <div part="compliance-detail-prev-next" class="d-flex justify-center align-center">
        <button id="button-detail-previous" part="button-icon" class="mr-10 material-icons${previousId != "" ? "" : " gone"}">chevron_left</button>
        <button id="button-detail-next" part="button-icon" class="material-icons${nextId != "" ? "" : " gone"}">chevron_right</button>
      </div>
      ` : `
        <button part="button-icon" class="material-icons invisible">close</button>
      `}
        <h3 part="results-title" class="m-0">Compliance Details</h3>
        <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
      </div>
    
    `;

    // if (previousId != "" || nextId != "") {
    //   html += `
    //   <div part="compliance-detail-prev-next" class="d-flex justify-between m-20">
    //     <button id="button-detail-previous" part="button-icon" class="material-icons${previousId != "" ? "" : " invisible"}">chevron_left</button>
    //     <button id="button-detail-next" part="button-icon" class="material-icons${nextId != "" ? "" : " invisible"}">chevron_right</button>
    //   </div>
    //   `
    // }

    if (this.selectedItemIds.length > 1) {

      html += `
    
        <div class="d-flex justify-between m-20">
          <h4 class="m-0">${this.selectedItemIds.length - 1} other ` + ((this.selectedItemIds.length - 1) === 1 ? `item` : `items`) + ` also selected</h4>
        </div>
    
      `;

    }

    html += '<div class="accordian-container m-20 pb-20" part="accordian-container">';

    html += '<div part="detail-summary">';
    html += ('<div part="detail-summary-title" class="pl-20 pr-20"><h1>' + event['obligationtitle'].replace(/\\n|\r?\n/g, '') + '</h1></div>');
    let obligationArr = event['obligation'].split('More information:');
    console.log('detailsObligation', obligationArr[0], obligationArr[0].replace(/\\n|\r?\n/g, '<br />'))
    html += ('<div part="detail-summary-subtitle" class="pl-20 pr-20"><h3>' + obligationArr[0].replace(/\\n|\r?\n/g, '<br />') + '</h3></div>');
    if (obligationArr.length > 1) {
      let tempObligationArr = obligationArr.slice(1);
      console.log('tempObligationArr', tempObligationArr);
      html += ('<div part="detail-summary-subtitle-more-info" class="pl-20 pr-20 pb-10">' + ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="More information:' + (tempObligationArr.join('')).replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="80"></sf-i-elastic-text>') + '</div>');
    }
    html += ('<div part="detail-summary-content" class="pl-20 pr-20 pt-20">' + ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event['internalcontrols'] + "").replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="80"></sf-i-elastic-text>') + '</div>');
    html += '</div>';

    html += '<br />';

    html += '<div class="accordian-section section-basic pl-20 pr-20" part="accordian-section">';
    html += '<div class="d-flex justify-between accordian-head head-basic cursor" part="accordian-head">';
    html += '<h3>Basic Information</h3>'
    html += '<h3 class="head-indicator-basic">-</h3>'
    html += '</div>';
    html += '<div class="d-flex flex-wrap accordian-body body-basic" part="accordian-body">';

    for (var i = 0; i < basicFields.length; i++) {

      if (!this.getEventPreviewFields().includes(basicFields[i])) {

        if (!this.getEventHideFields().includes(basicFields[i])) {

          console.log('basicFields', event[basicFields[i]] + "");
          if ((event[basicFields[i]] + "").indexOf("[") >= 0) {
            html += '<div class="m-20">';
            html += '<div part="detail-head"><strong>' + basicFields[i] + '</strong></div>'
            html += this.getEventTexts(basicFields[i], JSON.parse(event[basicFields[i]]), event).replace(/ *\([^)]*\) */g, "").trim();
            html += '</div>';
          } else {
            html += '<div class="m-20">';
            html += '<div part="detail-head"><strong>' + basicFields[i] + '</strong></div>'
            html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event[basicFields[i]] + "").replace(/"/g, "").replace(/ *\([^)]*\) */g, "").trim().split(';')[0] + '" minLength="80"></sf-i-elastic-text>';
            html += '</div>';
          }

        }
      }

    }

    if (this.mode == "consumer") {
      if (approved) {
        html += '<div class="m-20">';
        html += '<div part="detail-head"><strong>Approved</strong></div>'
        html += '<span class="material-icons color-done">check_circle</span>'
        html += '</div>';
      }
    }

    if (docs != null) {
      html += '<div class="m-20">';
      html += '<div part="detail-head"><strong>Documents</strong></div>'
      html += '<span class="material-icons muted">description</span>'
      html += docs.length
      html += '</div>';
    }

    if (comments != null) {
      html += '<div class="m-20">';
      html += '<div part="detail-head"><strong>Comments</strong></div>'
      html += '<span class="material-icons muted">forum</span>'
      html += comments.length
      html += '</div>';
    }

    html += '<div class="m-20">';
    html += '<div part="detail-head"><strong>Reporters</strong></div>'
    html += this.getReporterDetailStringFromEvent(event);
    html += '</div>';

    html += '<div class="m-20">';
    html += '<div part="detail-head"><strong>Approvers</strong></div>'
    html += this.getApproverDetailStringFromEvent(event);
    html += '</div>';

    html += '</div>';
    html += '</div>';


    html += '<div class="accordian-section section-statute pl-20 pr-20" part="accordian-section">';
    html += '<div class="d-flex justify-between accordian-head head-statute cursor" part="accordian-head">';
    html += '<h3>Statute Information</h3>'
    html += '<h3 class="head-indicator-statute">-</h3>'
    html += '</div>';
    html += '<div class="d-flex flex-wrap accordian-body body-statute" part="accordian-body">';

    for (var i = 0; i < statuteFields.length; i++) {

      if (!this.getEventPreviewFields().includes(statuteFields[i])) {
        if (event[statuteFields[i]] != null && event[statuteFields[i]] != "") {
          if (!this.getEventHideFields().includes(statuteFields[i])) {

            html += '<div class="m-20">';
            html += '<div part="detail-head"><strong>' + statuteFields[i] + '</strong></div>'
            if ((event[statuteFields[i]] + "").indexOf("[") >= 0 && Util.isJSONParsable((event[statuteFields[i]] + ""))) {
              html += this.getEventTexts(statuteFields[i], JSON.parse(event[statuteFields[i]]), event);
            } else {
              html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event[statuteFields[i]] + "").replace(/"/g, "") + '" minLength="80"></sf-i-elastic-text>';
            }
            html += '</div>';

          }
        }
      }

    }

    html += '<div id="container-definition" class="w-100"></div>';

    html += '</div>';
    html += '</div>';

    html += '<div class="accordian-section section-compliance pl-20 pr-20" part="accordian-section">';
    html += '<div class="d-flex justify-between accordian-head head-compliance" part="accordian-head">';
    html += '<h3>Compliance Information</h3>'
    html += '<h3 class="head-indicator-compliance">-</h3>'
    html += '</div>';
    html += '<div class="d-flex flex-wrap accordian-body body-compliance" part="accordian-body">';

    for (var i = 0; i < complianceFields.length; i++) {

      //console.log(complianceFields[i]);
      //console.log(event[complianceFields[i]]);

      if (!this.getEventPreviewFields().includes(complianceFields[i])) {

        if (!this.getEventHideFields().includes(complianceFields[i])) {
          if (event[complianceFields[i]] != null && event[complianceFields[i]] != "") {
            if (event[complianceFields[i]].indexOf('http://') >= 0) {

              let res = event[complianceFields[i]].split(" ").find((word: any) => word.startsWith("http"));
              html += '<div class="m-20">';
              html += '<div part="detail-head"><strong>' + complianceFields[i] + '</strong></div>'
              if ((event[complianceFields[i]] + "").indexOf("[") >= 0) {
                html += this.getEventTexts(complianceFields[i], JSON.parse(event[complianceFields[i]]), event) + "&nbsp;<a href=\"" + res + "\" target=\"_blank\">Open</a>";
              } else {
                html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event[complianceFields[i]] + "").replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="80"></sf-i-elastic-text>' + "&nbsp;<a href=\"" + res + "\" target=\"_blank\">Open</a>";
              }
              html += '</div>';

            } else if (complianceFields[i] == 'attachment') {
              if (event[complianceFields[i]] != null && event[complianceFields[i]].length > 0) {
                console.log('attachments str', event[complianceFields[i]]);

                html += '<div class="m-20">';
                html += '<div part="detail-head"><strong>' + complianceFields[i] + '</strong></div>'
                if (typeof event[complianceFields[i]] === "string") {
                  let attachmentArr = JSON.parse(event[complianceFields[i]].toString());
                  if (attachmentArr.length > 0) {
                    for (let attachment of attachmentArr) {
                      html += `<sf-i-uploader class="event-attachment" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": attachment.key, "ext": attachment.ext }]).replace(/"/g, '&quot;')}" extract="no" mode="view" maximize="yes" hidepreview="yes" displaydetail="yes"></sf-i-uploader>`
                    }
                  }
                } else {
                  for (let attachmentStr of event[complianceFields[i]]) {
                    let attachment: any = {};
                    if (typeof attachmentStr === "object") {
                      attachment = attachmentStr;

                    } else {
                      attachment = JSON.parse(attachmentStr.toString());
                    }
                    // html += `<sf-i-uploader class="event-attachment" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": attachment.key, "ext": attachment.ext }]).replace(/"/g, '&quot;')}" projectid="${this.projectId}" extract="no" mode="view" maximize="yes" hidepreview="yes" displaydetail="yes"></sf-i-uploader>`
                    html += `<sf-i-uploader class="event-attachment" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;,&quot;xls&quot;,&quot;xlsx&quot;,&quot;doc&quot;,&quot;docx&quot;]" prepopulatedInputArr="${JSON.stringify([{ "key": attachment.key, "ext": attachment.ext }]).replace(/"/g, '&quot;')}" extract="no" mode="view" maximize="yes" hidepreview="yes" displaydetail="yes"></sf-i-uploader>`
                  }
                }
                html += '</div>';
              }
            } else {

              html += '<div class="m-20">';
              html += '<div part="detail-head"><strong>' + complianceFields[i] + '</strong></div>'
              if ((event[complianceFields[i]] + "").indexOf("[") >= 0) {
                html += this.getEventTexts(complianceFields[i], JSON.parse(event[complianceFields[i]]), event);
              } else {
                html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event[complianceFields[i]] + "").replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="80"></sf-i-elastic-text>';
              }
              html += '</div>';

            }
          }
        }
      }

    }

    html += '</div>';
    html += '</div>';

    html += '<div class="accordian-section section-grc pl-20 pr-20" part="accordian-section">';
    html += '<div class="d-flex justify-between accordian-head head-grc" part="accordian-head">';
    html += '<h3>GRC Information</h3>'
    html += '<h3 class="head-indicator-grc">-</h3>'
    html += '</div>';
    html += '<div class="d-flex flex-wrap accordian-body body-grc" part="accordian-body">';

    for (var i = 0; i < grcFields.length; i++) {

      //console.log(grcFields[i]);
      if (!this.getEventPreviewFields().includes(grcFields[i])) {
        if (event[grcFields[i]] != null && event[grcFields[i]] != "") {
          if (!this.getEventHideFields().includes(grcFields[i])) {

            html += '<div class="m-20">';
            html += '<div part="detail-head"><strong>' + grcFields[i] + '</strong></div>'

            if (grcFields[i].toLowerCase() == "riskarea") {

              const arrValues = event[grcFields[i]];
              for (var k = 0; k < arrValues.length; k++) {
                html += '<div part="detail-reporter-name" class="mr-10">' + arrValues[k] + '</div>';
              }

            } else {
              if ((event[grcFields[i]] + "").indexOf("[") >= 0) {
                html += this.getEventTexts(grcFields[i], JSON.parse(event[grcFields[i]]), event);
              } else {
                //console.log('grcfield', event[grcFields[i]]);
                html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (event[grcFields[i]] + "").replace(/"/g, "").replace(/\\n|\r?\n/g, '<br />') + '" minLength="80"></sf-i-elastic-text>';
              }
            }

            html += '</div>';

          }
        }
      }

    }

    html += '</div>';
    html += '</div>';

    html += '<sf-new-feature class="new-feature m-10" exportparts="new-feature-text-container,new-feature-text" updatetime="1743405417000"></sf-new-feature>'
    html += '<div class="accordian-section section-feedback pl-20 pr-20" part="accordian-section">';
    html += '<div class="d-flex justify-between accordian-head head-feedback" part="accordian-head">';
    html += '<h3>Feedback</h3>'
    html += '<h3 class="head-indicator-feedback">+</h3>'
    html += '</div>';
    html += '<div class="d-flex flex-wrap accordian-body body-feedback hide" part="accordian-body">';

    html += '<div class="d-flex justify-end w-100 flex-wrap">'
    html += '<div class="d-flex w-100 mb-10">'
    html += '<div part="feedback-message">Do you wish to send us feedback about this compliance? Any doubts? Need guidance or more clarity? Drop us a feedback and we will revert soon.</div>'
    html += '</div>'
    html += '<div class="d-flex justify-end w-100 mb-10">'
    html += '<textarea part="input" id="feedback-message" class="w-100 mt-10 mb-10 hide" placeholder="Type your feedback message here..."></textarea>'
    html += '</div>'
    if (this.myRole == this.TAB_FUNCTION_HEAD || this.myRole == this.TAB_VIEWER) {
      html += '<div part="suspense-container" class="d-flex justify-start w-100">'
      html += '<input part="input-checkbox" id="feedback-suspense" class="hide" type="checkbox"/>'
      html += '<label part="input-checkbox-label" id="feedback-suspense-label" class="ml-10 hide">Mark Suspense</label>'
      html += '</div>'
    }
    html += '<div class="d-flex w-100">'
    html += ('<button part="button-lg-short" id="button-feedback" class="d-flex justify-center align-center"><span class="material-symbols-outlined">comment</span><span>&nbsp;&nbsp;Send Feedback</span></button>');
    html += ('<button part="button-lg-short-secondary" id="button-feedback-cancel" class="hide d-flex justify-center align-center mr-10"><span class="material-symbols-outlined">close</span><span>&nbsp;&nbsp;Cancel</span></button>');
    html += ('<button part="button-lg-short" id="button-feedback-confirm" class="hide d-flex justify-center align-center"><span class="material-symbols-outlined">commentcheck</span><span>&nbsp;&nbsp;Submit Feedback</span></button>');
    html += '</div>'
    html += '</div>'

    html += '</div>';
    html += '</div>';

    html += '</div>';

    if (this.mode == "consumer" || this.mode == "next" || this.mode == "viewer") {
      if (this.mode != "viewer" && !fromDrilldown) {
        html += '<div part="reporting-view-container" class="m-20" id="reporting-view-container">'
        html += this.renderReporting(event, mmddyyyy);
        html += "</div>"
      }

      html += '<div class="d-flex justify-between m-20">';
      html += '<h3 part="results-title" class="m-0"><br />Comments</h3>';
      html += '</div>';

      html += '<div class="m-20">';

      html += '<div class="d-flex flex-col">';

      for (var i = 0; i < comments.length; i++) {
        html += '<div part="commentbox" class="d-flex commentbox ' + (comments[i].author + "").toLowerCase() + 'box">';
        html += '<div class="mr-20 d-flex flex-col align-end"><span part="comment-username">' + (comments[i].username != null ? comments[i].username : '') + '</span><span part="td-head">' + comments[i].author + '</span>' + ((i === (comments.length - 1) && this.enableDeleteLatestReport) ? '<br /><button class="mt-5 button-delete" part="button">Delete</button>' : '') + '</div>';

        const onlyCommentText = (comments[i].comment + "").replace(/ *\([^)]*\) */g, "").trim();
        try {

          const jsonComments = JSON.parse(onlyCommentText);

          if (Util.isInteger(jsonComments)) {
            html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
          } else {
            //console.log('json comments', jsonComments);
            var htmlTable = '';
            for (var j = 0; j < Object.keys(jsonComments).length; j++) {
              htmlTable += '<div class="mb-20">';
              htmlTable += ('<div part="detail-head">' + Object.keys(jsonComments)[j] + '</div>');
              htmlTable += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonComments[Object.keys(jsonComments)[j]] + '" minLength="20"></sf-i-elastic-text>');
              htmlTable += '</div>';
            }
            html += '<div class="">' + htmlTable + '<small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
          }

        } catch (e: any) {
          //console.log('json comments exception', comments[i]);
          html += '<div class="">' + comments[i].comment + '<br /><small><span class="muted">' + Util.getDateTimeStrings(new Date(comments[i].timestamp).getTime()) + '</span></small></div>';
        }

        html += '</div>';
      }
      if (comments.length === 0) {
        html += '<div><strong>No comments yet!</strong></div>';
      }

      html += '</div>';

      html += '</div>';

      if (event.reportevent != null) {

        html += '<div class="d-flex justify-between m-20">';
        html += '<h3 part="results-title" class="m-0"><br />Reported Event Details</h3>';
        html += '</div>';
        html += '<div class="m-20">';

        html += '<div class="w-100p scroll-x">';
        console.log("reportevent", JSON.parse(event.reportevent));
        const jsonReportEvent = JSON.parse(event.reportevent);

        html += '<table>';
        html += '<tr>';
        for (i = 0; i < Object.keys(jsonReportEvent).length; i++) {

          if (!this.EXCLUDE_COLS_FROM_REGS.includes(Object.keys(jsonReportEvent)[i].toLowerCase())) {

            html += '<td part="td-body-register">';
            html += ('<span part="td-head" style="padding-left: 0px !important">' + Object.keys(jsonReportEvent)[i] + '</span>');
            html += ('<span part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + jsonReportEvent[Object.keys(jsonReportEvent)[i]] + '" lineSize="4" minLength="60"></sf-i-elastic-text>' + '</span>');
            html += '</td>';

          }

        }
        html += '</tr>';
        html += '</table>';

        html += '</div>';

        html += '<div>';
      }

    }

    (this._SfDetailContainer as HTMLDivElement).innerHTML = html;
    (this._SfDetailContainer as HTMLDivElement).style.display = 'block';
    if (this.mode != "viewer" && (this._SfUploader[0]) != null) {
      let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2];

      let emailcontent = `<table border="0" cellspacing="0" style="color:#666666;border-radius:5px;border:solid 1px #efefef;width:100%; margin-top:20px"><tbody><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Compliance ID</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.id}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Country</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.countryname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Entity</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.entityname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Location</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.locationname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Statute</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.statute[0] ?? ""}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Subcategory</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.subcategory}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Reporter</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.reporters[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Approver</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.approvers[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Due Date</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${ddmmyyyy}</td></tr></tbody></table>`;
      (this._SfUploader[0].querySelector('#uploader') as SfIUploader).emailcontent = emailcontent;
    }

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-previous')?.addEventListener('click', () => {
      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((eventsContainer as HTMLDivElement).querySelector('#' + previousId) as HTMLElement)?.dispatchEvent(clickEvent);
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-next')?.addEventListener('click', () => {
      var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
      });
      ((eventsContainer as HTMLDivElement).querySelector('#' + nextId) as HTMLElement)?.dispatchEvent(clickEvent);
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.head-basic')?.addEventListener('click', () => {

      //console.log('head basic clicked', ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display);

      if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display == '') {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display = 'none';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-basic') as HTMLDivElement).innerHTML = '+';
      } else {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-basic') as HTMLDivElement).style.display = 'flex';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-basic') as HTMLDivElement).innerHTML = '-';
      }
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.head-statute')?.addEventListener('click', () => {

      //console.log('head statute clicked', ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display);

      if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display == '') {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display = 'none';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-statute') as HTMLDivElement).innerHTML = '+';
      } else {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-statute') as HTMLDivElement).style.display = 'flex';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-statute') as HTMLDivElement).innerHTML = '-';
      }
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.head-compliance')?.addEventListener('click', () => {
      if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display == '') {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display = 'none';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-compliance') as HTMLDivElement).innerHTML = '+';
      } else {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-compliance') as HTMLDivElement).style.display = 'flex';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-compliance') as HTMLDivElement).innerHTML = '-';
      }
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.head-grc')?.addEventListener('click', () => {
      if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display == 'flex' || ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display == '') {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display = 'none';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-grc') as HTMLDivElement).innerHTML = '+';
      } else {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-grc') as HTMLDivElement).style.display = 'flex';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-grc') as HTMLDivElement).innerHTML = '-';
      }
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('.head-feedback')?.addEventListener('click', () => {
      if (((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display == 'flex') {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display = 'none';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-feedback') as HTMLDivElement).innerHTML = '+';
      } else {
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.body-feedback') as HTMLDivElement).style.display = 'flex';
        ((this._SfDetailContainer as HTMLDivElement).querySelector('.head-indicator-feedback') as HTMLDivElement).innerHTML = '-';
      }
    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfDetailContainer as HTMLDivElement).innerHTML = '';
      (this._SfDetailContainer as HTMLDivElement).style.display = 'none';

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback')?.addEventListener('click', () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement);
      const feedbackSuspenseLabel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense-label') as HTMLLabelElement);
      const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);

      console.log(buttonConfirm.classList);

      if (feedbackMessage.classList.contains('hide')) {
        feedbackMessage.classList.remove('hide');
      }

      if (feedbackSuspense != null) {
        if (feedbackSuspense.classList.contains('hide')) {
          feedbackSuspense.classList.remove('hide');
        }
      }
      if (feedbackSuspenseLabel != null) {
        if (feedbackSuspenseLabel.classList.contains('hide')) {
          feedbackSuspenseLabel.classList.remove('hide');
        }
      }

      if (buttonConfirm.classList.contains('hide')) {
        buttonConfirm.classList.remove('hide');
      }

      if (buttonCancel.classList.contains('hide')) {
        buttonCancel.classList.remove('hide');
      }

      if (!buttonFeedback.classList.contains('hide')) {
        buttonFeedback.classList.add('hide');
      }

      // const body = {
      //   projectid: this.projectId,
      //   complianceid: compliance.id
      // }
      // console.log(body);

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel')?.addEventListener('click', () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement);
      const feedbackSuspenseLabel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense-label') as HTMLLabelElement);
      const buttonFeedback = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback') as HTMLButtonElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);

      console.log(buttonConfirm.classList);

      if (!feedbackMessage.classList.contains('hide')) {
        feedbackMessage.classList.add('hide');
      }

      if (feedbackSuspense != null) {
        if (feedbackSuspense.classList.contains('hide')) {
          feedbackSuspense.classList.remove('hide');
        }
      }
      if (feedbackSuspenseLabel != null) {
        if (feedbackSuspenseLabel.classList.contains('hide')) {
          feedbackSuspenseLabel.classList.remove('hide');
        }
      }

      if (!buttonConfirm.classList.contains('hide')) {
        buttonConfirm.classList.add('hide');
      }

      if (!buttonCancel.classList.contains('hide')) {
        buttonCancel.classList.add('hide');
      }

      if (buttonFeedback.classList.contains('hide')) {
        buttonFeedback.classList.remove('hide');
      }

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm')?.addEventListener('click', async () => {

      const feedbackMessage = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message') as HTMLTextAreaElement);
      const feedbackSuspense = ((this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-suspense') as HTMLInputElement);
      const buttonCancel = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-cancel') as HTMLButtonElement);
      const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement);
      console.log('sending feedback', event);
      if (feedbackMessage.value.length === 0) {
        feedbackMessage.setAttribute('style', 'border:solid 2px ' + this.COLOR_REJECTED + ' !important');
      } else {
        feedbackMessage.setAttribute('style', 'border:');
        let feedbackSuspenseVal = false
        if (feedbackSuspense != null && feedbackSuspense.checked) {
          feedbackSuspenseVal = true
        }
        let shortid = event.shortid
        if (Util.isJSONParsable(event.shortid)) {
          shortid = JSON.parse(event.shortid)[0]
        }
        this.uploadTriggerMyEvent(
          event.id + " - " + shortid,
          feedbackMessage.value,
          (event.country[0] ?? "").replace(/ *\([^)]*\) */g, ""),
          (event.entityname ?? "").replace(/ *\([^)]*\) */g, ""),
          (event.locationname ?? "").replace(/ *\([^)]*\) */g, ""),
          event.statute[0],
          event.subcategory[0],
          {
            addtosuspense: feedbackSuspenseVal,
            mmddyyyy: mmddyyyy,
            eventid: event.id,
            entityid: entityId,
            locationid: locationId,
            reporters: event.reporters,
            approvers: event.approvers,
            functionheads: event.functionheads,
            obligationtitle: event.obligationtitle,
            obligation: event.obligation,
            reference: event.reference,
          }
        );
        buttonCancel.click();
        buttonClose.click();
      }

    });

    (this._SfDetailContainer as HTMLDivElement).querySelector('#feedback-message')?.addEventListener('keyup', (e: any) => {

      if (e.code == "Enter") {

        const buttonConfirm = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-feedback-confirm') as HTMLButtonElement);
        buttonConfirm.click();

      }

    })

    if (this.mode == "consumer" || this.mode == "next") {
      let eventDetailReportingContainer = (this._SfDetailContainer as HTMLDivElement).querySelector('#reporting-view-container') as HTMLDivElement
      if (eventDetailReportingContainer != null) {
        this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, (this._SfDetailContainer as HTMLDivElement))
      }
    }

    this.fetchStatuteDefinitionDetails(statuteName);
    console.log('customreporting', event['customreporting'])
    if (event['customreporting'] != null) {
      let reportingContainer = (this._SfDetailContainer as HTMLDivElement)
      if (reportingContainer.querySelector('#report-format-container') != null) {
        reportingContainer.querySelector('#report-format-container')!.innerHTML = `<slot name="reporting"></slot>`;
        console.log('innerhtml', reportingContainer.querySelector('#report-format-container')!.innerHTML);
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).name = event.obligationtitle;
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).mode = "edit";
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).flow = "reporting";
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).configjson = event['customreporting'];
        // if(reportformatvalues != ""){
        //   (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).prepopulateValJson = reportformatvalues
        // }
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).loadMode();
      }
    } else if (event['reportformat'] != null && event['reportformat'].length > 0) {
      this.fetchReportFormat((this._SfDetailContainer as HTMLDivElement), reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? "");
    }
  }

  renderEventDetailReporting = (eventDetailReportingContainer: HTMLDivElement, event: any, mmddyyyy: any, eventDetailContainer: HTMLDivElement) => {
    console.log('detailreporting event', event, this.graphFilter);
    let html = ''
    let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]

    let reportformatName: string = '';
    if (event['reportformat'] != null) {
      reportformatName = (event['reportformat'][0] ?? "").trim().replace('&amp;', '&');
    }
    let docs = event['documents'] == null ? [] : event['documents'];
    event.approved = event['approved'] == null ? false : event['approved'];
    event.dateOfCompletion = event['dateofcompletion'] == null ? '' : event['dateofcompletion'];
    event.makercheckers = event['makercheckers'] == null ? [] : event['makercheckers'];
    event.docsOptional = event['docs'] == null ? [] : event['docs'];
    html = this.renderReporting(event, mmddyyyy);
    console.log('reporting html', html);
    let ddmmyyyy = mmddyyyy.split('/')[1] + '/' + mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[2];

    let emailcontent = `<table border="0" cellspacing="0" style="color:#666666;border-radius:5px;border:solid 1px #efefef;width:100%; margin-top:20px"><tbody><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Compliance ID</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.id}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Country</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.countryname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Entity</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${event.entityname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Location</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.locationname.replace(/ *\([^)]*\) */g, "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%;font-weight:bold">Statute</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#fbfbfb;font-size:110%">${(event.statute[0] ?? "")}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Subcategory</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.subcategory}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Reporter</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.reporters[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Approver</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${event.approvers[0].split(';')[0]}</td></tr><tr><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%;font-weight:bold">Due Date</td><td style="padding:10px;padding-top:10px;padding-bottom:10px;vertical-align:top;background-color:#f5f5f5;font-size:110%">${ddmmyyyy}</td></tr></tbody></table>`;
    eventDetailReportingContainer.innerHTML = html;
    if (this._SfUploader[0] != null) {
      (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.emailcontent = emailcontent;
    }
    const buttonClose = ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-detail-close') as HTMLButtonElement);

    (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.addEventListener('change', (e) => {
      let value = (e.target as HTMLInputElement).value;
      if (this.reportingSuggestionsNotApplicable.indexOf(value) >= 0) {
        console.log('suggestion matched', value);
        let uploadOptionalWarning = eventDetailReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement;
        uploadOptionalWarning.classList.remove('hide');
        let supportingDocumentsLabel = eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement;
        supportingDocumentsLabel.innerText = 'Supporting Documents';
      } else {
        let uploadOptionalWarning = eventDetailReportingContainer.querySelector('#uploader-optional-warning') as HTMLDivElement;
        uploadOptionalWarning.classList.add('hide');
        let supportingDocumentsLabel = eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement;
        supportingDocumentsLabel.innerText = 'Supporting Documents' + (event.docsOptional.length > 0 ? '' : '*');
      }
    })
    let deleteButtons = eventDetailContainer.querySelectorAll('.button-delete') as NodeListOf<HTMLButtonElement>
    for (let deleteButton of deleteButtons) {
      deleteButton?.addEventListener('click', async () => {

        await this.fetchDeleteReview(event["id"], mmddyyyy, event.entityid, event.locationid);
        this.setSuccess('Deleted successfully!')
        setTimeout(() => {
          this.clearMessages()
        }, 3000);
        //console.log('deleted', resultDelete);
        if (this.getCurrentTab() == this.TAB_CUSTOM) {
          this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
        } else {
          // if(currentColumnButton != null) {
          //   currentColumnButton.click();
          // }
        }

      });
    }
    eventDetailReportingContainer.querySelector('#button-auto-approve')?.addEventListener('click', async () => {
      if (this.selectedItemIds.length <= 1) {
        await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
        this.setSuccess('Auto-Approved successfully!')
        setTimeout(() => {
          this.clearMessages()
        }, 3000);
      } else {
        let bulkBodyReview = []
        for (var k = 0; k < this.selectedItemIds.length; k++) {

          const selectedId = this.selectedItemIds[k];
          //console.log('selectedid', selectedId);
          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

          //console.log(entityId, locationId, eventId, mmddyyyy);
          let yearStr = this.getFinancialYear(mmddyyyy)
          bulkBodyReview.push({
            "mmddyyyy": mmddyyyy,
            "projectid": this.projectId,
            "type": "review",
            "eventid": eventId,
            "comments": "Auto approved",
            "approved": true,
            "entityid": entityId,
            "locationid": locationId,
            "username": this.userName,
            "userid": this.userProfileId,
            "userrole": this.myRole,
            "year": yearStr,
            "module": event.module ?? "compliance"
          })
        }
        await this.uploadReviewsBulk(bulkBodyReview);
      }
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
      } else {
        // if(currentColumnButton != null) {
        //   currentColumnButton.click();
        // }
      }

    });
    eventDetailReportingContainer.querySelector('#upload-guidance-button')?.addEventListener('click', async () => {
      console.log('upload guidance clicked', event);
      let inputReportingPercentage = (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement)?.value ?? "100";
      let selectReportedLocations = (eventDetailReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf<HTMLSelectElement>);
      let selectReportedLocationValue = "[]";
      for (let selectReportedLocation of selectReportedLocations) {
        selectReportedLocationValue = JSON.stringify([...JSON.parse(selectReportedLocationValue), selectReportedLocation.value])
      }
      let approvercomments = (eventDetailReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement)?.value ?? "";
      let reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement)?.value ?? "";
      let dateOfCompletion;
      if ((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement) != null) {
        dateOfCompletion = new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "";
      } else {
        dateOfCompletion = new Date((eventDetailReportingContainer.querySelector('#input-approver-doc') as HTMLInputElement).value).getTime() + "";
      }
      let documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader).selectedValues()
      if (dateOfCompletion == "NaN") {
        dateOfCompletion = "";
      }
      console.log('dateOfCompletion', dateOfCompletion)
      await this.fetchEventDetails(event, mmddyyyy, null, eventDetailContainer, "", "", true, eventDetailReportingContainer, reportercomments, approvercomments, inputReportingPercentage, selectReportedLocationValue, documents, dateOfCompletion);
    })
    if (this.mode == "consumer" || this.mode == "next") {
      let inputReportingPercentage = eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement;
      let percentage = inputReportingPercentage.value
      const entityContainers = eventDetailReportingContainer.querySelectorAll('.reporting-entity-container') as NodeListOf<HTMLDivElement>;
      const locationsContainers = eventDetailReportingContainer.querySelectorAll('.reporting-location-container') as NodeListOf<HTMLDivElement>;
      const addLocationButtons = eventDetailReportingContainer.querySelectorAll('.button-reporter-location-add') as NodeListOf<HTMLButtonElement>;
      if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) {
        entityContainers.forEach(container => container.classList.remove('hide'));
        locationsContainers.forEach(container => container.classList.remove('hide'));
        addLocationButtons.forEach(container => container.classList.remove('hide'));
      } else {
        entityContainers.forEach(container => container.classList.add('hide'));
        locationsContainers.forEach(container => container.classList.add('hide'));
        addLocationButtons.forEach(container => container.classList.add('hide'));
      }
      inputReportingPercentage?.addEventListener('change', () => {
        setTimeout(() => {
          let percentage = inputReportingPercentage.value
          console.log('percentage', percentage, inputReportingPercentage, inputReportingPercentage.value, event.reportedlocations);
          if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100) {
            entityContainers.forEach(container => container.classList.remove('hide'));
            locationsContainers.forEach(container => container.classList.remove('hide'));
            addLocationButtons.forEach(container => container.classList.remove('hide'));
          } else {
            entityContainers.forEach(container => container.classList.add('hide'));
            locationsContainers.forEach(container => container.classList.add('hide'));
            addLocationButtons.forEach(container => container.classList.add('hide'));
          }
          if ((percentage != null && parseInt(percentage) == 0) || event.docsOptional.length > 0) {
            (eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents';
          } else {
            (eventDetailReportingContainer.querySelector('#input-label-docs') as HTMLLabelElement).innerHTML = 'Supporting Documents*';
          }
          if (percentage != null && percentage.length > 0 && parseInt(percentage) < 100 && (event.reportedlocations == "" || event.reportedlocations == "[]")) {
            event.percentage = percentage
            event.reportedlocations = JSON.stringify([""])
            event.reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;
            event.dateofcompletion = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
            event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
            console.log('rendering list reporting', event.percentage, event.reportedlocations)
            this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, eventDetailContainer);
          }
        }, 200);
      })
      let projectUserMap = Util.getProjectUsermap()
      addLocationButtons.forEach((addLocationBtn) => {
        addLocationBtn.addEventListener('click', () => {
          let iconhtml = addLocationBtn.innerHTML
          let index = parseInt(addLocationBtn.id.split('-')[4])
          console.log('button clicked', iconhtml, addLocationBtn.id);
          if (iconhtml == "add") {
            console.log('this.reportedLocationsVals', this.reportedLocationsVals)
            this.reportedLocationsVals.push("");
          } else {
            this.reportedLocationsVals.splice(index, 1);
          }
          event.percentage = inputReportingPercentage.value;
          event.reportedlocations = JSON.stringify(this.reportedLocationsVals)
          if (this.reportedLocationsVals.length == 0) {
            event.percentage = "100";
          }
          console.log('rendering list reporting', this.reportedLocationsVals, event.percentage, event.reportedlocations)
          event.reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;
          event.dateofcompletion = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
          event.documents = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
          this.renderEventDetailReporting(eventDetailReportingContainer, event, mmddyyyy, eventDetailContainer);
        })
      })

      for (let indexRepLoc = 0; indexRepLoc < this.reportedLocationsVals.length; indexRepLoc++) {
        console.log('AddingEntities', indexRepLoc)
        let selectReportingEntity = eventDetailReportingContainer.querySelector('#input-reporter-entity-' + indexRepLoc) as HTMLSelectElement;
        let selectReportingLocation = eventDetailReportingContainer.querySelector('#input-reporter-location-' + indexRepLoc) as HTMLSelectElement;
        selectReportingEntity.innerHTML = '';
        let defaultOption = new Option("Select Entity", "", true, true)
        defaultOption.disabled = true
        selectReportingEntity.add(defaultOption)
        for (let country of Object.keys(projectUserMap)) {
          if (country == "roles") {
            continue;
          }
          for (let entity of Object.keys(projectUserMap[country])) {
            let entityName = entity.split(';')[0].replace(/ *\([^)]*\) */g, "")
            let option = new Option(entityName, entity)
            selectReportingEntity.add(option);
          }
        }
        selectReportingEntity.addEventListener('change', (e: any) => {
          selectReportingLocation.innerHTML = ''
          let defaultOption = new Option("Select Location", "", true, true)
          defaultOption.disabled = true
          selectReportingLocation.add(defaultOption)
          for (let country of Object.keys(projectUserMap)) {
            if (country == "roles") {
              continue;
            }
            for (let entity of Object.keys(projectUserMap[country])) {
              if (entity.indexOf(e.target.value) < 0) {
                continue;
              }
              for (let location of Object.keys(projectUserMap[country][entity])) {
                let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "")
                let option = new Option(locationName, location)
                selectReportingLocation.add(option);
              }
            }
          }
          (eventDetailReportingContainer.querySelector('#reporting-location-container-' + indexRepLoc) as HTMLDivElement).classList.remove('hide')
          selectReportingLocation.value = event.reportedlocations != null ? (Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations) : "";
        })

        if (selectReportingLocation.innerHTML == '') {
          let defaultOption = new Option("Select Location", "", true, true)
          defaultOption.disabled = true
          selectReportingLocation.add(defaultOption)
          // for (let country of Object.keys(projectUserMap)) {
          //   if (country == "roles") {
          //     continue;
          //   }
          //   for (let entity of Object.keys(projectUserMap[country])) {
          //     for (let location of Object.keys(projectUserMap[country][entity])) {
          //       let locationName = location.split(';')[0].replace(/ *\([^)]*\) */g, "")
          //       let option = new Option(locationName, location)
          //       selectReportingLocation.add(option);
          //       break;
          //     }
          //     break;
          //   }
          //   break;
          // }
        }
        selectReportingLocation.addEventListener('change', (e: any) => {
          if (selectReportingEntity.value == "") {
            return;
          }
          let index = parseInt(e.target.id.split('-')[3])
          this.reportedLocationsVals[index] = e.target.value
        })
        if (event.reportedlocations != null && event.reportedlocations.length > indexRepLoc) {
          console.log('setting reportedlocations', event.reportedlocations)
          let tempReportedLocation = Util.isJSONParsable(event.reportedlocations) ? JSON.parse(event.reportedlocations)[indexRepLoc] : event.reportedlocations
          for (let country of Object.keys(projectUserMap)) {
            if (country == "roles") {
              continue;
            }
            for (let entity of Object.keys(projectUserMap[country])) {
              let flagSetVal = false;
              for (let location of Object.keys(projectUserMap[country][entity])) {
                if (tempReportedLocation.indexOf(location) >= 0) {
                  selectReportingEntity.value = entity;
                  const changeEvent = new Event('change', { bubbles: true });
                  selectReportingEntity.dispatchEvent(changeEvent)
                  selectReportingLocation.value = location;
                  flagSetVal = true;
                  break;
                }
              }
              if (flagSetVal) {
                break;
              }
            }
          }
        } else {
          selectReportingEntity.value = "";
          selectReportingLocation.value = "";
        }
      }

      eventDetailReportingContainer.querySelector('#button-uploader-submit-approve')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = (eventDetailReportingContainer.querySelector('#input-approver-comments') as HTMLInputElement).value;
        console.log('comments', comments, JSON.stringify(event.comments))
        const approved = (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked;
        let currStatus = this.getCompletenessStatus(event);
        let newEvent = { ...event };
        newEvent.comments = comments;
        newEvent.approved = approved;
        let newStatus = this.getCompletenessStatus(newEvent);
        if (currStatus == newStatus) {
          buttonClick.innerHTML = "Save"
          this.setError(approved ? 'Already Approved!' : 'Already Rejected!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);
          return;
        }
        let flagBulk = false;
        if (this.selectedItemIds.length <= 1) {
          console.log('selectedevent', JSON.stringify(event));
          if (await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) {
            if (this.mode != "next") {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                  this.events[mmdd][p].approved = approved
                  console.log('selected event', this.events[mmdd][p]);
                  this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                  if (approved) {
                    this.events[mmdd][p].dateofcompletion = new Date().getTime() + ""
                  }
                }
              }
            }
            if (this.recentlyReported[mmdd] == null) {
              this.recentlyReported[mmdd] = []
            }
            this.recentlyReported[mmdd].push(event)
          }
        } else {
          let bulkBodyReview = []
          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            let entityid = selectedId.split('-')[7].replace(/_/g, '-');
            let locationid = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

            //console.log(entityId, locationId, eventId, mmddyyyy);
            let yearStr = this.getFinancialYear(mmddyyyy)
            bulkBodyReview.push({
              "mmddyyyy": mmddyyyy,
              "projectid": this.projectId,
              "type": "review",
              "eventid": eventId,
              "comments": comments,
              "approved": approved,
              "entityid": entityid,
              "locationid": locationid,
              "username": this.userName,
              "userid": this.userProfileId,
              "userrole": this.myRole,
              "year": yearStr,
              "module": event.module ?? "compliance"
            })
            // await this.uploadReview(entityId, locationId, mmddyyyy, eventId, comments, approved)

            // this.setSuccess("Updating " + (k + 1) + "/" + this.selectedItemIds.length + ", please wait...");
            // await this.sleep(2000);
            // this.clearMessages();

          }
          await this.uploadReviewsBulk(bulkBodyReview);

          for (var k = 0; k < this.selectedItemIds.length; k++) {

            const selectedId = this.selectedItemIds[k];
            //console.log('selectedid', selectedId);
            let entityid = selectedId.split('-')[7].replace(/_/g, '-');
            let locationid = selectedId.split('-')[8].replace(/_/g, '-');
            const eventId = selectedId.split('-')[9].replace(/_/g, '-');
            mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
            let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
            if (this.mode == "next") {
              for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityid) {
                  flagBulk = true;
                  this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                }
              }
            } else {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationid && this.events[mmdd][p].entityid == entityid) {

                  this.events[mmdd][p].isbulk = true
                  flagBulk = true
                  if (this.recentlyReported[mmdd] == null) {
                    this.recentlyReported[mmdd] = []
                  }
                  this.recentlyReported[mmdd].push(this.events[mmdd][p])
                }
              }
            }
          }
        }

        if (this.mode == "next") {
          // this.fetchNext(this.nextPage)
          // this.renderRoleTabsNext(this.nextPage)
          buttonClose?.dispatchEvent(new Event('click'))
          this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
        } else {
          // if(this.getCurrentTab() == this.TAB_CUSTOM) {
          //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
          // } else 
          if (this.getCurrentTab() == this.TAB_FIND) {
            const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
            this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
          } else {
            if (this.selectedItemIds.length > 0) {
              await this.fetchBulkReportingData();
            }
            console.log('events', this.events);
            buttonClose?.dispatchEvent(new Event('click'))
            this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
          }
        }

      });

      eventDetailReportingContainer.querySelector('#button-uploader-submit-audit')?.addEventListener('click', async (ev: any) => {
        let buttonClick = ev.target as HTMLButtonElement
        buttonClick.innerHTML = "Saving..."
        const comments = (eventDetailReportingContainer.querySelector('#input-auditor-comments') as HTMLInputElement).value;
        const approved = (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked;

        if (comments.trim().length === 0) {
          buttonClick.innerHTML = "Save"
          this.setError('Comments cannot be blank!');
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        } else {
          let flagBulk = false;
          if (this.selectedItemIds.length <= 1) {
            if (await this.uploadAudit(event.entityid, event.locationid, mmddyyyy, event["id"], comments, approved, event.module ?? "compliance")) {
              for (var p = 0; p < this.events[mmdd].length; p++) {
                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                  this.events[mmdd][p].approved = approved
                  this.events[mmdd][p].comments.push({ 'author': 'Auditor', 'comment': comments + ` (Approved: ${approved ? 'Yes' : 'No'})`, 'timestamp': new Date().toString() })
                  this.events[mmdd][p].lastupdated = new Date().toString()
                  if (approved) {
                    this.events[mmdd][p].dateofcompletion = new Date().getTime() + ""
                  }
                }
              }
              if (this.recentlyReported[mmdd] == null) {
                this.recentlyReported[mmdd] = []
              }
              this.recentlyReported[mmdd].push(event)
            }
          } else {
            let bulkBodyAudit = []
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);

              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

              //console.log(entityId, locationId, eventId, mmddyyyy);
              bulkBodyAudit.push({
                "mmddyyyy": mmddyyyy,
                "projectid": this.projectId,
                "type": "audit",
                "eventid": eventId,
                "comments": comments,
                "approved": approved,
                "entityid": entityId,
                "locationid": locationId,
                "username": this.userName,
                "userid": this.userProfileId,
                "userrole": this.myRole,
                "year": this.calendarStartYYYY,
                "module": event.module ?? "compliance"
              })
              // await this.uploadAudit(entityId, locationId, mmddyyyy, eventId, comments, approved);

            }

            await this.uploadAuditsBulk(bulkBodyAudit);
            for (var k = 0; k < this.selectedItemIds.length; k++) {

              const selectedId = this.selectedItemIds[k];
              //console.log('selectedid', selectedId);
              let entityId = selectedId.split('-')[7].replace(/_/g, '-');
              let locationId = selectedId.split('-')[8].replace(/_/g, '-');
              const eventId = selectedId.split('-')[9].replace(/_/g, '-');
              mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
              let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
              if (this.mode == "next") {
                for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                  if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) {
                    flagBulk = true;
                    this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                  }
                }
              } else {
                for (var p = 0; p < this.events[mmdd].length; p++) {
                  if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {

                    this.events[mmdd][p].isbulk = true
                    flagBulk = true;
                    if (this.recentlyReported[mmdd] == null) {
                      this.recentlyReported[mmdd] = []
                    }
                    this.recentlyReported[mmdd].push(this.events[mmdd][p])
                  }
                }
              }
            }
          }
          if (this.mode == "next") {
            // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
            buttonClose?.dispatchEvent(new Event('click'))
            this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
          } else {
            // if(this.getCurrentTab() == this.TAB_CUSTOM) {
            //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
            // } else 
            if (this.getCurrentTab() == this.TAB_FIND) {
              const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
              this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
            } else {
              if (this.selectedItemIds.length > 0) {
                await this.fetchBulkReportingData();
              }
              buttonClose?.dispatchEvent(new Event('click'))
              this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk);
              // if(currentColumnButton != null) {
              //   currentColumnButton.click();
              // }
            }
          }

        }



      });

      if (this.myRole == this.TAB_REPORTER || this.myRole == this.TAB_FUNCTION_HEAD) {
        if (event.approved) {

          if ((eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) {
            (eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'hidden';
          }
          if ((eventDetailReportingContainer.querySelector('#reporting-suggestions-container') as HTMLElement) != null) {
            (eventDetailReportingContainer.querySelector('#reporting-suggestions-container') as HTMLElement).style.visibility = 'hidden';
          }


        } else {
          let reportingSuggestionMoreButton = eventDetailReportingContainer.querySelector('#reporting-suggestions-more') as HTMLButtonElement;
          reportingSuggestionMoreButton?.addEventListener('click', (e) => {
            (e.target as HTMLButtonElement).style.display = 'none';
            let reportingSuggestions = eventDetailReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf<HTMLDivElement>;
            reportingSuggestions.forEach(suggestion => {
              suggestion.classList.remove('hide');
            })
          })
          let reportingSuggestionButtons = eventDetailReportingContainer.querySelectorAll('.reporting-suggestion') as NodeListOf<HTMLDivElement>;
          for (let reportingSuggestionButton of reportingSuggestionButtons) {
            reportingSuggestionButton.addEventListener('click', (e) => {
              let button = e.currentTarget as HTMLDivElement;
              (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value = ((eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value + " " + button.innerHTML).trim();
              (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).dispatchEvent(new Event('change', { bubbles: true }));
            })
          }
          if ((eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement) != null) {


            (eventDetailReportingContainer.querySelector('#button-uploader-submit-report') as HTMLElement).style.visibility = 'visible';

            eventDetailReportingContainer.querySelector('#button-uploader-submit-report')?.addEventListener('click', async (ev: any) => {
              let buttonClick = ev.target as HTMLButtonElement
              buttonClick.innerHTML = "Saving..."
              const reportercomments = (eventDetailReportingContainer.querySelector('#input-reporter-comments') as HTMLInputElement).value;

              //console.log('reporter comments 1', reportercomments);

              const reporterdoc = (eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value.length > 0 ? (new Date((eventDetailReportingContainer.querySelector('#input-reporter-doc') as HTMLInputElement).value).getTime() + "") : "";
              let docs: any[] = [];

              //console.log('reporter comments 2', reportercomments);

              // if(docsOptional.length === 0) {
              let percentage: string = "100";
              if ((eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement) != null) {
                percentage = (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value
              }
              docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
              // }
              let flag = false;
              do {
                if (docs.length > 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments) > -1) {
                  for (let doc of docs) {
                    if ((doc.jobId == null || doc.jobId.length === 0) && (doc.ext.toLowerCase() == 'pdf' || doc.ext.toLowerCase() == 'png' || doc.ext.toLowerCase() == 'jpeg' || doc.ext.toLowerCase() == 'jpg')) {
                      flag = false
                    } else {
                      flag = true;
                    }
                  }
                } else {
                  flag = true;
                }
                if (flag === false) {
                  await this.sleep(1000);
                  console.log('waiting for docs', docs);
                  docs = (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.selectedValues();
                }
              } while (flag === false);
              //console.log('docs', docs);
              let reportformatvalues: string = "";
              let reportformatschema: string = "";
              if (this._SfReporting[0] != null) {
                reportformatvalues = JSON.stringify((this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.selectedValues()) ?? "";
                reportformatschema = (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting)!.configjson ?? "";
              }

              console.log('percentage', percentage, (eventDetailReportingContainer.querySelector('#input-reporter-percentage') as HTMLInputElement).value);
              if (Number.isNaN(parseInt(percentage)) || parseInt(percentage) < 0 || parseInt(percentage) > 100) {

                //console.log('reporter comments 3', reportercomments);
                buttonClick.innerHTML = "Save"
                this.setError('Invalid Percentage!');
                setTimeout(() => {
                  this.clearMessages();
                }, 3000);

              } else {
                if (docs.length == 0 && event.docsOptional != null && event.docsOptional.length === 0 && parseInt(percentage) > 0 && this.reportingSuggestionsNotApplicable.indexOf(reportercomments) < 0) {

                  //console.log('reporter comments 3', reportercomments);
                  buttonClick.innerHTML = "Save"
                  this.setError('No documents uploaded!');
                  setTimeout(() => {
                    this.clearMessages();
                  }, 3000);

                } else {

                  //console.log('reporterdoc', reporterdoc);

                  if (reporterdoc.length === 0) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion not selected!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else if ((new Date(mmddyyyy).getTime() - (this.reportingLimitDays * 24 * 60 * 60 * 1000)) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError(`Reporting allowed only within ${this.reportingLimitDays} days before due date`);
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);
                  } else if (parseInt(reporterdoc) > new Date().getTime()) {
                    buttonClick.innerHTML = "Save"
                    this.setError('Date of completion cannot be in future!');
                    setTimeout(() => {
                      this.clearMessages();
                    }, 3000);

                  } else {

                    //console.log('makerscheckers 1', reportercomments);

                    if (reportercomments.trim().length === 0) {
                      buttonClick.innerHTML = "Save"
                      this.setError('Comments cannot be blank!');
                      setTimeout(() => {
                        this.clearMessages();
                      }, 3000);

                    } else {
                      let flagBulk = false;
                      // let reportedlocations = selectReportingLocation?.value ?? "";
                      let reportedlocations = "[]";
                      if (parseInt(percentage) !== 100) {
                        let selectReportedLocations = (eventDetailReportingContainer.querySelectorAll('.input-reporter-location') as NodeListOf<HTMLSelectElement>);
                        for (let selectReportedLocation of selectReportedLocations) {
                          reportedlocations = JSON.stringify([...JSON.parse(reportedlocations), selectReportedLocation.value])
                        }
                      }
                      if (this.selectedItemIds.length <= 1) {

                        if (await this.uploadReport(event.entityid, event.locationid, mmddyyyy, event["id"], reportercomments, reporterdoc, docs, event, reportformatvalues, reportformatschema, event.module ?? "compliance", percentage, event.makercheckers, reportedlocations)) {

                          if (this.mode != "next") {
                            for (var p = 0; p < this.events[mmdd].length; p++) {
                              if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                                this.events[mmdd][p].documents = docs
                                this.events[mmdd][p].percentage = percentage
                                this.events[mmdd][p].reportedlocations = reportedlocations
                                this.events[mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                                this.events[mmdd][p].lastupdated = new Date().toString()
                              }
                            }

                            if (event.makercheckers.length > 0) {

                              // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
                              for (var p = 0; p < this.events[mmdd].length; p++) {
                                if (this.events[mmdd][p].id == event.id && this.events[mmdd][p].locationid == event.locationid && this.events[mmdd][p].entityid == event.entityid) {
                                  this.events[mmdd][p].approved = true
                                  // this.events[mmdd][p].documents = docs
                                  this.events[mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                                  this.events[mmdd][p].lastupdated = new Date().toString()
                                }
                              }
                            }
                            if (this.recentlyReported[mmdd] == null) {
                              this.recentlyReported[mmdd] = []
                            }
                            this.recentlyReported[mmdd].push(event)
                            console.log('recently reported', this.recentlyReported)

                          } else {
                            for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                              if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) {
                                this.nextEvents[this.nextTabRole][mmdd][p].documents = docs
                                this.nextEvents[this.nextTabRole][mmdd][p].percentage = percentage
                                this.nextEvents[this.nextTabRole][mmdd][p].reportedlocations = reportedlocations
                                this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Reporter', 'comment': reportercomments + ` (Documents Saved: ${docs.length}})`, 'timestamp': new Date().toString() })
                                this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString()
                              }
                            }

                            if (event.makercheckers.length > 0) {

                              // await this.uploadReview(event.entityid, event.locationid, mmddyyyy, event["id"], "Auto approved", true, event.module ?? "compliance");
                              for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                                if (this.nextEvents[this.nextTabRole][mmdd][p].id == event.id && this.nextEvents[this.nextTabRole][mmdd][p].locationid == event.locationid && this.nextEvents[this.nextTabRole][mmdd][p].entityid == event.entityid) {
                                  this.nextEvents[this.nextTabRole][mmdd][p].approved = true
                                  // this.events[mmdd][p].documents = docs
                                  this.nextEvents[this.nextTabRole][mmdd][p].comments.push({ 'author': 'Approver', 'comment': `Auto approved (Approved: Yes})`, 'timestamp': new Date().toString() })
                                  this.nextEvents[this.nextTabRole][mmdd][p].lastupdated = new Date().toString()
                                }
                              }
                            }
                            if (this.recentlyReported[mmdd] == null) {
                              this.recentlyReported[mmdd] = []
                            }
                            this.recentlyReported[mmdd].push(event)
                            console.log('recently reported', this.recentlyReported)
                          }
                        }
                      } else {
                        let bulkBody = []
                        let bulkBodyReview = []
                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);

                          const makercheckersL = selectedId.split('-')[5];
                          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];

                          //console.log(entityId, locationId, eventId, mmddyyyy);

                          let yearStr = this.getFinancialYear(mmddyyyy)
                          bulkBody.push({
                            "mmddyyyy": mmddyyyy,
                            "projectid": this.projectId,
                            "type": "report",
                            "eventid": eventId,
                            "comments": reportercomments,
                            "dateofcompletion": reporterdoc,
                            "percentage": percentage,
                            "reportedlocations": reportedlocations,
                            "entityid": entityId,
                            "locationid": locationId,
                            "event": null,
                            "docs": JSON.stringify(docs),
                            "username": this.userName,
                            "reportformatvalues": reportformatvalues,
                            "reportformatschema": reportformatschema,
                            "userid": this.userProfileId,
                            "userrole": this.myRole,
                            "year": yearStr,
                            "module": event.module ?? "compliance",
                            "makercheckers": (parseInt(makercheckersL) > 0) ? ["makercheckers"] : null
                          })


                        }

                        if (bulkBody.length > 0) {
                          await this.uploadReportsBulk(bulkBody, bulkBodyReview.length == 0);
                        }


                        for (var k = 0; k < this.selectedItemIds.length; k++) {

                          const selectedId = this.selectedItemIds[k];
                          //console.log('selectedid', selectedId);
                          let entityId = selectedId.split('-')[7].replace(/_/g, '-');
                          let locationId = selectedId.split('-')[8].replace(/_/g, '-');
                          const eventId = selectedId.split('-')[9].replace(/_/g, '-');
                          mmddyyyy = selectedId.split('-')[10] + '/' + selectedId.split('-')[11] + '/' + selectedId.split('-')[12];
                          let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
                          if (this.mode == "next") {
                            for (var p = 0; p < this.nextEvents[this.nextTabRole][mmdd].length; p++) {
                              if (this.nextEvents[this.nextTabRole][mmdd][p].id == eventId && this.nextEvents[this.nextTabRole][mmdd][p].locationid == locationId && this.nextEvents[this.nextTabRole][mmdd][p].entityid == entityId) {
                                flagBulk = true;
                                this.nextEvents[this.nextTabRole][mmdd][p].isbulk = true
                                if (this.recentlyReported[mmdd] == null) {
                                  this.recentlyReported[mmdd] = []
                                }
                                this.recentlyReported[mmdd].push(this.nextEvents[this.nextTabRole][mmdd][p])
                              }
                            }
                          } else {
                            for (var p = 0; p < this.events[mmdd].length; p++) {
                              if (this.events[mmdd][p].id == eventId && this.events[mmdd][p].locationid == locationId && this.events[mmdd][p].entityid == entityId) {
                                flagBulk = true;
                                this.events[mmdd][p].isbulk = true
                                if (this.recentlyReported[mmdd] == null) {
                                  this.recentlyReported[mmdd] = []
                                }
                                this.recentlyReported[mmdd].push(this.events[mmdd][p])
                              }
                            }
                          }
                        }
                      }

                      if (this.mode == "next") {
                        // this.fetchNext(this.nextPage, this.nextTabRole, this.nextTabStatus)
                        buttonClose?.dispatchEvent(new Event('click'))
                        this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
                      } else {
                        // if(this.getCurrentTab() == this.TAB_CUSTOM) {
                        //   this.processDateSelection((this._SfCustomContainer as HTMLDivElement));
                        // } else 
                        if (this.getCurrentTab() == this.TAB_FIND) {
                          const searchString = ((this._SfFindContainer as HTMLDivElement).querySelector('#stream-search') as HTMLInputElement).value;
                          this.processFindSelection((this._SfFindContainer as HTMLDivElement), searchString);
                        } else {
                          if (this.selectedItemIds.length > 0) {
                            await this.fetchBulkReportingData();
                          }
                          buttonClose.dispatchEvent(new Event('click'))
                          this.renderAppropriateStream(this.sdate, this.edate, true, flagBulk)
                          // if(currentColumnButton != null) {
                          //   currentColumnButton.click();
                          // }
                        }
                      }
                    }
                  }
                }
              }
            });

          }

        }

      }

      if (this._SfUploader[0] != null) {
        if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
          (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
        }
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisInProgress', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);

          if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
            (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "block"
          }
        });
        this._SfUploader[0].querySelector('#uploader').addEventListener('analysisCompleted', (_ev: any) => {
          console.log('uploader analysisInProgress', _ev);
          if ((eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement) != null) {
            (eventDetailReportingContainer.querySelector('.uploader-analysis-message') as HTMLDivElement).style.display = "none"
          }
        });


        console.log('documentType checking', event.documenttype);

        if (event.documenttype != null) {
          if (Array.isArray(event.documenttype)) {
            (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype[0] ?? "";
          } else {
            (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documenttype;
          }
        } else if (event.documentType != null) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = event.documentType;
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.docType = "";
        }

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify([]);
        console.log('uploader', (this._SfUploader[0].querySelector('#uploader') as SfIUploader));
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = 0;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();

        if (docs.length > 0) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.prepopulatedInputArr = JSON.stringify(docs);
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.current = docs.length;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        if (this.myRole == this.TAB_APPROVER || event.approved) {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = true;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        } else {
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.readOnly = false;
          (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        }

        const dataPassthrough = {
          projectId: this.projectId,
          countryId: this.countryId,
          entityId: event.entityid,
          locationId: event.locationid,
          mmddyyyy: mmddyyyy,
          complianceId: event['id'],
          path: "uploadextract"
        };

        const callbackUrlHost = "8icpy39ru0.execute-api.us-east-1.amazonaws.com";
        const callbackUrlPath = "test/uploadextract";

        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.projectId = this.projectId;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.dataPassthrough = JSON.stringify(dataPassthrough);
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlHost = callbackUrlHost;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.callbackUrlPath = callbackUrlPath;
        (this._SfUploader[0].querySelector('#uploader') as SfIUploader)!.loadMode();
        console.log('uploader prepopulate', (this._SfUploader[0].querySelector('#uploader') as SfIUploader).prepopulatedInputArr, (this._SfUploader[0].querySelector('#uploader') as SfIUploader).extract)

      }



      //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
      if (this.myRole == this.TAB_APPROVER || this.myRole == this.TAB_VIEWER || this.myRole == this.TAB_AUDITOR || this.myRole == this.TAB_FUNCTION_HEAD) {
        //console.log('approved 1', event["approved"], this.myRole, this.TAB_APPROVER);
        if (event["approved"] != null) {
          if (event["approved"] === true) {
            //console.log('approved 2', event["approved"], this.myRole, this.TAB_APPROVER);
            if ((eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = true;
            }
            if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
              (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = false;
            }
          } else {
            if ((eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement) != null) {
              (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement)!.checked = false;
            }
            if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
              (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement)!.checked = true;
            }
          }
        } else {
          if (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement != null) {
            (eventDetailReportingContainer.querySelector('#input-approve-yes') as HTMLInputElement).checked = false;
          }
          if ((eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement) != null) {
            (eventDetailReportingContainer.querySelector('#input-approve-no') as HTMLInputElement).checked = true;
          }
        }
      }
    }
    if (event['reportformat'] != null && event['reportformat'].length > 0) {
      this.fetchReportFormat(eventDetailReportingContainer, reportformatName, event['reportformatschema'] ?? "", event['reportformatvalues'] ?? "");
    }
  }

  renderCalendar = () => {

    //console.log('redering calendar', this.events);

    var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);

    var html = '';

    for (var i = 0; i < 12; i++) {

      const monthStatus = this.getMonthStatus(startDate.getMonth(), startDate.getFullYear());
      console.log('monthstatus', monthStatus, startDate);

      const partApproved = this.COLOR_APPROVED + ' 0%, ' + this.COLOR_APPROVED + ' ' + parseInt(monthStatus['percApproved'] + '') + '%';
      const partPendingApproval = this.COLOR_PENDING_APPROVAL + ' ' + parseInt(monthStatus['percApproved'] + '') + '%, ' + this.COLOR_PENDING_APPROVAL + ' ' + (monthStatus['percApproved'] + (monthStatus['percPendingApproval']) + '') + '%';
      const partRejected = this.COLOR_REJECTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + '') + '%, ' + this.COLOR_REJECTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + monthStatus['percRejected'] + '') + '%';
      const partNotStarted = this.COLOR_NOT_STARTED + ' ' + (monthStatus['percApproved'] + monthStatus['percPendingApproval'] + monthStatus['percRejected'] + '') + '%, ' + this.COLOR_NOT_STARTED + ' ' + 100 + '%';


      html += '<div class="calendar-item d-flex flex-col flex-grow" part="calendar-month" style="background: linear-gradient(to right, ' + partApproved + ',' + partPendingApproval + ',' + partRejected + ',' + partNotStarted + ');">';
      html += '<div part="bg-calendar" class="d-flex justify-between align-center p-10">';
      html += '<div part="month-title" class="title-item">' + this.monthNames[startDate.getMonth()] + '&nbsp;&nbsp;' + startDate.getFullYear() + '</div>';
      html += '<button id="calendar-button-' + i + '" part="button-icon-small-light" class="title-item material-icons">open_in_new</button>'
      html += '</div>';
      html += this.insertDayNames();
      html += this.insertDates(startDate.getMonth(), startDate.getFullYear());
      html += '</div>';

      startDate.setMonth(startDate.getMonth() + 1);

    }

    (this._SfCalendarContainer as HTMLDivElement).innerHTML = html;

    for (var i = 0; i < 12; i++) {

      (this._SfCalendarContainer as HTMLDivElement).querySelector('#calendar-button-' + i)?.addEventListener('click', (ev: any) => {

        const id = (ev.target as HTMLButtonElement).id.split("-")[2];
        //console.log('render stream', id);
        this.enableStream();
        this.renderTabs(this.TAB_STREAM);
        this.renderStream(parseInt(id), false, false);

      })

    }

  }

  matchesOnBoardingFilter = (country: string, state: string, subcategory: string, statute: string) => {

    // console.log('matchingonboarding','country=' + country, 'state=' + state, 'subcategory=' + subcategory, '-' + statute + '-');

    let matchesCountry = false;

    for (var i = 0; i < this.getfilterOnboarding().length; i++) {

      matchesCountry = false;

      if (country.toLowerCase().trim().indexOf(this.getfilterOnboarding()[i].country.trim().toLowerCase()) >= 0) {

        matchesCountry = true;

        let matchesState = false;
        let matchesSubcategory = false;

        //console.log('matchingonboarding', matchesCountry, statute);

        for (var j = 0; j < this.getfilterOnboarding()[i].states.length; j++) {

          //if(state.toLowerCase().indexOf(this.getfilterOnboarding()[i].states[j].toLowerCase()) >= 0) {
          if (this.getfilterOnboarding()[i].states[j].toLowerCase().indexOf(state.toLowerCase()) >= 0) {
            matchesState = true;
            break;
          }

        }

        //console.log('matchingonboarding', matchesState, statute);

        for (var j = 0; j < this.getfilterOnboarding()[i].subcategories.length; j++) {

          if (subcategory.toLowerCase().trim().indexOf(this.getfilterOnboarding()[i].subcategories[j].toLowerCase().trim()) >= 0) {
            matchesSubcategory = true;
          }

        }

        //console.log('matchingonboarding', matchesSubcategory, statute);

        let isNotExcludedStatute = true;

        if (this.getfilterOnboarding()[i].excludestatutes != null) {
          if (this.getfilterOnboarding()[i].excludestatutes.includes(statute.trim())) {
            isNotExcludedStatute = false;
          }
        }

        let isIncludedStatute = false;


        if (this.getfilterOnboarding()[i].includestatutes != null) {
          if (this.getfilterOnboarding()[i].includestatutes.includes(statute.trim())) {
            isIncludedStatute = true;
          }
        }

        if (statute == "Gujarat Goods and Services Tax Act, 2017 + Gujarat Goods and Services Tax Rules, 2017") {
          console.log('isIncludedStatute', isIncludedStatute);
        }
        //console.log('matchingonboarding', isIncludedStatute, this.getfilterOnboarding()[i].includestatutes, '='+statute);

        if (matchesCountry && matchesState && matchesSubcategory && isNotExcludedStatute) {
          //console.log('matchingonboarding return true');
          return true;
        }

        if (matchesCountry && isIncludedStatute) {
          //console.log('matchingonboarding return true');
          return true;
        }

      }

    }

    //console.log('matchingonboarding return true');
    return false;

  }

  applyAndReloadTagging = (e: any, colName: string, taggingArray: any, sourceArray: any, divElement: any) => {

    const selectedIndex = e.currentTarget.id.split('-')[1];

    // taggingArray.data.mappings.mappings = [];

    const tempArray = [];
    console.log('selectedindexchecking 1', this.selectedCbs)
    for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) {

      console.log('selectedindexchecking', selectedIndex, count, this.selectedCbs.includes(selectedIndex + ""), this.selectedCbs.includes(count + ""));
      //taggingArray.data.mappings.mappings[count] = sourceArray.data.mappings.mappings[count];
      //taggingArray.data.mappings.mappings.push(sourceArray.data.mappings.mappings[count]);
      tempArray.push(sourceArray.data.mappings.mappings[count]);
      // //console.log('selectedindexchecking', this.selectedCbs, count, this.selectedCbs.includes(selectedIndex), this.selectedCbs.includes(count));
      if (this.selectedCbs.includes(selectedIndex + '') && this.selectedCbs.includes(count + '')) {
        if (((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues != null) {

          if (tempArray[count] == null) tempArray[count] = {};
          tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues();
          // //console.log('selectedindexchecking A');
          // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {};
          // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues();

        } else {

          //console.log('selectedindexchecking B');

          if (tempArray[count] == null) tempArray[count] = {};
          tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value;

          // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {};
          // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value;
        }

      } else {

        if (((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues != null) {

          if (tempArray[count] == null) tempArray[count] = {};
          tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues();


        } else {
          //console.log('selectedindexchecking D');

          if (tempArray[count] == null) tempArray[count] = {};
          tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value;

          // if(taggingArray.data.mappings.mappings[count] == null) taggingArray.data.mappings.mappings[count] = {};
          // taggingArray.data.mappings.mappings[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value;
        }

      }

    }

    taggingArray.data.mappings.mappings = tempArray;
    //console.log('selectedindexchecking', colName, taggingArray);


  }

  applyAndReloadTaggingNew = (e: any, colName: string, taggingArray: any, sourceArray: any, divElement: any) => {

    const selectedIndex = e.currentTarget.id.split('-')[1];
    const tempArray = taggingArray.data.mappings.mappings;
    console.log('sourceArray apply', sourceArray, taggingArray);
    console.log('selectedindexchecking 1', this.selectedCbs)
    for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) {
      console.log('selectedindexchecking', selectedIndex, count, this.selectedCbs.includes(selectedIndex + ""), this.selectedCbs.includes(count + ""));
      // tempArray.push(taggingArray.data.mappings.mappings[count]);

      if (this.selectedCbs.includes(selectedIndex + '') && this.selectedCbs.includes(count + '')) {
        let selectedValues;
        // if(!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof  HTMLInputElement)){
        //   selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues()
        // }else if(((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement) != null){
        //   selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value
        // }
        if (!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof HTMLInputElement) && ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues() != null) {

          if (tempArray[count] == null) tempArray[count] = {};
          if (colName == "countries" || colName == "entities" || colName == "locations") {
            selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues()
            if (selectedValues == null || selectedValues.length == 0) {
              // tempArray[count] = {};
              tempArray[count][colName] = ""
              if (colName == "countries") {
                tempArray[count]["countryname"] = ""
                tempArray[count]["countryid"] = ""
              }
              if (colName == "entities") {
                tempArray[count]["entityname"] = ""
                tempArray[count]["entityid"] = ""
              }
              if (colName == "locations") {
                tempArray[count]["locationname"] = ""
                tempArray[count]["locationid"] = ""
              }
              console.log('deleting1', tempArray, JSON.stringify(selectedValues))
            } else {
              tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues();
              if (colName == "countries") {
                tempArray[count]["countryname"] = selectedValues[0].split(';')[0]
                tempArray[count]["countryid"] = selectedValues[0].split(';')[1]
              }
              if (colName == "entities") {
                tempArray[count]["entityname"] = selectedValues[0].split(';')[0]
                tempArray[count]["entityid"] = selectedValues[0].split(';')[1]
              }
              if (colName == "locations") {
                tempArray[count]["locationname"] = selectedValues[0].split(';')[0]
                tempArray[count]["locationid"] = selectedValues[0].split(';')[1]
              }
            }

          } else {
            tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as SfIForm).selectedValues();
          }
        } else {

          if (tempArray[count] == null) tempArray[count] = {};
          tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) as HTMLInputElement).value;
        }

      } else {

        if (!((divElement as HTMLDivElement).querySelector('#tags-' + selectedIndex) instanceof HTMLInputElement) && ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues() != null) {

          if (tempArray[count] == null) tempArray[count] = {};
          if (colName == "countries" || colName == "entities" || colName == "locations") {
            let selectedValues = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues()
            if (selectedValues == null || selectedValues.length == 0) {
              // tempArray[count] = {};
              tempArray[count][colName] = ""
              if (colName == "countries") {
                tempArray[count]["countryname"] = ""
                tempArray[count]["countryid"] = ""
              }
              if (colName == "entities") {
                tempArray[count]["entityname"] = ""
                tempArray[count]["entityid"] = ""
              }
              if (colName == "locations") {
                tempArray[count]["locationname"] = ""
                tempArray[count]["locationid"] = ""
              }
              console.log('deleting1', tempArray)
            } else {
              tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues();
              if (colName == "countries") {
                tempArray[count]["countryname"] = selectedValues[0].split(';')[0]
                tempArray[count]["countryid"] = selectedValues[0].split(';')[1]
              }
              if (colName == "entities") {
                tempArray[count]["entityname"] = selectedValues[0].split(';')[0]
                tempArray[count]["entityid"] = selectedValues[0].split(';')[1]
              }
              if (colName == "locations") {
                tempArray[count]["locationname"] = selectedValues[0].split(';')[0]
                tempArray[count]["locationid"] = selectedValues[0].split(';')[1]
              }
            }
          } else {
            tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as SfIForm).selectedValues();
          }


        } else {
          //console.log('selectedindexchecking D');

          if (tempArray[count] == null) tempArray[count] = {};
          if (colName == "countries" || colName == "entities" || colName == "locations") {
            // tempArray[count] = {};
            tempArray[count][colName] = ""
            if (colName == "countries") {
              tempArray[count]["countryname"] = ""
              tempArray[count]["countryid"] = ""
            }
            if (colName == "entities") {
              tempArray[count]["entityname"] = ""
              tempArray[count]["entityid"] = ""
            }
            if (colName == "locations") {
              tempArray[count]["locationname"] = ""
              tempArray[count]["locationid"] = ""
            }
            console.log('deleting2', tempArray);
          } else {
            tempArray[count][colName] = ((divElement as HTMLDivElement).querySelector('#tags-' + count) as HTMLInputElement).value;
          }
        }
      }
    }

    taggingArray.data.mappings.mappings = tempArray;
    console.log('selectedindexchecking', colName, taggingArray);

  }

  getDataValue = (jsonData: any, id: string) => {

    let ret: any = null;

    //console.log('pushing up again..', id, jsonData);

    for (var i = 0; i < jsonData.length; i++) {
      if (jsonData[i].id == id) {

        return jsonData[i].data.data;
      }

    }

    return ret;

  }

  getColsValue = (jsonData: any, id: string) => {

    let ret: any = null;

    for (var i = 0; i < jsonData.length; i++) {

      if (jsonData[i].id == id) {
        return jsonData[i].data.cols;
      }

    }

    return ret;

  }

  saveMapping = async (divElement: any, uploadBlock: number, jsonData: any, extraFields: any, searchString: string, uploadFunction: any, refreshFunction: any, saveInBackground: boolean = false, mappedStatutes: Array<any>) => {

    const process = async () => {
      const tableRowArr = (divElement as HTMLDivElement).querySelectorAll('.tablerow') as NodeListOf<HTMLTableRowElement>;
      const checkboxArr = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf<HTMLInputElement>;
      const statuteArr = (divElement as HTMLDivElement).querySelectorAll('.statute') as NodeListOf<SfIElasticText>;
      //console.log(tableRowArr);
      //console.log(checkboxArr);
      //console.log(statuteArr);
      for (var i = 0; i < statuteArr.length; i++) {
        //console.log((statuteArr[i] as SfIElasticText).text);
      }
      let updatedRows = [];
      let jsonArr = [];
      if (uploadBlock < 0) {
        if (mappedStatutes.length == 0) {
          for (var i = 0; i < checkboxArr.length; i++) {

            //console.log('tablerow', (tableRowArr[i] as HTMLTableRowElement));
            if (checkboxArr[i].checked !== true) {
              continue;
            }

            if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') {
            } else {
              updatedRows.push((statuteArr[i] as SfIElasticText).text);
            }
            let cols = JSON.parse(this.getColsValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]);
            let data = JSON.parse(this.getDataValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]);
            var dataToBePushed: any = { id: (statuteArr[i] as SfIElasticText).text, name: data[cols.indexOf('name')], countryname: data[cols.indexOf('country')][0] };
            /* var dataToBePushed = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] };
            for (var j = 0; j < extraFields.length; j++) {
              const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf<SfIMultitextarea>;
              const value = inputArr[k].getValues();
              dataToBePushed.extraFields.push(value);
              if (j === 0) {
                const fields = inputArr[i].getFields();
                dataToBePushed.updatedFields.push(...fields);
              }
            } */

            jsonArr.push(dataToBePushed)
          }
          console.log('jsonArr', jsonArr);
          //console.log('updatedRows', updatedRows);
          // const batchNum = new Date().getTime();
          // await uploadFunction({ "searchstring": searchString, "mappings": jsonArr, "batch": batchNum, "updatedrows": updatedRows });

          await uploadFunction({ "searchstring": searchString, "mappings": jsonArr });
        } else {
          for (var i = 0; i < checkboxArr.length; i++) {

            //console.log('tablerow', (tableRowArr[i] as HTMLTableRowElement));
            if (checkboxArr[i].checked !== true) {
              continue;
            }

            if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') {
            } else {
              updatedRows.push((statuteArr[i] as SfIElasticText).text);
            }
            let cols = JSON.parse(this.getColsValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]);
            let data = JSON.parse(this.getDataValue(jsonData, (statuteArr[i] as SfIElasticText).text)[0]);
            var dataToBePushed: any = { id: (statuteArr[i] as SfIElasticText).text, data: [JSON.stringify(data)], cols: [JSON.stringify(cols)] };
            /* var dataToBePushed = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] };
            for (var j = 0; j < extraFields.length; j++) {
              const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf<SfIMultitextarea>;
              const value = inputArr[k].getValues();
              dataToBePushed.extraFields.push(value);
              if (j === 0) {
                const fields = inputArr[i].getFields();
                dataToBePushed.updatedFields.push(...fields);
              }
            } */

            jsonArr.push(dataToBePushed)
          }
          let jsonObj: { [key: string]: { [key: string]: any } } = {};

          for (let statuteObj of mappedStatutes) {
            let statuteid = statuteObj.id;
            if (jsonObj[statuteid] == null) {
              jsonObj[statuteid] = {};
            }
            for (let mappingObj of jsonArr) {
              console.log('mappingObj', mappingObj.data, statuteid);
              if (mappingObj.data[0].indexOf(statuteid) >= 0) {
                jsonObj[statuteid][mappingObj.id] = mappingObj;
              }
            }
          }

          await uploadFunction(jsonObj, mappedStatutes);
        }

      } else {

        const batchNum = new Date().getTime();
        for (var i = 0; i < checkboxArr.length; i += uploadBlock) {

          if ((tableRowArr[i] as HTMLTableRowElement).style.display == 'none') {
          } else {
            updatedRows.push((statuteArr[i] as SfIElasticText).text);
          }

          jsonArr = [];
          for (var k = i; k < (i + uploadBlock) && k < checkboxArr.length; k++) {

            if ((statuteArr[k] as SfIElasticText) != null) {

              var dataToBePushed: any = { id: (statuteArr[k] as SfIElasticText).text, selected: checkboxArr[k].checked, data: this.getDataValue(jsonData, (statuteArr[k] as SfIElasticText).text), cols: this.getColsValue(jsonData, (statuteArr[k] as SfIElasticText).text), extraFields: [] as string[], updatedFields: [] as string[] };
              for (var j = 0; j < extraFields.length; j++) {
                const inputArr = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf<SfIMultitextarea>;
                const value = inputArr[k].getValues();
                dataToBePushed.extraFields.push(value);
                if (j === 0) {
                  const fields = inputArr[i].getFields();
                  dataToBePushed.updatedFields.push(...fields);
                }
              }
              jsonArr.push(dataToBePushed)

            }

          }

          //console.log('jsonArr', i, jsonArr);
          //console.log('updatedRows', updatedRows);
          await uploadFunction({ "searchstring": searchString, "mappings": jsonArr, "percentage": parseInt(((k * 100) / checkboxArr.length) + ""), "batch": batchNum, "updatedrows": updatedRows });

          // await this.sleepFunction(2000);

        }

      }

      if (!saveInBackground) {
        await this.renderOnboardingTabs();
        refreshFunction(mappedStatutes);
      }
    }

    if (this.disablesave == "yes") {
      return;
    }

    if (saveInBackground) {
      if (this.AUTOSAVE_FLAG) {
        this.AUTOSAVE_FLAG = false;
        setTimeout(async () => {
          await process();
          this.AUTOSAVE_FLAG = true;
          this.setSuccess('Autosaved');
          setTimeout(() => {
            this.clearMessages();
          }, 1000);
        }, 5000);
      }
    } else {
      process();
    }

  }

  saveTagging = async (mapping: any, selectedStatutes: any, uploadFunction: any, refreshFunction: any, saveInBackground: boolean, colName: string) => {
    let refreshTabs = this.renderOnboardingTabs;
    async function process() {

      console.log('Saving...', JSON.stringify(mapping));
      let statuteids = []
      let statutewiseMapping: any = {}
      for (let statutesObj of selectedStatutes) {
        statuteids.push(statutesObj.id);
        statutewiseMapping[statutesObj.id] = {};
        for (let mapObj of mapping.mappings) {
          if (mapObj.statuteid == statutesObj.id) {
            let pushObj = mapObj;
            delete pushObj.statuteid
            let compoundid = mapObj.id

            // if (colName == "countries" || colName == "entities" || colName == "locations") {
            switch (colName) {
              case "countries":
                compoundid = mapObj.countryid + ';' + mapObj.id
                break;

              case "entities":
                compoundid = mapObj.entityid + ';' + mapObj.id;
                break;

              case "locations":
                compoundid = mapObj.locationid + ';' + mapObj.id;
                break;

              default:
                compoundid = mapObj.entityid + ';' + mapObj.locationid + ';' + mapObj.id
                break;
            }
            // if(statutesObj.id == "7a9c19d6-fffd-48ef-b1c5-beabcefc00cb"){
            //   console.log('compoundid', compoundid)
            // }
            // }
            if (compoundid.split(';')[0].length == 0) {
              continue;
            }
            if (statutewiseMapping[statutesObj.id][compoundid] != null) {
              let pushObjOld = statutewiseMapping[statutesObj.id][compoundid];
              pushObj[colName] = [...(pushObjOld[colName] ?? []), ...(mapObj[colName] ?? [])]
            } else {
              statutewiseMapping[statutesObj.id][compoundid] = pushObj;
            }
          }
        }
      }
      console.log('Uploading ...', JSON.stringify(statutewiseMapping));
      await uploadFunction(statutewiseMapping, statuteids);
      if (!saveInBackground) {
        await refreshTabs();
        refreshFunction(selectedStatutes);
      }
    }

    if (this.disablesave == "yes") {
      return;
    }

    if (saveInBackground) {
      if (this.AUTOSAVE_FLAG) {
        this.AUTOSAVE_FLAG = false;
        setTimeout(async () => {
          await process();
          this.AUTOSAVE_FLAG = true;
          this.setSuccess('Autosaved');
          setTimeout(() => {
            this.clearMessages();
          }, 1000);
        }, 10000);
      }
    } else {
      process();
    }

  }

  renderTaggingTable = (divElement: any, sourceArray: any, taggingArray: any, sourceCols: any, uploadFunction: any, refreshFunction: any, colName: any, uniqCols: Array<any>, apiIdDropdown: string, dropdownSearchPhrase: any, mandatoryFields: any, jobs: any, anotherProjection: any, extraFields: Array<string>, _arrFeedbackReference: any, proposedUsersLabel: string, subfilter: string) => {
    // source array is the serialized field mappedcompliances
    // tagging array is the tagged array mappedcountries

    //console.log('divelement', divElement);
    //console.log('sourcearray', sourceArray);
    console.log('taggingarray', taggingArray);
    //console.log('uniqcols', uniqCols);
    //console.log('subfiltervalue', subfilter);
    //console.log('arrFeedbackReference', arrFeedbackReference);

    this.selectedCbs = [];

    if (taggingArray.length === 0 || sourceArray.length === 0) return;

    const foundArr = [];

    if (taggingArray.data.mappings != null && taggingArray.data.mappings.mappings != null) {

      for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) {

        var found = false;

        for (var j = 0; j < sourceArray.data.mappings.mappings.length; j++) {

          var equal = true;

          for (var k = 0; k < uniqCols.length; k++) {

            if (sourceArray.data.mappings.mappings[j] != null && taggingArray.data.mappings.mappings[i] != null) {
              if (sourceArray.data.mappings.mappings[j][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) {
                equal = false;
                // if(taggingArray.data.mappings.mappings.length > 0){
                //   console.log('taggingarray col not found', uniqCols[k], taggingArray.data.mappings.mappings[i])
                // }
              }
            }

          }

          if (equal) {
            found = true;
          }

        }


        if (found) {
          foundArr.push(taggingArray.data.mappings.mappings[i]);
        } else {
          console.log('taggingarray not found', taggingArray.data.mappings.mappings[i], i, sourceArray.data.mappings.mappings[i])
        }

      }
    }
    console.log('taggingarray2', taggingArray.data.mappings.mappings.length + "");
    if (taggingArray.data.mappings == null) {
      taggingArray.data.mappings = {};
    }

    taggingArray.data.mappings.mappings = foundArr;
    let mandatoryPresent = true;

    for (i = 0; i < (mandatoryFields as Array<string>).length; i++) {

      for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {


        if (taggingArray.data.mappings.mappings[j][mandatoryFields[i]] == null) {
          mandatoryPresent = false;
        }

      }

    }

    var tagged = 0;
    var changed = 0
    console.log('taggingarray3', taggingArray.data.mappings.mappings.length + "");
    for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

      if (taggingArray.data.mappings.mappings[j] != null) {
        if (taggingArray.data.mappings.mappings[j][colName] != null && taggingArray.data.mappings.mappings[j][colName].length > 0) {
          tagged++;
        }
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = ""
          for (let [k, col] of uniqCols.entries()) {
            changedId += taggingArray.data.mappings.mappings[j][col];
            if (k < (uniqCols.length - 1)) {
              changedId += ";"
            }
          }
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            changed++;
          }
        }

      }

    }

    // let colCountry = -1;
    // let colState = -1;
    // let colSubcategory = -1;
    // let colStatute = -1;

    const unfilteredDict: any[] = [];

    var html = '';

    var showTable = true;

    html += '<div class="d-flex justify-between flex-wrap align-center"> ';

    // if(jobs && jobs.data) {
    //   html += (jobs.data.status == "0" ? "<div part=\"results-title\" class=\"left-sticky d-flex align-center mb-10 mr-10\"><span class=\"color-not-started material-icons\">schedule</span>&nbsp; Job initizalied</div>" : jobs.data.status == "1" ? "<div  part=\"results-title\" class=\"left-sticky d-flex align-center mb-10 mr-10\"><span class=\"color-pending material-icons\">pending</span>&nbsp; Job in-progress&nbsp; "+parseInt(jobs.data.progress)+"% complete</div>" : "<div part=\"results-title\" class=\"left-sticky d-flex align-center mb-10 mr-10\"><span class=\"color-done material-icons\">check_circle</span>&nbsp; Job complete</div>" );
    //   if(jobs.data.status == "0" || jobs.data.status == "1") {
    //     showTable = false;
    //   }
    // }

    var status = '';
    if (tagged < sourceArray.data.mappings.mappings.length) {
      status = '<span class="color-pending material-icons">pending</span>';
    } else {
      status = '<span class="color-done material-icons">check_circle</span>';
    }

    var mandatoryStatus = '';
    if (!mandatoryPresent) {
      mandatoryStatus = '<span class="color-late-executed material-icons">error</span>&nbsp;&nbsp;Mandatory fields are not present';
    } else {
      mandatoryStatus = '<span class="color-done material-icons">check_circle</span>&nbsp;&nbsp;Mandatory fields are present';
    }

    if (showTable) {

      html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">' + status + '&nbsp;&nbsp;Mapped ' + tagged + ' out of ' + sourceArray.data.mappings.mappings.length + '</h4></div>');

    } else {

      html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">' + status + '&nbsp;&nbsp;Mapped ' + tagged + ' out of ' + sourceArray.data.mappings.mappings.length + '</h4></div>')

    }
    if (changed > 0) {
      html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0"><span class="color-pending material-icons">pending</span>&nbsp;&nbsp;' + changed + ' Items changed</h4></div>')
    }
    html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0">' + mandatoryStatus + '</h4></div>')

    html += ((jobs && jobs.data && (jobs.data.status == "1" || jobs.data.status == "0")) ? '' : '<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="span-extra-filled" class="m-0" part="results-title"></h4></div>')

    html += '<div class="d-flex align-center">';
    // html += '<input part="input" type="text" placeholder="Filter" class="input-filter mr-10" value="'+subfilter+'" />';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'
    // html += '<div class="d-flex justify-end"><button part="button" class="align-center button-download-backups hide" style="position: absolute; margin-top: 5px;"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button></div>'
    html += '<div style="position: absolute; margin-top: 5px;">'
    html += '<button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping-csv" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">data_table</span><span>Export CSV</span></button>'

    // console.log('jobs', jobs);
    html += ((jobs == null || jobs.data == null) ? '<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>' : ((jobs.data.status == "1" || jobs.data.status == "0") ? '<button part="button" class="mt-10 hide button-cancel" style="margin-left: -80px">Cancel Job</button>' : (this.disablesave == "yes" ? '' : '<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>')));
    html += '</div>';
    html += '</div>';
    html += '<button part="button" class="button-apply d-flex align-center mr-10"><span class="material-symbols-outlined mr-10">touch_app</span><span>Apply</span></button>'
    html += '<button part="button" class="button-save d-flex align-center"><span class="material-symbols-outlined mr-10">save</span><span>Save On Cloud</span></button>'
    html += '</div>';

    html += '</div>';

    html += '<div>';
    html += '<h4 id="span-filtered" part="results-title"></h4>'
    html += '<div id="div-subfiltered"></div>'
    html += '</div>';

    html += '<br />';

    var subfiltered = 0;

    if (showTable) {

      // for(var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) {
      //   if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "country") {
      //     //console.log('colstate-setting country', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j);
      //     colCountry = j;
      //   }
      //   if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "state") {
      //     //console.log('colstate-setting state', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j);
      //     colState = j;
      //   }
      //   if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "subcategory") {
      //     //console.log('colstate-setting subcategory', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j);
      //     colSubcategory = j;
      //   }
      //   if(JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase() == "statute") {
      //     //console.log('colstate-setting statute', JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j].toLowerCase(), j);
      //     colStatute = j;
      //   }
      // }

      html += '<table id="table-data" class="mt-20" style="height: 200px">';

      html += '<thead>';
      html += '<th part="td-head" class="td-head">'
      html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox" ' + ((this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + '/></div>';
      html += '</th>'
      for (var i = 0; i < extraFields.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += extraFields[i];
        html += '</th>'
      }
      html += '<th part="td-head" class="td-head">'
      html += colName;
      html += '</th>'
      // if(arrFeedbackReference != null) {
      //   html += '<th part="td-head" class="td-head">'
      //   html += proposedUsersLabel;
      //   html += '</th>'
      // }
      for (i = 0; i < uniqCols.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += uniqCols[i];
        html += '</th>'
      }
      for (i = 0; i < sourceCols.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += sourceCols[i];
        html += '</th>'
      }

      // for(i = 0; i < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; i++) {
      //   html += '<th part="td-head" class="td-head">'
      //   html += JSON.parse(sourceArray.data.mappings.mappings[0].cols)[i];
      //   html += '</th>'
      // }
      html += '</thead>';
      html += '<tbody>';
      // console.log('changedIds', this.changedOnboardingItemIds);
      for (i = 0; i < sourceArray.data.mappings.mappings.length; i++) {

        var showSearch = false;

        if (subfilter == "") {
          //console.log('showsearch true 1');
          showSearch = true;
        }

        // check showSearch in extra fields

        // if(!showSearch) {

        //   for(var j = 0; j < extraFields.length; j++) {

        //     var k = 0;
        //     for(k = 0; k < taggingArray.data.mappings.mappings.length; k++) {

        //       if(taggingArray.data.mappings.mappings[k].id == sourceArray.data.mappings.mappings[i].id) {
        //         break;
        //       }

        //     }

        //     if(k < taggingArray.data.mappings.mappings.length) {

        //       try {
        //         if(taggingArray.data.mappings.mappings[k].extraFields != null && taggingArray.data.mappings.mappings[k].extraFields[j] != null && taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

        //           //console.log('showsearch true 2', taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase(), subfilter);
        //           showSearch = true;
        //           subfiltered++;
        //           break;

        //         }
        //       } catch (_e: any) {

        //       }

        //       try {

        //         if(taggingArray.data.mappings.mappings[k].extraFields != null && taggingArray.data.mappings.mappings[k].extraFields[j] != null && JSON.stringify(taggingArray.data.mappings.mappings[k].extraFields[j]).toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

        //           //console.log('showsearch true 2', taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase(), subfilter);
        //           showSearch = true;
        //           subfiltered++;
        //           break;

        //         }

        //       } catch (_e: any) {

        //       }


        //     }

        //   }

        // }

        // if(!showSearch) {

        //   // check showSearch in uniq cols

        //   for(var l = 0; l < uniqCols.length; l++) {

        //     if(sourceArray.data.mappings.mappings[i][uniqCols[l]].replace(/ *\([^)]*\) */g, "").toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

        //       //console.log('showsearch true 3');
        //       showSearch = true;
        //       subfiltered++;
        //       break;

        //     }  

        //   }

        // }

        // if(!showSearch) {

        //   // check showSearch in source cols

        //   for(l = 0; l < sourceCols.length; l++) {

        //     for(var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) {

        //       if(sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) {

        //         if(sourceArray.data.mappings.mappings[i].data != null) {

        //           if(Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) {

        //             for(var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) {

        //               if(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j][k].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

        //                 //console.log('showsearch true 4');
        //                 showSearch = true;
        //                 subfiltered++;
        //                 break;

        //               }  

        //             }

        //           } else {

        //             if(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

        //               //console.log('showsearch true 5');
        //               showSearch = true;
        //               subfiltered++;
        //               break;

        //             }

        //           }

        //         }

        //       }

        //     }

        //   }

        // }

        var classBg = "";

        if (i % 2 === 0) {
          if (this.changedOnboardingItemIds.length > 0) {
            let changedId = ""
            for (let [k, col] of uniqCols.entries()) {
              // console.log('taggingarray rendered', i, col)
              changedId += taggingArray.data.mappings.mappings[i][col];
              if (k < (uniqCols.length - 1)) {
                changedId += ";"
              }
            }
            if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
              classBg = 'td-light-selected';
            } else {
              classBg = 'td-light';
            }
          } else {
            classBg = 'td-light';
          }
        } else {
          if (this.changedOnboardingItemIds.length > 0) {
            let changedId = ""
            for (let [k, col] of uniqCols.entries()) {
              if (taggingArray.data.mappings.mappings[i] == null) {
                console.log('id not found', i, taggingArray.data.mappings.mappings.length, sourceArray.data.mappings.mappings.length)
              }
              changedId += taggingArray.data.mappings.mappings[i][col];
              if (k < (uniqCols.length - 1)) {
                changedId += ";"
              }
            }
            if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
              classBg = 'td-dark-selected';
            } else {
              classBg = 'td-dark';
            }
          } else {
            classBg = 'td-dark';
          }
        }

        html += '<tr class="" id="tablerow-' + i + '">';

        html += '<td class="left-sticky td-body ' + classBg + '" ><div class="' + (!showSearch ? 'truncate' : '') + '"><input id="cb-' + i + '" type="checkbox" class="checkbox-row cb-select"/></div></td>';

        for (var j = 0; j < extraFields.length; j++) {

          var k = 0;
          for (k = 0; k < taggingArray.data.mappings.mappings.length; k++) {

            // if (taggingArray.data.mappings.mappings[k].id == sourceArray.data.mappings.mappings[i].id) {
            //   if (taggingArray.data.mappings.mappings[k].id == "62330e24-298d-4ef2-9449-c0e400e37cac") {

            //     console.log('found', taggingArray.data.mappings.mappings[k]);
            //     //console.log('before before filtermatch',sourceCols[l],JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j], colCountry, (sourceArray.data.mappings.mappings[i]), (sourceArray.data.mappings.mappings[i].data), colState);
            //     //console.log('before filtermatch', colCountry, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry], colState, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory]);

            //   }
            //   break;
            // }

          }

          if (i < taggingArray.data.mappings.mappings.length) {

            html += '<td part="td-body" class="' + classBg + '">';
            html += '<div class="' + (!showSearch ? 'truncate' : '') + '">'
            // html += '<textarea part="input" id="extra-field-'+i+'-'+j+'" class="extra-field extra-field-'+j+'" '+ (taggingArray.data.mappings.mappings[k].extraFields != null ? (taggingArray.data.mappings.mappings[k].extraFields[j] != null ?  ((taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase() == "client remarks" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : ((taggingArray.data.mappings.mappings[k].extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')) : "") : "") +' >'+(taggingArray.data.mappings.mappings[k].extraFields != null ? (taggingArray.data.mappings.mappings[k].extraFields[j] != null ? taggingArray.data.mappings.mappings[k].extraFields[j] : "") : "")+'</textarea>';
            html += '<textarea part="input" id="extra-field-' + i + '-' + j + '" class="extra-field extra-field-' + j + '" ' + (extraFields != null ? (extraFields[j] != null ? ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')) : "") : "") + ' >' + (taggingArray.data.mappings.mappings[i].extraFields != null ? (taggingArray.data.mappings.mappings[i].extraFields[j] != null ? (typeof taggingArray.data.mappings.mappings[i].extraFields[j] == 'string' ? taggingArray.data.mappings.mappings[i].extraFields[j] : "") : "") : "") + '</textarea>';
            html += '</div>';
            html += '</td>';
          } else {

            html += '<td part="td-body" class="' + classBg + '">';
            html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
            html += '<textarea part="input" id="extra-field-' + i + '-' + j + '" class="extra-field extra-field-' + j + '" type="text" value="" ' + ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + ' ></textarea>';
            html += '</div>';
            html += '</td>';
          }


        }

        html += '<td class="td-body ' + classBg + '" part="td-key">'
        html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
        if (apiIdDropdown.length > 0) {
          if (anotherProjection != null) {
            html += '<sf-i-form id="tags-' + i + '" class="tags-input tags-' + i + '" name="Tags" label="Select ' + colName + '" apiId="' + apiIdDropdown + '" mode="multiselect-dropdown" searchPhrase="' + this.projectName + ((dropdownSearchPhrase != null && dropdownSearchPhrase != "") ? dropdownSearchPhrase : "") + '" selectProjection="name" selectAnotherProjection="' + anotherProjection + '" mandatory></sf-i-form>';
          } else {
            html += '<sf-i-form id="tags-' + i + '" class="tags-input tags-' + i + '" name="Tags" label="Select ' + colName + '" apiId="' + apiIdDropdown + '" mode="multiselect-dropdown" searchPhrase="' + this.projectName + ((dropdownSearchPhrase != null && dropdownSearchPhrase != "") ? dropdownSearchPhrase : "") + '" selectProjection="name" mandatory></sf-i-form>';
          }

        } else {

          if (colName.toLowerCase() == "internalcontrols") {
            html += '<textarea id="tags-' + i + '" type="text" part="input" class="tags-input"></textarea>';
          } else {
            html += '<input id="tags-' + i + '" type="text" part="input" class="tags-input"/>';
          }

        }
        html += '</div>';
        html += '</td>'
        // if(arrFeedbackReference != null) {

        //   html += '<td class="td-body '+classBg+'" part="td-key">'
        //   html += '<div class="'+(!showSearch ? 'truncate' : '')+'">';
        //   if(arrFeedbackReference[JSON.parse(sourceArray.data.mappings.mappings[i].data)[1][0].trim()][JSON.parse(sourceArray.data.mappings.mappings[i].data)[6][0].trim().replace(/&amp;/g, "&")] == null) {

        //     this.setError(JSON.parse(sourceArray.data.mappings.mappings[i].data)[1][0].trim() + ':' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[6][0].trim().replace(/&amp;/g, "&") + ' - is not mapped correctly');
        //     setTimeout(() => {
        //       this.clearMessages();
        //     }, 20000);

        //   } else {
        //     html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="'+JSON.stringify(arrFeedbackReference[JSON.parse(sourceArray.data.mappings.mappings[i].data)[1][0].trim()][JSON.parse(sourceArray.data.mappings.mappings[i].data)[6][0].trim().replace(/&amp;/g, "&")]).replace(/"/g,"").replace(/\\n/g,"").replace(/{/g,"").replace(/}/g,"").replace(/\\/g,"")+'" lineSize="4" minLength="60"></sf-i-elastic-text>';
        //   }

        //   html += '</div>';
        //   html += '</td>'

        // }
        for (var l = 0; l < uniqCols.length; l++) {
          // console.log('uniqcolval', uniqCols[l], sourceArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i][uniqCols[l]]);
          html += '<td class="td-body ' + classBg + '" part="td-key">'
          html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
          html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + sourceArray.data.mappings.mappings[i][uniqCols[l]].replace(/ *\([^)]*\) */g, "") + '" minLength="20"></sf-i-elastic-text>';
          html += '</div>';
          html += '</td>'
        }


        for (l = 0; l < sourceCols.length; l++) {

          for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) {

            if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) {

              if (sourceArray.data.mappings.mappings[i].data != null) {

                html += '<td class="td-body ' + classBg + '" part="td-body">';
                html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';


                // if(sourceArray.data.mappings.mappings[i].id == "62330e24-298d-4ef2-9449-c0e400e37cac") {

                //   console.log('found', sourceArray.data.mappings.mappings[i]);

                //   //console.log('before before filtermatch',sourceCols[l],JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j], colCountry, (sourceArray.data.mappings.mappings[i]), (sourceArray.data.mappings.mappings[i].data), colState);

                //   //console.log('before filtermatch', colCountry, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry], colState, JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory]);

                // }

                //const filterMatch = this.matchesOnBoardingFilter(JSON.parse(sourceArray.data.mappings.mappings[i].data)[colCountry][0], JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState].length > 0 ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colState][0] : "", JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory].length > 0 ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colSubcategory][0] : "", Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute]) ? JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute][0] : JSON.parse(sourceArray.data.mappings.mappings[i].data)[colStatute]);

                const filterMatch = false;

                //console.log('after filtermatch', filterMatch);

                if (filterMatch) {
                  if (!unfilteredDict.includes(i)) {
                    unfilteredDict.push(i);
                  }
                }

                //console.log('isArray', sourceCols[l], Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j]));
                if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) {

                  for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) {
                    html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[j][k] + '" minLength="100" lineSize="4"></sf-i-elastic-text>');
                  }

                } else {
                  html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[j] + '" minLength="100" lineSize="4"></sf-i-elastic-text>')
                }

                html += '</div>';
                html += '</td>';

              }

            }

          }

        }

        html += '</tr>';
        //console.log('i=', i);

      }
      html += '</tbody>';
      html += '</table>';

    }

    divElement.innerHTML = html;

    if (unfilteredDict.length > 0) {
      var html = '';
      html += '<div class="mb-10">Items In Your Category (' + unfilteredDict.length + ")</div>";
      html += this.getFilterOnboardingString();
      ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html;

    } else {
      ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none';
    }

    if (subfiltered > 0) {
      ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '<h4 part="results-title">Filtered Results (' + subfiltered + ')</h4>';
    }

    if (this.getfilterOnboarding().length > 0) {
      for (var i = 0; i < sourceArray.data.mappings.mappings.length; i++) {

        if (!unfilteredDict.includes(i)) {
          const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i);
          if (tableRow != null) {
            (tableRow as HTMLTableRowElement).style.display = 'none';
          }

        }

      }
    }

    // const inputFilter = (divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement;
    // inputFilter.addEventListener('keyup', (e: any) => {

    //   if(e.key == 'Enter') {
    //     //console.log('filtering...', inputFilter.value);
    //     if(this._SfLoader != null) {
    //       this._SfLoader.innerHTML = '<div class="lds-dual-ring"></div>';
    //       this._SfLoader.innerHTML += ('<div class="lds-text"><div class="lds-text-c"></div></div>');
    //     }
    //     setTimeout(() => {
    //       this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, inputFilter.value);
    //       // this._SfLoader.innerHTML = '';
    //     }, 1000);

    //   }

    // });

    (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => {

      ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;

      const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf<HTMLInputElement>;
      //console.log('cb-length', arrCheckBoxes.length);
      for (var i = 0; i < arrCheckBoxes.length; i++) {
        const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement;
        //console.log('tablerow', i, tableRow);
        if (tableRow != null) {
          if (tableRow.style.display != 'none') {
            //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement));
            (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked;
            if (e.currentTarget.checked) {
              if (!this.selectedCbs.includes(i + '')) {
                this.selectedCbs.push(i + '');
              }
            } else {
              this.selectedCbs = [];
            }
          }
        }
      }

      //console.log('checkedarr', this.selectedCbs);

    });

    for (var j = 0; j < extraFields.length; j++) {

      const inputArrJ = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf<SfIForm | HTMLInputElement>;
      for (var k = 0; k < inputArrJ.length; k++) {
        inputArrJ[k].addEventListener('keyup', (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;

          if (e.key == "Enter") {

            this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement);

            const activeIndex = e.target.id.split('-')[2];

            for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) {

              taggingArray.data.mappings.mappings[count].extraFields = [];

              if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) {

                for (var l = 0; l < extraFields.length; l++) {
                  const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement);
                  taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
                }

              } else {

                for (var l = 0; l < extraFields.length; l++) {
                  const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement);
                  taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
                }

              }

            }

            this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)

          }

          // this.saveTagging(taggingArray.data.mappings, uploadFunction, refreshFunction, true);

        });

        inputArrJ[k].addEventListener('focusout', (e: any) => {

          this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement);

          const activeIndex = e.target.id.split('-')[2];

          for (var count = 0; count < sourceArray.data.mappings.mappings.length; count++) {

            taggingArray.data.mappings.mappings[count].extraFields = [];

            if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) {

              for (var l = 0; l < extraFields.length; l++) {
                const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement);
                taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
              }

            } else {

              for (var l = 0; l < extraFields.length; l++) {
                const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement);
                taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
              }

            }

          }

          this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)

        });
      }

    }

    const multiArr = (divElement as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf<SfIForm | HTMLInputElement>;

    for (var i = 0; i < multiArr.length; i++) {

      if (apiIdDropdown.length > 0) {


        for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

          var equal = true;

          for (var k = 0; k < uniqCols.length; k++) {

            if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) {
              if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) {
                equal = false;
              }
            }

          }

          // if(taggingArray.data.mappings.mappings[j].id == "62330e24-298d-4ef2-9449-c0e400e37cac" && equal) {
          // if (taggingArray.data.mappings.mappings[j].id == "62330e24-298d-4ef2-9449-c0e400e37cac") {

          //   // console.log('rendertagging', taggingArray.data.mappings.mappings[j], sourceArray.data.mappings.mappings[i]);
          //   console.log('rendertagging', taggingArray.data.mappings.mappings[j]);

          // }


          if (equal) {

            (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(taggingArray.data.mappings.mappings[j][colName]);
            if (taggingArray.data.mappings.mappings[j][colName] != null && taggingArray.data.mappings.mappings[j][colName].length > 0) {
              ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped");
            }

          }

        }

        // for(var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

        //   var equal = true;

        //   for(var k = 0; k < uniqCols.length; k++) {

        //     if(sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) {
        //       if(sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) {
        //         equal = false;
        //       }
        //     }

        //   }

        //   if(taggingArray.data.mappings.mappings[i].id == "fdea6e4a-9d47-4042-916f-724c51f465c1") {

        //     //console.log('rendertagging', taggingArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i]);

        //   }


        //   if(equal) {

        //     (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(taggingArray.data.mappings.mappings[j][colName]);
        //     if(taggingArray.data.mappings.mappings[j][colName].length > 0) {
        //       ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped");
        //     }

        //   }

        // }

        //console.log('preselect', multiArr[i]);

        multiArr[i].addEventListener('valueChanged', async (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
          this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement);
          // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter); 

        });

      } else {

        for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

          var equal = true;

          for (var k = 0; k < uniqCols.length; k++) {

            if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) {
              if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) {
                equal = false;
              }
            }

          }

          if (taggingArray.data.mappings.mappings[j].id == "89cbfcab-b1a9-4a33-a59b-da3c1210dfd2" && taggingArray.data.mappings.mappings[j].locationid == "a5fd6c0c-7743-4fd2-b8d9-1d5e53fbaefa" && equal) {

            // console.log('rendertagging', taggingArray.data.mappings.mappings[j], sourceArray.data.mappings.mappings[i]);
            console.log('rendertagging', i, j, taggingArray.data.mappings.mappings[j], equal);

          }

          if (equal) {

            if (taggingArray.data.mappings.mappings[j] != null) {
              (multiArr[i] as HTMLInputElement).value = taggingArray.data.mappings.mappings[j][colName];
            }

          }

        }



        multiArr[i].addEventListener('keyup', async (e: any) => {

          if (e.key == "Enter") {

            ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
            this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement);
            // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter)

          }

        });

        multiArr[i].addEventListener('focusout', async (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
          this.applyAndReloadTagging(e, colName, taggingArray, sourceArray, divElement);
          // this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols,apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, arrFeedbackReference, proposedUsersLabel, subfilter)

        });


      }


    }

    const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
    buttonApply.addEventListener('click', () => {
      // console.log('applied');
      // this.applyAndReloadTagging(e,colName, taggingArray, sourceArray, divElement);
      this.renderTaggingTable(divElement, sourceArray, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)
    })

    const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');
      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'flex';
      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'flex';
      const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'flex';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'flex';
      const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'flex';
      const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'flex';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'flex';

      const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups);
      buttonDownloadBackupsNew.addEventListener('click', async () => {

        const result = await this.fetchGetStoredMapping(colName);

        for (var i = 0; i < result.data.length; i++) {

          const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' });
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', url)
          a.setAttribute('download', 'report_' + colName + '_' + i + '.json');
          a.click()

        }

        (buttonToggleMoreBack as HTMLButtonElement).click();

        if (result.data.length === 0) {

          this.setError("No backups found!")
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        }

      });

      const buttonExportMappingNew = Util.clearListeners(buttonExportMapping);
      buttonExportMappingNew.addEventListener('click', async () => {

        let valueStr: string[] = [];

        for (var i = 0; i < multiArr.length; i++) {

          if (apiIdDropdown.length > 0) {

            for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

              var equal = true;

              for (var k = 0; k < uniqCols.length; k++) {

                if (sourceArray.data.mappings.mappings[i] != null && taggingArray.data.mappings.mappings[j] != null) {
                  if (sourceArray.data.mappings.mappings[i][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) {
                    equal = false;
                  }
                }

              }

              if (equal) {
                valueStr.push(JSON.stringify(taggingArray.data.mappings.mappings[j][colName]));
              }
            }

          } else {

            if (taggingArray.data.mappings.mappings[i] != null) {
              valueStr.push(taggingArray.data.mappings.mappings[i][colName]);
            } else {
              valueStr.push('');
            }

          }

        }

        //console.log('valueStr', valueStr);

        const valuesHTML = JSON.stringify(valueStr);

        const outerHTML = '<h3>This extract is generated on ' + new Date() + '</h3>' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '<br /><h2>' + ((divElement as HTMLDivElement).querySelector('#mapped-stats-title') as HTMLHeadingElement).outerHTML + '</h2>' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML;

        let tableHTML = this.TAGGING_HTML.replace(/TABLE_DATA/g, outerHTML);
        tableHTML = tableHTML.replace(/TABLE_VALUES/g, valuesHTML);

        const blob = new Blob([tableHTML], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html');
        a.click()

      });

      const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV);
      buttonExportMappingCSVNew?.addEventListener('click', async () => {
        let csvArray = JSON.parse(JSON.stringify(taggingArray.data.mappings.mappings))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj
          if (obj['cols'] != null && obj['data'] != null) {
            let dataArr = JSON.parse(obj['data'])
            let colsArr = JSON.parse(obj['cols'])
            for (let [j, colKey] of colsArr.entries()) {
              tempCsvObj['cols_' + colKey] = dataArr[j]
            }
          }
          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        let csvData = Util.convertToCSV(csvArray);
        // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings);
        console.log('csvData', csvData);
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.csv');
        a.click()
      })

      const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal);
      buttonLoadLocalNew?.addEventListener('click', async () => {
        console.log('load-local');
        ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
      });

      const fileInput = (divElement as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement;
      fileInput.value = '';
      const fileInputNew = Util.clearListeners(fileInput);
      fileInputNew.addEventListener('change', (e: any) => {
        var fr = new FileReader();
        fr.onload = () => {
          this.renderTaggingTable(divElement, sourceArray, JSON.parse(fr.result + ""), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter);
        };
        var frCsv = new FileReader();
        frCsv.onload = () => {
          console.log('taggingarray onload called');
          console.log('csv result', frCsv.result);
          const tempArr = Util.parseCsv(frCsv.result + "");
          console.log('csv data', tempArr)
          let changeCount = 0;
          for (let [i, obj] of tempArr.entries()) {
            let tempObj = taggingArray.data.mappings.mappings[i]
            delete tempObj['delta'];
            delete tempObj['lastupdated'];
            if (tempObj["id"].indexOf("6fb88c28-d572-4b55-b16c-957a519733b9") >= 0 || tempObj["id"].indexOf("90dbfbcc-a009-4778-b28e-a463867ceea9") >= 0 || tempObj["id"].indexOf("62330e24-298d-4ef2-9449-c0e400e37cac") >= 0 || tempObj["id"].indexOf("b9370711-024a-498a-8ce2-21c549824600") >= 0) {
              console.log('changed onboarding item', tempObj, obj, JSON.stringify(tempObj) !== JSON.stringify(obj))
            }
            let tempNewObj = obj
            delete tempNewObj['delta'];
            delete tempNewObj['lastupdated'];
            if (JSON.stringify(tempObj) !== JSON.stringify(tempNewObj)) {
              // console.log('item changed', taggingArray.data.mappings.mappings[i], obj)
              let changedId = ""
              for (let [k, col] of uniqCols.entries()) {
                changedId += tempObj[col];
                if (k < (uniqCols.length - 1)) {
                  changedId += ";"
                }
              }
              // this.changedOnboardingItemIds.push(taggingArray.data.mappings.mappings[i].id + ";" + taggingArray.data.mappings.mappings[i].entityid + ";" + taggingArray.data.mappings.mappings[i].locationid)
              this.changedOnboardingItemIds.push(changedId)
              // if(changedId.indexOf("6fb88c28-d572-4b55-b16c-957a519733b9") >= 0){
              //   console.log('changed onboarding item', tempObj, obj)
              // }
              changeCount++
            }
          }
          this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [
            () => {
              this.clearMessages();
              this.changedOnboardingItemIds = [];
              (buttonToggleMoreBack as HTMLButtonElement).click();
            },
            () => {
              this.clearMessages();
              let tempObj: any = {}
              tempObj["data"] = {}
              // let mappingsObj:any = {}
              // mappingsObj.mappings = tempArr
              // console.log('csv mappingsobj', mappingsObj)
              tempObj["data"]["mappings"] = {}
              tempObj["data"]["mappings"]["mappings"] = tempArr
              // for(let tempItem of tempArr){
              //   tempObj["data"]["mappings"]["mappings"].push(tempItem)
              // }
              // tempObj.data.mappings.mappings.push("pqrs")
              let tempObjStr = JSON.stringify(tempObj)

              // console.log('csv taggingarray tempobj', tempObj, tempObjStr, tempObj.data.mappings.mappings[0])
              console.log('csv taggingarray cols', uniqCols, JSON.parse(tempObjStr)["data"]["mappings"]["mappings"].length, Object.keys(tempObj.data.mappings.mappings[0]))

              this.renderTaggingTable(divElement, sourceArray, JSON.parse(tempObjStr), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, jobs, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter);
            }
          ])
          // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}}
          // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}}


        }
        if (e.target.files[0].name.toLowerCase().indexOf(colName.toLowerCase()) >= 0) {
          let ext = e.target.files[0].name.split('.')[e.target.files[0].name.split('.').length - 1]
          if (ext.toLowerCase() == "csv") {
            frCsv.readAsText(e.target.files[0]);
          } else {
            fr.readAsText(e.target.files[0]);
          }
        }
      })

      const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal);
      buttonSaveLocalNew?.addEventListener('click', async () => {
        console.log('save-local');
        const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().toLocaleString() + '.txt');
        a.click()
      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';
      const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'none';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'none';
      const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'none';
      const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'none';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'none';

    });

    // const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
    // buttonLoadLocal?.addEventListener('click', async () => {
    //   console.log('load-local');
    //   ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
    // });




    // const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
    // buttonSaveLocal?.addEventListener('click', async () => {
    //   console.log('save-local');
    //   const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' });
    //   const url = window.URL.createObjectURL(blob)
    //   const a = document.createElement('a')
    //   a.setAttribute('href', url)
    //   a.setAttribute('download', 'mapping_'+colName+'_'+new Date().toLocaleString()+'.txt');
    //   a.click()
    // });

    const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
    buttonSave?.addEventListener('click', async () => {
      await this.saveTagging(taggingArray.data.mappings, [], uploadFunction, refreshFunction, false, colName);
    });

    const buttonCancel = (divElement as HTMLDivElement).querySelector('.button-cancel') as HTMLButtonElement;
    buttonCancel?.addEventListener('click', async () => {
      //console.log('cancel clicked');
      await this.fetchCancelOnboardingJob(colName);
      refreshFunction();
    });

    const cbArr = (divElement as HTMLDivElement).querySelectorAll('.cb-select') as NodeListOf<HTMLInputElement>;
    for (i = 0; i < cbArr.length; i++) {
      cbArr[i].addEventListener('change', (ev: any) => {
        const cbSelectId = ev.currentTarget.id;
        const cbSelectIndex = cbSelectId.split('-')[1];

        if (!this.selectedCbs.includes(cbSelectIndex)) {
          this.selectedCbs.push(cbSelectIndex);
        } else {
          this.selectedCbs.splice(this.selectedCbs.indexOf(cbSelectIndex), 1);
        }
        //console.log(this.selectedCbs);
      })
    }

    // const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field') as NodeListOf<HTMLInputElement>;
    // var totalFields = 0;
    // var filledFields = 0;
    // for(var i = 0; i < arrExtraFields.length; i++) {
    //   const extraField = arrExtraFields[i] as HTMLInputElement;
    //   if(extraField.parentElement?.parentElement?.style.display != "none") {
    //     if(extraField.value != "") {
    //       filledFields++;
    //     }
    //     totalFields++;
    //   }
    // }
    if ((divElement as HTMLDivElement).querySelector("#span-extra-filled") != null) {
      //(divElement as HTMLDivElement).querySelector("#span-extra-filled")!.innerHTML = "Fields: " + filledFields + "/" + totalFields + " completed";
      //console.log('Total fields = ' + totalFields + ', filled fields = ' + filledFields);
    }
    this.changedOnboardingItemIds = []
  }

  renderTaggingTableNew = (divElement: any, selectedStatutes: any, sourceObject: any, sourceMapping: any, taggingObject: any, sourceCols: any, uploadFunction: any, refreshFunction: any, colName: any, uniqCols: Array<any>, apiIdDropdown: string, dropdownSearchPhrase: any, mandatoryFields: any, compareFields: Array<any>, anotherProjection: any, extraFields: Array<string>, _arrFeedbackReference: any, proposedUsersLabel: string, subfilter: string) => {
    console.log('sourceObj', sourceObject)
    console.log('taggingObj', taggingObject)
    let sourceArray: any = { data: { mappings: { mappings: sourceObject.data.mappings } } };
    let taggingArray: any = { data: { mappings: { mappings: taggingObject.data.mappings } } };
    if (taggingObject.data.mappings.mappings != null) {
      taggingArray = taggingObject;
    }
    console.log('divelement', divElement);
    console.log('sourcearray', sourceArray);
    console.log('sourceMappingStr', JSON.stringify(sourceMapping));
    console.log('sourceMapping', sourceMapping);
    console.log('taggingarray', JSON.stringify(taggingArray));
    console.log('tagged length', taggingArray.data.mappings.mappings.length)
    console.log('selectedStatutes', selectedStatutes);

    this.selectedCbs = [];
    if (sourceMapping.data == null) {
      console.log('sourcemapping data null');
      sourceMapping = { data: { mappings: Object.values(sourceArray.data.mappings.mappings) } }
    }
    for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) {
      if (taggingArray.data.mappings.mappings[i].id != null && sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[i].id] == null) {
        console.log('tagged splicing', taggingArray.data.mappings.mappings[i].id)
        taggingArray.data.mappings.mappings.splice(i, 1)
      } else {
        let flagFoundSource = false
        for (var j = 0; j < sourceMapping.data.mappings.length; j++) {
          if (sourceMapping.data.mappings[j].id == taggingArray.data.mappings.mappings[i].id) {
            flagFoundSource = true;
            break;
          }
        }
        if (taggingArray.data.mappings.mappings[i].id == "3cadde91-4ef5-4adf-baee-fd088a3297da") {
          console.log('tagged for splicing', flagFoundSource)
        }
        if (!flagFoundSource) {
          console.log('tagged splicing1', taggingArray.data.mappings.mappings[i].id)
          taggingArray.data.mappings.mappings.splice(i, 1)
        }
      }
    }

    let mandatoryPresent = true;
    console.log('mandatoryFields', mandatoryFields);
    for (i = 0; i < (mandatoryFields as Array<string>).length; i++) {
      for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {
        if (taggingArray.data.mappings.mappings[j][mandatoryFields[i]] == null) {
          console.log('mandatory not found', mandatoryFields[i])
          mandatoryPresent = false;
        }
      }
    }

    var taggedIds = []
    for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {
      if (taggingArray.data.mappings.mappings[j] != null) {
        if (sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[j].id] != null) {
          if (taggedIds.indexOf(taggingArray.data.mappings.mappings[j].id) < 0) {
            taggedIds.push(taggingArray.data.mappings.mappings[j].id)
          }
        } else {
          console.log('tagged id not found', taggingArray.data.mappings.mappings[j])
        }
      }
    }

    let countPush = 0;
    let countFound = 0
    let tempMappings = taggingArray.data.mappings.mappings
    for (let sourceObj of (sourceMapping.data?.mappings ?? [])) {
      let flagMatch = false;
      if (sourceArray.data.mappings.mappings[sourceObj.id] == null) {
        console.log('tagging id not found', sourceObj.id)
        continue;
      }
      for (let taggingObj of taggingArray.data.mappings.mappings) {
        if (sourceObj.id == taggingObj.id) {
          let flagMatchObj = true;
          for (let objKey of compareFields) {
            if (sourceObj[objKey] !== taggingObj[objKey] && taggingObj[objKey] != null && taggingObj[objKey] != "" && sourceObj[objKey] != null && sourceObj[objKey] != "") {
              console.log('Flag Mismatch', objKey, sourceObj[objKey], taggingObj[objKey])
              flagMatchObj = false;
              break;
            }
          }
          if (flagMatchObj == true) {
            flagMatch = true;
            countFound++;
            break;
          }
        }
      }
      if (flagMatch == false) {
        let objToPush: any = sourceObj
        for (let mandatoryField of mandatoryFields) {
          objToPush[mandatoryField] = ""
        }
        tempMappings.push(objToPush);
        countPush++;
      }
    }
    taggingArray.data.mappings.mappings = tempMappings;
    console.log('found tagging items', countFound)
    console.log('pushed tagging items', countPush)
    tempMappings = []
    for (let taggingObj of taggingArray.data.mappings.mappings) {
      if (sourceArray.data.mappings.mappings[taggingObj.id] != null) {
        tempMappings.push(taggingObj)
      }
    }

    taggingArray.data.mappings.mappings = tempMappings

    if (colName == "countries" || colName == "entities" || colName == "locations") {
      let tempMappingObj: any = {}
      for (let mappingItem of taggingArray.data.mappings.mappings) {
        let compositeKey = mappingItem.id
        for (let compareField of compareFields) {
          compositeKey += ";" + mappingItem[compareField]
        }
        if (tempMappingObj[compositeKey] == null) {
          tempMappingObj[compositeKey] = mappingItem
        }
        let tempMap = tempMappingObj[compositeKey][colName] ?? []
        let mapStr = ""
        let flagBlank = false;
        for (let mandatoryField of mandatoryFields) {
          if (mappingItem[mandatoryField] == null || mappingItem[mandatoryField] == "") {
            flagBlank = true;
            break;
          }
          mapStr += mappingItem[mandatoryField] + ";"
        }
        if (flagBlank) {
          continue;
        }
        tempMap.push(mapStr.slice(0, -1))
        tempMappingObj[compositeKey][colName] = tempMap
      }
      taggingArray.data.mappings.mappings = Object.values(tempMappingObj)
    }

    var tagged = 0;
    var changed = 0;
    var total = 0;
    var untagged = 0;
    let countFlagNull = 0
    tempMappings = []
    for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {
      if (taggingArray.data.mappings.mappings[j] != null) {
        let flagFound = false;
        for (let sourceObj of sourceMapping.data.mappings) {
          if (sourceObj.id == taggingArray.data.mappings.mappings[j].id) {
            let flagEqual = true;
            for (let col of compareFields) {
              if (sourceObj[col] != taggingArray.data.mappings.mappings[j][col] && taggingArray.data.mappings.mappings[j][col] != null) {
                flagEqual = false;
                break;
              }
            }
            if (flagEqual) {
              flagFound = true;
              break;
            }
          }
        }
        if (flagFound) {
          let tagStr = ""
          for (let col of compareFields) {
            tagStr += `${taggingArray.data.mappings.mappings[j][col]};`
          }
          tagStr.slice(0, -1)
          tempMappings.push(taggingArray.data.mappings.mappings[j])
          total++;
          if (this.changedOnboardingItemIds.length > 0) {
            let changedId = tagStr
            if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
              changed++;
            }
          }
          if (taggingArray.data.mappings.mappings[j][colName] == null || taggingArray.data.mappings.mappings[j][colName] == "" || taggingArray.data.mappings.mappings[j][colName].length == 0) {
            if (colName == "countries" || colName == "entities" || colName == "locations") {
              let flagNull = false;
              for (let mandatoryfield of mandatoryFields) {
                if (taggingArray.data.mappings.mappings[j][mandatoryfield] == null || taggingArray.data.mappings.mappings[j][mandatoryfield] == "") {
                  flagNull = true;
                  break;
                }
              }
              if (flagNull) {
                countFlagNull++;
                console.log('flag null', taggingArray.data.mappings.mappings[j], countFlagNull)
                continue
              }
            } else {
              countFlagNull++;
              console.log('flag null 1', taggingArray.data.mappings.mappings[j], countFlagNull)
              continue;
            }
          }
          tagged++;
        } else {
          untagged++;
          console.log('tagged not found', taggingArray.data.mappings.mappings[j].id, sourceArray.data.mappings.mappings[taggingArray.data.mappings.mappings[j].id])
        }
        // }
      }
    }
    taggingArray.data.mappings.mappings = tempMappings
    console.log('taggingarray3', JSON.stringify(taggingArray.data.mappings.mappings));
    let tempObj: any = {}
    let countDuplicate = 0
    for (let taggingObj of taggingArray.data.mappings.mappings) {
      if (tempObj[taggingObj.id] == null) {
        tempObj[taggingObj.id] = true
      } else {
        countDuplicate++;
        console.log('duplicate taggingObject', taggingObj.id, countDuplicate);
      }
    }
    console.log('tagged', tagged, 'total', total, 'untagged', untagged, 'length', taggingArray.data.mappings.mappings.length);
    const unfilteredDict: any[] = [];
    if (divElement == null) {
      return;
    }
    var html = '';

    var showTable = true;

    html += '<div class="d-flex justify-between flex-wrap align-center"> ';

    var status = '';
    if (tagged < total) {
      status = '<span class="color-pending material-icons">pending</span>';
    } else {
      status = '<span class="color-done material-icons">check_circle</span>';
    }

    var mandatoryStatus = '';
    if (!mandatoryPresent) {
      mandatoryStatus = '<span class="color-late-executed material-icons">error</span>&nbsp;&nbsp;Mandatory fields are not present';
    } else {
      mandatoryStatus = '<span class="color-done material-icons">check_circle</span>&nbsp;&nbsp;Mandatory fields are present';
    }

    if (showTable) {

      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">' + status + '&nbsp;&nbsp;Mapped ' + tagged + ' out of ' + total + '</h4></div>');

    } else {

      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">' + status + '&nbsp;&nbsp;Mapped ' + tagged + ' out of ' + total + '</h4></div>')

    }
    if (changed > 0) {
      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0"><span class="color-pending material-icons">pending</span>&nbsp;&nbsp;' + changed + ' Items changed</h4></div>')
    }
    html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0">' + mandatoryStatus + '</h4></div>')

    html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="span-extra-filled" class="m-0" part="results-title"></h4></div>')

    html += '<div class="d-flex align-center">';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'

    html += '<div style="position: absolute; margin-top: 5px;">'
    html += '<button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping-csv" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">data_table</span><span>Export CSV</span></button>'

    // console.log('jobs', jobs);
    html += ('<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>');
    html += '</div>';
    html += '</div>';
    html += '<button part="button" class="button-apply d-flex align-center mr-10"><span class="material-symbols-outlined mr-10">touch_app</span><span>Apply</span></button>'
    html += '<button part="button" class="button-save d-flex align-center"><span class="material-symbols-outlined mr-10">save</span><span>Save On Cloud</span></button>'
    html += '</div>';

    html += '</div>';

    html += '<div>';
    html += '<h4 id="span-filtered" part="results-title"></h4>'
    html += '<div id="div-subfiltered"></div>'
    html += '</div>';

    html += '<br />';

    var subfiltered = 0;

    if (showTable) {

      html += '<table id="table-data" class="mt-20" style="height: 200px">';

      html += '<thead>';
      html += '<th part="td-head" class="td-head">'
      html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox" ' + ((this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + '/></div>';
      html += '</th>'
      for (var i = 0; i < extraFields.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += extraFields[i];
        html += '</th>'
      }
      html += '<th part="td-head" class="td-head">'
      html += colName;
      html += '</th>'

      for (i = 0; i < uniqCols.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += uniqCols[i];
        html += '</th>'
      }
      for (i = 0; i < sourceCols.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += sourceCols[i];
        html += '</th>'
      }

      html += '</thead>';
      html += '<tbody>';
      // console.log('changedIds', this.changedOnboardingItemIds);
      for (i = 0; i < taggingArray.data.mappings.mappings.length; i++) {

        let complianceid = taggingArray.data.mappings.mappings[i].id
        console.log('compliance id', complianceid);
        var showSearch = false;

        if (subfilter == "") {
          //console.log('showsearch true 1');
          showSearch = true;
        }

        var classBg = "";

        if (i % 2 === 0) {
          if (this.changedOnboardingItemIds.length > 0) {
            let changedId = ""
            for (let [k, col] of uniqCols.entries()) {
              // console.log('taggingarray rendered', i, col)
              changedId += taggingArray.data.mappings.mappings[i][col];
              if (k < (uniqCols.length - 1)) {
                changedId += ";"
              }
            }
            if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
              classBg = 'td-light-selected';
            } else {
              classBg = 'td-light';
            }
          } else {
            classBg = 'td-light';
          }
        } else {
          if (this.changedOnboardingItemIds.length > 0) {
            let changedId = ""
            for (let [k, col] of uniqCols.entries()) {
              if (taggingArray.data.mappings.mappings[i] == null) {
                // console.log('id not found', i, taggingArray.data.mappings.mappings.length, sourceArray.data.mappings.mappings.length)
              }
              changedId += taggingArray.data.mappings.mappings[i][col];
              if (k < (uniqCols.length - 1)) {
                changedId += ";"
              }
            }
            if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
              classBg = 'td-dark-selected';
            } else {
              classBg = 'td-dark';
            }
          } else {
            classBg = 'td-dark';
          }
        }

        html += '<tr class="" id="tablerow-' + i + '">';

        html += '<td class="left-sticky td-body ' + classBg + '" ><div class="' + (!showSearch ? 'truncate' : '') + '"><input id="cb-' + i + '" type="checkbox" class="checkbox-row cb-select"/></div></td>';

        for (var j = 0; j < extraFields.length; j++) {

          if (i < taggingArray.data.mappings.mappings.length) {

            html += '<td part="td-body" class="' + classBg + '">';
            html += '<div class="' + (!showSearch ? 'truncate' : '') + '">'
            html += '<textarea part="input" id="extra-field-' + i + '-' + j + '" class="extra-field extra-field-' + j + '" ' + (extraFields != null ? (extraFields[j] != null ? ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')) : "") : "") + ' >' + (taggingArray.data.mappings.mappings[i].extraFields != null ? (taggingArray.data.mappings.mappings[i].extraFields[j] != null ? (typeof taggingArray.data.mappings.mappings[i].extraFields[j] == 'string' ? taggingArray.data.mappings.mappings[i].extraFields[j] : "") : "") : "") + '</textarea>';
            html += '</div>';
            html += '</td>';
          } else {

            html += '<td part="td-body" class="' + classBg + '">';
            html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
            html += '<textarea part="input" id="extra-field-' + i + '-' + j + '" class="extra-field extra-field-' + j + '" type="text" value="" ' + ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + ' ></textarea>';
            html += '</div>';
            html += '</td>';
          }


        }

        html += '<td class="td-body ' + classBg + '" part="td-key">'
        html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
        if (apiIdDropdown.length > 0) {
          if (anotherProjection != null) {
            html += '<sf-i-form id="tags-' + i + '" class="tags-input tags-' + i + '" name="Tags" label="Select ' + colName + '" apiId="' + apiIdDropdown + '" mode="multiselect-dropdown" searchPhrase="' + this.projectName + ((dropdownSearchPhrase != null && dropdownSearchPhrase != "") ? dropdownSearchPhrase : "") + '" selectProjection="name" selectAnotherProjection="' + anotherProjection + '" mandatory></sf-i-form>';
          } else {
            html += '<sf-i-form id="tags-' + i + '" class="tags-input tags-' + i + '" name="Tags" label="Select ' + colName + '" apiId="' + apiIdDropdown + '" mode="multiselect-dropdown" searchPhrase="' + this.projectName + ((dropdownSearchPhrase != null && dropdownSearchPhrase != "") ? dropdownSearchPhrase : "") + '" selectProjection="name" mandatory></sf-i-form>';
          }

        } else {

          if (colName.toLowerCase() == "internalcontrols") {
            html += '<textarea id="tags-' + i + '" type="text" part="input" class="tags-input"></textarea>';
          } else {
            html += '<input id="tags-' + i + '" type="text" part="input" class="tags-input"/>';
          }

        }
        html += '</div>';
        html += '</td>'

        for (var l = 0; l < uniqCols.length; l++) {
          html += '<td class="td-body ' + classBg + '" part="td-key">'
          html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';
          html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + taggingArray.data.mappings.mappings[i][uniqCols[l]].replace(/ *\([^)]*\) */g, "") + '" minLength="20"></sf-i-elastic-text>';
          html += '</div>';
          html += '</td>'
        }


        for (l = 0; l < sourceCols.length; l++) {

          for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[complianceid].cols).length; j++) {

            if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[complianceid].cols)[j]) {

              if (sourceArray.data.mappings.mappings[complianceid].data != null) {

                html += '<td class="td-body ' + classBg + '" part="td-body">';
                html += '<div class="' + (!showSearch ? 'truncate' : '') + '">';

                if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j])) {

                  for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j].length; k++) {
                    html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j][k] + '" minLength="100" lineSize="4"></sf-i-elastic-text>');
                  }

                } else {
                  if (typeof JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j] == "string" && Util.isJSONParsable(JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j])) {
                    html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j]) + '" minLength="100" lineSize="4"></sf-i-elastic-text>')

                  } else {
                    html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[complianceid].data)[j] + '" minLength="100" lineSize="4"></sf-i-elastic-text>')
                  }
                }

                html += '</div>';
                html += '</td>';

              }

            }

          }

        }

        html += '</tr>';
        //console.log('i=', i);

      }
      html += '</tbody>';
      html += '</table>';

    }
    if (divElement == null) {
      return;
    }
    divElement.innerHTML = html;

    if (unfilteredDict.length > 0) {
      var html = '';
      html += '<div class="mb-10">Items In Your Category (' + unfilteredDict.length + ")</div>";
      html += this.getFilterOnboardingString();
      ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html;

    } else {
      ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none';
    }

    if (subfiltered > 0) {
      ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '<h4 part="results-title">Filtered Results (' + subfiltered + ')</h4>';
    }

    if (this.getfilterOnboarding().length > 0) {
      for (var i = 0; i < taggingArray.data.mappings.mappings.length; i++) {

        if (!unfilteredDict.includes(i)) {
          const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i);
          if (tableRow != null) {
            (tableRow as HTMLTableRowElement).style.display = 'none';
          }

        }

      }
    }

    (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => {

      ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;

      const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf<HTMLInputElement>;
      //console.log('cb-length', arrCheckBoxes.length);
      for (var i = 0; i < arrCheckBoxes.length; i++) {
        const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement;
        //console.log('tablerow', i, tableRow);
        if (tableRow != null) {
          if (tableRow.style.display != 'none') {
            //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement));
            (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked;
            if (e.currentTarget.checked) {
              if (!this.selectedCbs.includes(i + '')) {
                this.selectedCbs.push(i + '');
              }
            } else {
              this.selectedCbs = [];
            }
          }
        }
      }

      //console.log('checkedarr', this.selectedCbs);

    });

    for (var j = 0; j < extraFields.length; j++) {

      const inputArrJ = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + j) as NodeListOf<SfIForm | HTMLInputElement>;
      for (var k = 0; k < inputArrJ.length; k++) {
        inputArrJ[k].addEventListener('keyup', (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;

          if (e.key == "Enter") {

            this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement);

            const activeIndex = e.target.id.split('-')[2];

            for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) {

              taggingArray.data.mappings.mappings[count].extraFields = [];

              if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) {

                for (var l = 0; l < extraFields.length; l++) {
                  const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement);
                  taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
                }

              } else {

                for (var l = 0; l < extraFields.length; l++) {
                  const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement);
                  taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
                }

              }

            }

            this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)

          }

          // this.saveTagging(taggingArray.data.mappings, uploadFunction, refreshFunction, true);

        });

        inputArrJ[k].addEventListener('focusout', (e: any) => {

          this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement);

          const activeIndex = e.target.id.split('-')[2];

          for (var count = 0; count < taggingArray.data.mappings.mappings.length; count++) {

            taggingArray.data.mappings.mappings[count].extraFields = [];

            if (this.selectedCbs.length > 0 && this.selectedCbs.includes(count + "")) {

              for (var l = 0; l < extraFields.length; l++) {
                const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + activeIndex + '-' + l) as HTMLInputElement);
                taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
              }

            } else {

              for (var l = 0; l < extraFields.length; l++) {
                const inputExtraField = ((divElement as HTMLDivElement).querySelector('#extra-field-' + count + '-' + l) as HTMLInputElement);
                taggingArray.data.mappings.mappings[count].extraFields.push(inputExtraField.value)
              }

            }

          }

          this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)

        });
      }

    }

    const multiArr = (divElement as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf<SfIForm | HTMLInputElement>;

    for (var i = 0; i < multiArr.length; i++) {

      if (apiIdDropdown.length > 0) {


        // for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

        var equal = true;
        let complianceid = taggingArray.data.mappings.mappings[i].id
        for (var k = 0; k < uniqCols.length; k++) {
          if (uniqCols[k] != "id") { continue; }
          if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[i] != null) {
            if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) {
              equal = false;
            }
          }

        }

        if (equal) {
          let preselctedVals = []
          if ((colName == "countries" || colName == "entities" || colName == "locations") && (taggingArray.data.mappings.mappings[i][colName] == null || taggingArray.data.mappings.mappings[i][colName].length == 0)) {
            let preselctedValsStr = ""
            for (let mandatoryfield of mandatoryFields) {
              if (taggingArray.data.mappings.mappings[i][mandatoryfield] == null || taggingArray.data.mappings.mappings[i][mandatoryfield] == "") {
                preselctedValsStr = ""
              } else {
                preselctedValsStr += `${taggingArray.data.mappings.mappings[i][mandatoryfield]};`
              }
            }

            preselctedValsStr = preselctedValsStr.slice(0, -1);
            if (preselctedValsStr.indexOf(';') >= 0) {
              preselctedVals.push(preselctedValsStr)
            }
            taggingArray.data.mappings.mappings[i][colName] = preselctedVals;
          } else {
            preselctedVals = taggingArray.data.mappings.mappings[i][colName];
          }
          (multiArr[i] as SfIForm).preselectedValues = JSON.stringify(preselctedVals);
          if (preselctedVals.length > 0) {
            ((multiArr[i] as SfIForm).parentElement as HTMLTableCellElement).setAttribute("part", "row-mapped");
          }

        }

        // }

        multiArr[i].addEventListener('valueChanged', async (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
          this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement);
        });

      } else {

        // for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

        var equal = true;
        let complianceid = taggingArray.data.mappings.mappings[i].id
        for (var k = 0; k < uniqCols.length; k++) {
          if (uniqCols[k] != "id") { continue; }
          if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[i] != null) {
            if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[i][uniqCols[k]]) {
              equal = false;
            }
          }

        }
        console.log('Array JSON parsable', taggingArray.data.mappings.mappings[i][colName], equal);
        if (equal) {

          if (taggingArray.data.mappings.mappings[i] != null) {
            // if (Util.isJSONParsable(taggingArray.data.mappings.mappings[i][colName])) {

            //   (multiArr[i] as HTMLInputElement).value = JSON.parse(taggingArray.data.mappings.mappings[i][colName])[0];
            // } else {
            (multiArr[i] as HTMLInputElement).value = taggingArray.data.mappings.mappings[i][colName] ?? "";
            // }
          }

        }

        // }



        multiArr[i].addEventListener('keyup', async (e: any) => {

          if (e.key == "Enter") {

            ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
            this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement);
          }

        });

        multiArr[i].addEventListener('focusout', async (e: any) => {

          ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
          this.applyAndReloadTaggingNew(e, colName, taggingArray, sourceArray, divElement);
        });


      }


    }

    const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
    buttonApply.addEventListener('click', () => {
      // console.log('applied');
      // this.applyAndReloadTagging(e,colName, taggingArray, sourceArray, divElement);
      this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, taggingArray, sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter)
    })

    const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');
      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'flex';
      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'flex';
      const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'flex';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'flex';
      const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'flex';
      const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'flex';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'flex';

      const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups);
      buttonDownloadBackupsNew.addEventListener('click', async () => {

        const result = await this.fetchGetStoredMapping(colName);

        for (var i = 0; i < result.data.length; i++) {

          const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' });
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', url)
          a.setAttribute('download', 'report_' + colName + '_' + i + '.json');
          a.click()

        }

        (buttonToggleMoreBack as HTMLButtonElement).click();

        if (result.data.length === 0) {

          this.setError("No backups found!")
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        }

      });

      const buttonExportMappingNew = Util.clearListeners(buttonExportMapping);
      buttonExportMappingNew.addEventListener('click', async () => {

        let valueStr: string[] = [];

        for (var i = 0; i < multiArr.length; i++) {

          if (apiIdDropdown.length > 0) {

            for (var j = 0; j < taggingArray.data.mappings.mappings.length; j++) {

              var equal = true;
              let complianceid = taggingArray.data.mappings.mappings[j].id
              for (var k = 0; k < uniqCols.length; k++) {
                if (uniqCols[k] != "id") { continue; }
                if (sourceArray.data.mappings.mappings[complianceid] != null && taggingArray.data.mappings.mappings[j] != null) {
                  if (sourceArray.data.mappings.mappings[complianceid][uniqCols[k]] != taggingArray.data.mappings.mappings[j][uniqCols[k]]) {
                    equal = false;
                  }
                }

              }

              if (equal) {
                valueStr.push(JSON.stringify(taggingArray.data.mappings.mappings[j][colName]));
              }
            }

          } else {

            if (taggingArray.data.mappings.mappings[i] != null) {
              valueStr.push(taggingArray.data.mappings.mappings[i][colName]);
            } else {
              valueStr.push('');
            }

          }

        }

        //console.log('valueStr', valueStr);

        const valuesHTML = JSON.stringify(valueStr);

        const outerHTML = '<h3>This extract is generated on ' + new Date() + '</h3>' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '<br /><h2>' + ((divElement as HTMLDivElement).querySelector('#mapped-stats-title') as HTMLHeadingElement).outerHTML + '</h2>' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML;

        let tableHTML = this.TAGGING_HTML.replace(/TABLE_DATA/g, outerHTML);
        tableHTML = tableHTML.replace(/TABLE_VALUES/g, valuesHTML);

        const blob = new Blob([tableHTML], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html');
        a.click()

      });

      const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV);
      buttonExportMappingCSVNew?.addEventListener('click', async () => {
        let csvArray = JSON.parse(JSON.stringify(taggingArray.data.mappings.mappings))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj
          // if(tempCsvObj[colName] == null){
          //   let tempStr = ""
          //   for(let mandatoryfield of mandatoryFields){
          //     tempStr += `${tempCsvObj[mandatoryfield]};`
          //   }
          //   tempStr = tempStr.slice(0, -1);
          //   tempCsvObj[colName] = [tempStr]
          // }
          let tempId = obj.id;
          let tempCompliance = sourceArray.data.mappings.mappings[tempId]
          if (tempCompliance['cols'] != null && tempCompliance['data'] != null) {
            let dataArr = JSON.parse(tempCompliance['data'])
            let colsArr = JSON.parse(tempCompliance['cols'])
            for (let [j, colKey] of colsArr.entries()) {
              tempCsvObj['cols_' + colKey] = dataArr[j]
            }
          }

          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        let csvData = Util.convertToCSV(csvArray);
        // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings);
        console.log('csvData', csvData);
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.csv');
        a.click()
      })

      const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal);
      buttonLoadLocalNew?.addEventListener('click', async () => {
        console.log('load-local');
        ((divElement as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
      });

      const fileInput = (divElement as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement;
      fileInput.value = '';
      const fileInputNew = Util.clearListeners(fileInput);
      fileInputNew.addEventListener('change', (e: any) => {
        var fr = new FileReader();
        fr.onload = () => {
          this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, JSON.parse(fr.result + ""), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter);
        };
        var frCsv = new FileReader();
        frCsv.onload = () => {
          console.log('taggingarray onload called');
          console.log('csv result', frCsv.result);
          const tempArr = Util.parseCsv(frCsv.result + "");
          console.log('csv data', tempArr)
          let changeCount = 0;
          for (let [i, obj] of taggingArray.data.mappings.mappings.entries()) {
            let tempObj = tempArr[i] ?? {}
            for (let key of Object.keys(tempObj)) {
              if (key.indexOf('cols_') >= 0) {
                delete tempObj[key]
              }
            }
            delete tempObj['delta'];
            delete tempObj['lastupdated'];

            let tempNewObj = obj
            for (let key of Object.keys(tempNewObj)) {
              if (key.indexOf('cols_') >= 0) {
                delete tempNewObj[key]
              }
            }
            delete tempNewObj['delta'];
            delete tempNewObj['lastupdated'];
            // if(tempNewObj[colName] == null){
            //   delete tempObj[colName];
            // }
            console.log('comparing objects', tempObj, tempNewObj);
            if (JSON.stringify(tempObj) !== JSON.stringify(tempNewObj)) {
              // console.log('item changed', taggingArray.data.mappings.mappings[i], obj)
              let changedId = ""
              for (let [k, col] of uniqCols.entries()) {
                // if (col != "id") { continue; }
                changedId += tempObj[col];
                if (k < (uniqCols.length - 1)) {
                  changedId += ";"
                }
              }

              this.changedOnboardingItemIds.push(changedId)
              changeCount++
            }
          }
          this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [
            () => {
              this.clearMessages();
              this.changedOnboardingItemIds = [];
              (buttonToggleMoreBack as HTMLButtonElement).click();
            },
            () => {
              this.clearMessages();
              let tempObj: any = {}
              tempObj["data"] = {}
              tempObj["data"]["mappings"] = {}
              tempObj["data"]["mappings"]["mappings"] = tempArr
              let tempObjStr = JSON.stringify(tempObj)

              console.log('csv taggingarray cols', uniqCols, JSON.parse(tempObjStr)["data"]["mappings"]["mappings"].length, Object.keys(tempObj.data.mappings.mappings[0]), sourceMapping)

              this.renderTaggingTableNew(divElement, selectedStatutes, sourceObject, sourceMapping, JSON.parse(tempObjStr), sourceCols, uploadFunction, refreshFunction, colName, uniqCols, apiIdDropdown, dropdownSearchPhrase, mandatoryFields, compareFields, anotherProjection, extraFields, _arrFeedbackReference, proposedUsersLabel, subfilter);
            }
          ])
        }
        if (e.target.files[0].name.toLowerCase().indexOf(colName.toLowerCase()) >= 0) {
          let ext = e.target.files[0].name.split('.')[e.target.files[0].name.split('.').length - 1]
          if (ext.toLowerCase() == "csv") {
            frCsv.readAsText(e.target.files[0]);
          } else {
            fr.readAsText(e.target.files[0]);
          }
        }
      })

      const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal);
      buttonSaveLocalNew?.addEventListener('click', async () => {
        console.log('save-local');
        const blob = new Blob([JSON.stringify(taggingArray)], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().toLocaleString() + '.txt');
        a.click()
      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';
      const buttonExportMappingCSV = (divElement as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'none';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'none';
      const buttonLoadLocal = (divElement as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'none';
      const buttonSaveLocal = (divElement as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'none';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'none';

    });

    const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
    buttonSave?.addEventListener('click', async () => {
      await this.saveTagging(taggingArray.data.mappings, selectedStatutes, uploadFunction, refreshFunction, false, colName);
    });

    const buttonCancel = (divElement as HTMLDivElement).querySelector('.button-cancel') as HTMLButtonElement;
    buttonCancel?.addEventListener('click', async () => {
      //console.log('cancel clicked');
      await this.fetchCancelOnboardingJob(colName);
      refreshFunction();
    });

    const cbArr = (divElement as HTMLDivElement).querySelectorAll('.cb-select') as NodeListOf<HTMLInputElement>;
    for (i = 0; i < cbArr.length; i++) {
      cbArr[i].addEventListener('change', (ev: any) => {
        const cbSelectId = ev.currentTarget.id;
        const cbSelectIndex = cbSelectId.split('-')[1];

        if (!this.selectedCbs.includes(cbSelectIndex)) {
          this.selectedCbs.push(cbSelectIndex);
        } else {
          this.selectedCbs.splice(this.selectedCbs.indexOf(cbSelectIndex), 1);
        }
        //console.log(this.selectedCbs);
      })
    }

    this.changedOnboardingItemIds = []
  }

  renderMappingTable = (divElement: any, jsonData: Array<any>, cursor: Array<any>, fetchFunction: any, searchString: string, mappedArray: any, found: number, uploadFunction: any, refreshFunction: any, extraFields: Array<string>, uploadBlock: number, extraFieldPosition: number, colName: string, subfilter: string, statuteColName: string, extraHintsArr: Array<string>, mappedStatutes: Array<any> = []) => {
    console.log('cols1', jsonData);
    // console.log('cols', jsonData[0].data.cols);
    //console.log('divelement', divElement);
    //console.log('jsonData', jsonData);
    //console.log('cursor', cursor);
    //console.log('fetch', fetchFunction);
    //console.log('searchstring', searchString);
    //console.log('subfiltervalue', subfilter);

    const arrCompliancesFrequencies: any = {};

    if (jsonData.length === 0) return;

    this.selectedCbs = [];

    let colCountry = -1;
    let colState = -1;
    let colSubcategory = -1;
    let colStatute = -1;

    const unfilteredDict: any[] = [];

    var html = '';
    let mappedTotal = 0
    for (var i = 0; i < jsonData.length; i++) {
      if (jsonData[i].mapped) {
        mappedTotal++
      }
    }
    html += '<div>';
    html += '<h3 part="results-title">Total Items (' + found + ') · Mapped (' + mappedTotal + ')</h3>';
    html += '</div>';


    html += '<div class="d-flex justify-between align-center left-sticky flex-wrap">';

    html += '<div id="div-subfiltered"></div>';
    // html += '<div id="scroll-overlay" part="onboarding-scroll-overlay" class="pos-fixed-scroll justify-center align-center">';
    // html += '<div id="scroll-overlay-left" class="mr-10"><button part="button-icon"><span class="material-symbols-outlined">arrow_left_alt</span></button></div>';
    // html += '<div id="scroll-overlay-right" class="ml-10"><button part="button-icon"><span class="material-symbols-outlined">arrow_right_alt</span></button></div>';
    // html += '</div>';

    html += '<div id="detail-overlay" part="onboarding-detail-overlay" class="pos-fixed justify-center align-center hide">';
    html += '<div class="cover-slide"></div>';
    html += '<div class="detail-container p-10">';
    html += '<div class="d-flex justify-between align-center mb-20">';
    html += '<div part="results-title">Row Details</div>';
    html += '<button part="button-icon" class="detail-close"><span class="material-symbols-outlined">close</span></button>';
    html += '</div>';
    html += '<div id="detail-overlay-list">';
    html += '</div>';
    html += '</div>';
    html += '</div>';

    html += '<div class="d-flex align-center">';
    // html += '<input part="input" type="text" placeholder="Filter" class="input-filter mr-10" value="' + subfilter + '" />';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'
    html += '<div style="position: absolute; margin-top: 5px;"><button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button></div>'
    html += '</div>';
    html += (this.disablesave == "yes" ? '' : '<button part="button" class="button-save" disabled>Save</button>');
    html += '</div>';

    html += '</div>';

    html += '<table id="table-data">';

    html += '<thead>';
    html += '<th part="td-head" class="td-head">'
    // html += 'Select';
    html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox" ' + ((this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + '/></div>';
    html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += '<div>View</div>';
    html += '</th>'
    if (extraFieldPosition === 0) {
      for (var i = 0; i < extraFields.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += extraFields[i];
        html += '</th>'
      }
    }
    // if (colName.toLowerCase() == "compliances") {
    //   html += '<th part="td-head" class="td-head">'
    //   html += 'Proposed Users';
    //   html += '</th>'
    // }
    html += '<th part="td-head" class="td-head">'
    html += 'Id';
    html += '</th>'

    // for(var j = 0; j < JSON.parse(jsonData[0].data.cols).length; j++) {

    //   if(jsonData[0].cols.includes(JSON.parse(jsonData[0].data.cols)[j])) {
    //     html += '<th part="td-head" class="td-head ' + (statuteColName.toLowerCase() == JSON.parse(jsonData[0].data.cols)[j].toLowerCase() ? 'left-sticky' : '') + '">'
    //     html += JSON.parse(jsonData[0].data.cols)[j]
    //     html += '</th>'
    //   }

    // }

    for (var j = 0; j < jsonData[0].cols.length; j++) {
      console.log('jsoncols', JSON.parse(jsonData[0].data.cols), jsonData[0].cols.length, j)
      html += '<th part="td-head" class="td-head ' + (statuteColName.toLowerCase() == (JSON.parse(jsonData[0].data.cols)[j] ?? "").toLowerCase() ? 'left-sticky' : '') + '">'
      // html += jsonData[0].cols[j]
      html += '</th>'

    }

    if (extraFieldPosition === 1) {
      for (var i = 0; i < extraFields.length; i++) {
        html += '<th part="td-head" class="td-head">'
        html += extraFields[i];
        html += '</th>'
      }
    }
    html += '</thead>'

    //console.log('colstate',  JSON.parse(jsonData[0].data.cols));

    for (var i = 0; i < JSON.parse(jsonData[0].data.cols).length; i++) {
      if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "country") {
        console.log('colstate country', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i);
        colCountry = i;
      }
      if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "state") {
        //console.log('colstate state', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i);
        colState = i;
      }
      if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == "subcategory") {
        //console.log('colstate subcategory', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i);
        colSubcategory = i;
      }
      if (JSON.parse(jsonData[0].data.cols)[i].toLowerCase() == statuteColName) {
        //console.log('colstate statute', JSON.parse(jsonData[0].data.cols)[i].toLowerCase(), i);
        colStatute = i;
      }
    }

    //var countExtra0 = 0;
    var countextra = [];

    var subfiltered = 0;

    html += '<tbody>'

    var mappedCount = 0;

    for (let level = 0; level < 2; level++) {

      for (var i = 0; i < jsonData.length; i++) {

        // console.log('subfilter value before', subfiltered);
        console.log('rendering', i, jsonData[i])
        let tempColCountry = -1;
        let tempColState = -1;
        let tempColStatute = -1;
        let tempColSubcategory = -1;

        if (JSON.parse(jsonData[0].data.cols)[0] == ('lastModifiedBy')) {
          if (JSON.parse(jsonData[i].data.cols)[0] != ('lastModifiedBy')) {
            tempColCountry = colCountry - 2;
            tempColState = colState - 2;
            tempColStatute = colStatute - 2;
            tempColSubcategory = colSubcategory - 2;
          } else {
            tempColCountry = colCountry;
            tempColState = colState;
            tempColStatute = colStatute;
            tempColSubcategory = colSubcategory;
          }
        } else {
          if (JSON.parse(jsonData[i].data.cols)[0] == ('lastModifiedBy')) {
            tempColCountry = colCountry + 2;
            tempColState = colState + 2;
            tempColStatute = colStatute + 2;
            tempColSubcategory = colSubcategory + 2;
          } else {
            tempColCountry = colCountry;
            tempColState = colState;
            tempColStatute = colStatute;
            tempColSubcategory = colSubcategory;
          }
        }

        if ((JSON.parse(jsonData[i].data.data)[tempColCountry] ?? "").length === 0 && level === 1) {

          html += '<tr id="tablerow-' + i + '" class="tablerow" style="vertical-align: baseline; display: none">';

          html += '<td part="td-action">';
          html += '<div id="select-' + i + '"><input class="checkbox checkbox-' + i + ' checkbox-row" part="input-checkbox" type="checkbox"/></div>';
          html += '</td>';
          html += '<td part="td-action">';
          html += '<div><button part="button" id="show-detail-' + i + '"><span class="material-symbols-outlined">open_in_new</span></button></div>';
          html += '</td>';
          for (var j = 0; j < extraFields.length; j++) {
            html += '<td part="td-body">';
            html += '<sf-i-multitextarea id="extra-field-' + jsonData[i].id + '-' + j + '" class="extra-field-' + j + ' extra-field" fields="[]" values="" hint="" showFields="15"></sf-i-multitextarea>';
            html += '</td>';
            if (j === 0) {
              //countExtra0++;
              countextra.push(i);
            }
          }
          // if (colName.toLowerCase() == "compliances") {
          //   html += '<td part="td-body">';
          //   html += JSON.stringify(jsonData[i].previousExtraFields);
          //   html += '</td>';
          // }
          html += '<td part="td-body">';
          html += '<sf-i-elastic-text exportparts="highlight,highlight-count" class="statute id-' + i + '" text="' + (jsonData[i].id) + '" minLength="10"></sf-i-elastic-text>';
          html += '</td>';

          html += '</tr>';

          continue;

        }

        var showSearch = false;

        if (subfilter == "") {
          showSearch = true;
        } else {

          for (var j = 0; j < extraFields.length; j++) {

            try {

              if (jsonData[i].extraFields != null && jsonData[i].extraFields[j] != null && jsonData[i].extraFields[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

                showSearch = true;
                subfiltered++;
                break;

              }

            } catch (e) {

            }

            try {

              if (jsonData[i].extraFields != null && jsonData[i].extraFields[j] != null && JSON.stringify(jsonData[i].extraFields[j]).toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {

                showSearch = true;
                subfiltered++;
                break;

              }

            } catch (e) {

            }


          }

          if (!showSearch) {
            for (var j = 0; j < JSON.parse(jsonData[i].data.cols).length; j++) {

              if (jsonData[i].cols.includes(JSON.parse(jsonData[i].data.cols)[j])) {

                if (Array.isArray(JSON.parse(jsonData[i].data.data)[j])) {

                  var tempCount = subfiltered;
                  for (var k = 0; k < JSON.parse(jsonData[i].data.data)[j].length; k++) {

                    if (JSON.parse(jsonData[i].data.data)[j][k].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {
                      showSearch = true;
                      //console.log('subfilter value inside 1', subfiltered);
                      subfiltered++;
                      break;
                    }

                  }

                  if (subfiltered > tempCount) break;

                } else {

                  if (JSON.parse(jsonData[i].data.data)[j].toLowerCase().indexOf(subfilter.toLowerCase()) >= 0) {
                    showSearch = true;
                    //console.log('subfilter value inside 2', subfiltered);
                    subfiltered++;
                    break;
                  }

                }

              }

            }

          }

        }

        //console.log('subfilter value', subfiltered);

        var classBg = "";

        if (i % 2 === 0) {
          classBg = 'td-light';
        } else {
          classBg = 'td-dark';
        }

        var mapped = "";

        if (jsonData[i].mapped) {
          mapped = "checked";
          this.selectedCbs.push(i);
        }

        if ((level == 0 && jsonData[i].mapped) || (level == 1 && !jsonData[i].mapped)) {

          if ((level == 0 && jsonData[i].mapped)) {
            mappedCount++;
          }

          if (arrCompliancesFrequencies[jsonData[i].id] == null) {
            arrCompliancesFrequencies[jsonData[i].id] = 0;
          } else {
            arrCompliancesFrequencies[jsonData[i].id]++;
          }

          html += '<tr id="tablerow-' + i + '" class="tablerow" style="vertical-align: baseline">';
          html += '<td part="td-action" class="left-sticky' + (jsonData[i].mapped ? ' chosen' : '') + '">';
          html += '<div id="select-' + i + '" class="' + (!showSearch ? 'truncate' : '') + '"><input class="checkbox checkbox-' + i + ' checkbox-row" part="input-checkbox" type="checkbox" ' + mapped + ' ' + ((this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + '/></div>';
          html += '</td>';
          html += '<td part="td-action" class="' + (jsonData[i].mapped ? 'chosen' : '') + '">';
          html += '<div class="' + (!showSearch ? 'truncate' : '') + '"><button class="button-expand" part="button-icon" id="show-detail-' + i + '"><span class="material-symbols-outlined">open_in_new</span></button></div>';

          let locationsForThisItem: any = [];

          if ((JSON.parse(jsonData[i].data.data)[tempColState] ?? "").length > 0) {
            locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState][0], JSON.parse(jsonData[i].data.data)[tempColStatute]);
          } else {
            console.log(JSON.parse(jsonData[i].data.data)[colStatute], colStatute, statuteColName);
            locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColStatute]);
          }

          if (extraFieldPosition === 0) {

            for (var j = 0; j < extraFields.length; j++) {
              html += '<td part="td-body" class="' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';

              const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
              const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "");
              let strValuesForThisItem: string = "";
              strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');


              html += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea id="extra-field-' + jsonData[i].id + '-' + j + '" class="extra-field-' + j + ' extra-field" ' + (mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : ''))) + ' fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" hint="' + extraHintsArr[j] + '" showFields="15"></sf-i-multitextarea></div>';
              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><sf-i-multitextarea id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : '')))+' fields="'+strLocationsForThisItem+'" values="'+strValuesForThisItem+'" hint="'+extraHintsArr[j]+'">'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</sf-i-multitextarea></div>';
              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><textarea part="input" id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')))+' >'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</textarea></div>';
              html += '</td>';
            }

            /*
            for(var j = 0; j < extraFields.length; j++) {
              
              html += '<td part="td-body" class="'+classBg+' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';

              let locationsForThisItem: any = '';

              if(JSON.parse(jsonData[i].data.data)[colState].length > 0) {
                locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[colCountry][0], JSON.parse(jsonData[i].data.data)[colState][0], JSON.parse(jsonData[i].data.data)[colStatute][0]);
              } else {
                locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[colCountry][0], JSON.parse(jsonData[i].data.data)[colStatute][0]);
              }

              const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g,'&quot;');
              const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "");
              let strValuesForThisItem: string = "";
              strValuesForThisItem =  JSON.stringify(valuesForThisItem).replace(/"/g,'&quot;');
              // try {
              //   JSON.parse(valuesForThisItem);
              //   strValuesForThisItem =  JSON.stringify(valuesForThisItem).replace(/"/g,'&quot;'); 
              //   //console.log('locationsForThisItem 1', JSON.stringify(locationsForThisItem), strValuesForThisItem);
              // } catch (e: any) {
              //   strValuesForThisItem = "";
              // } 
              //console.log('locationsForThisItem', JSON.stringify(locationsForThisItem));

              html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><sf-i-multitextarea id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : '')))+' fields="'+strLocationsForThisItem+'" values="'+strValuesForThisItem+'" hint="'+extraHintsArr[j]+'" ></sf-i-multitextarea></div>';

              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><sf-i-multitextarea id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : '')))+' fields="'+strLocationsForThisItem+'" values="'+strValuesForThisItem+'" hint="'+extraHintsArr[j]+'" >'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</sf-i-multitextarea></div>';

              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><textarea part="input" id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')))+' >'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</textarea></div>';
              html += '</td>';
              if(j === 0) {
                countExtra0++;
              }
            }
            */
          }

          // if (colName.toLowerCase() == "compliances") {

          //   var userHtml = '';

          //   userHtml = this.getPreviousExtraFields(i, jsonData[i].previousExtraFields, locationsForThisItem, showSearch)

          //   html += '<td part="td-body" class="' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';
          //   html += userHtml
          //   html += '</td>';
          // }
          html += '<td part="td-body" class="' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';
          html += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-elastic-text exportparts="highlight,highlight-count" class="statute id-' + i + '" text="' + (jsonData[i].id) + '" minLength="10"></sf-i-elastic-text></div>';
          html += '</td>';
          //let data = JSON.parse(jsonData[i].fields.data);
          for (var j = 0; j < JSON.parse(jsonData[i].data.cols).length; j++) {

            if (jsonData[i].cols.includes(JSON.parse(jsonData[i].data.cols)[j])) {

              // html += '<td part="td-body" class="td-body ' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + ' ' + (statuteColName.toLowerCase() == JSON.parse(jsonData[i].data.cols)[j].toLowerCase() ? 'left-sticky' : '') + '">';
              html += '<td part="td-body" class="td-body ' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';
              html += '<div class="' + (!showSearch ? 'truncate' : '') + '">'
              html += '<div class="d-flex align-center flex-wrap">';

              let filterMatch: any = null;

              filterMatch = this.matchesOnBoardingFilter(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState].length > 0 ? JSON.parse(jsonData[i].data.data)[tempColState][0] : "", JSON.parse(jsonData[i].data.data)[tempColSubcategory].length > 0 ? JSON.parse(jsonData[i].data.data)[tempColSubcategory][0] : "", Array.isArray(JSON.parse(jsonData[i].data.data)[tempColStatute]) ? JSON.parse(jsonData[i].data.data)[tempColStatute][0] : JSON.parse(jsonData[i].data.data)[tempColStatute]);


              if (jsonData[i].id == "f724e2b9-451a-49ec-85ba-2b099f433c73") {
                console.log('filtermatch', filterMatch);
              }
              if (filterMatch) {
                if (!unfilteredDict.includes(i)) {
                  unfilteredDict.push(i);
                }
              }
              // if(JSON.parse(jsonData[i].data.cols)[j] == "statute") {
              //   html += '<span class="material-symbols-outlined pr-5 plain-filter-icon">filter_list</span>';
              // }

              html += ('<div part="td-head" class="pl-0-imp w-100">' + JSON.parse(jsonData[i].data.cols)[j] + '</div>');
              if (Array.isArray(JSON.parse(jsonData[i].data.data)[j])) {

                for (var k = 0; k < JSON.parse(jsonData[i].data.data)[j].length; k++) {

                  html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(jsonData[i].data.data)[j][k] + '" minLength="80" lineSize="4"></sf-i-elastic-text>');
                  //console.log('Considering', JSON.parse(jsonData[i].data.cols)[j], jsonData[i].cols, j, JSON.parse(jsonData[i].data.data)[j], '<sf-i-elastic-text exportparts="highlight,highlight-count" text="'+JSON.parse(jsonData[i].data.data)[j][k]+'" minLength="80"></sf-i-elastic-text>');

                }

              } else {

                html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(jsonData[i].data.data)[j] + '" minLength="80" lineSize="4"></sf-i-elastic-text>')
                //console.log('Considering', JSON.parse(jsonData[i].data.cols)[j], jsonData[i].cols, j, JSON.parse(jsonData[i].data.data)[j], '<sf-i-elastic-text exportparts="highlight,highlight-count" text="'+JSON.parse(jsonData[i].data.data)[j]+'" minLength="80"></sf-i-elastic-text>');

              }

              html += '</div>';
              html += '</div>';
              html += '</td>';

            }

          }

          for (var k = 0; k < jsonData[i].cols.length; k++) {

            if (JSON.parse(jsonData[i].data.cols).includes(jsonData[i].cols[k])) {

            } else {
              html += '<td part="td-body" class="td-body ' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + ' ' + '"></td>';
            }

          }

          // else {

          //   var foundCol = false;
          //   for(var k = 0; k < jsonData[i].cols.length; k++) {
          //     console.log('founcol compare', jsonData[i].cols[k], JSON.parse(jsonData[i].data.cols)[j]);
          //     if(jsonData[i].cols[k] == JSON.parse(jsonData[i].data.cols)[j]) {

          //       if(JSON.parse(jsonData[i].data.cols).includes(jsonData[i].cols[k])) {
          //         foundCol = true;
          //       }
          //     } 
          //     console.log('founcol compare', foundCol);
          //   }


          //   if(!foundCol) {
          //     html += '<td part="td-body" class="td-body '+classBg+' ' + (jsonData[i].mapped ? 'chosen' : '') + ' ' + (statuteColName.toLowerCase() == JSON.parse(jsonData[i].data.cols)[j].toLowerCase() ? 'left-sticky' : '') + '"></td>';
          //   }

          // }

          if (extraFieldPosition === 1) {
            for (var j = 0; j < extraFields.length; j++) {
              html += '<td part="td-body" class="' + classBg + ' ' + (jsonData[i].mapped ? 'chosen' : '') + '">';
              let locationsForThisItem: any = [];

              if (JSON.parse(jsonData[i].data.data)[tempColState].length > 0) {
                locationsForThisItem = this.getLocationsByState(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColState][0], JSON.parse(jsonData[i].data.data)[tempColStatute]);
              } else {
                //console.log(JSON.parse(jsonData[i].data.data)[colStatute]);
                locationsForThisItem = this.getLocationsByCountry(JSON.parse(jsonData[i].data.data)[tempColCountry][0], JSON.parse(jsonData[i].data.data)[tempColStatute]);
              }

              const strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
              const valuesForThisItem = (jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "");
              let strValuesForThisItem: string = "";
              strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');


              html += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea id="extra-field-' + jsonData[i].id + '-' + j + '" class="extra-field-' + j + ' extra-field" ' + (mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : ''))) + ' fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" hint="' + extraHintsArr[j] + '" showFields="15"></sf-i-multitextarea></div>';
              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><sf-i-multitextarea id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled="true"' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled="true"' : '')))+' fields="'+strLocationsForThisItem+'" values="'+strValuesForThisItem+'" hint="'+extraHintsArr[j]+'">'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</sf-i-multitextarea></div>';
              // html += '<div class="'+(!showSearch ? 'truncate' : '')+'"><textarea part="input" id="extra-field-'+jsonData[i].id+'-'+j+'" class="extra-field-'+j+' extra-field" '+(mapped != "checked" ? 'disabled' : ((extraFields[j].toLowerCase() == "client remarks" && this.disableclientresponse.toLowerCase() == "yes") ? 'disabled' : ((extraFields[j].toLowerCase() == "flagggrc response" && this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '')))+' >'+(jsonData[i].extraFields != null ? (jsonData[i].extraFields[j] != null ? jsonData[i].extraFields[j] : "") : "")+'</textarea></div>';
              html += '</td>';
            }
          }
          html += '</tr>';

        }

      }


    }

    html += '</tbody>'
    html += '</table>';

    //console.log('countextra', countExtra0, countextra);
    console.log('arrCompliancesFrequencies', arrCompliancesFrequencies);

    divElement.innerHTML = html;

    // if (unfilteredDict.length > 0) {
    //   var html = '';
    //   html += '<div class="mb-10">Items In Your Category (' + unfilteredDict.length + ")</div>";
    //   html += this.getFilterOnboardingString();
    //   ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).innerHTML = html;

    // } else {
    //   ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLDivElement).style.display = 'none';
    // }

    if (subfiltered > 0) {
      ((divElement as HTMLDivElement).querySelector('#div-subfiltered') as HTMLDivElement).innerHTML = '<h5 part="results-title">Filtered Results (' + subfiltered + ')</h5>';
    }

    if (this.getfilterOnboarding().length > 0) {
      for (var i = 0; i < jsonData.length; i++) {
        if (!unfilteredDict.includes(i)) {
          const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + i);
          if (tableRow != null) {
            (tableRow as HTMLTableRowElement).style.display = 'none';
          }
        }
      }
    }

    // Scroll arrow handlers

    // const scrollLeft = (divElement as HTMLDivElement).querySelector('#scroll-overlay-left') as HTMLButtonElement;
    // scrollLeft.addEventListener('click', () => {
    //   //console.log('left');
    //   (this._SfOnboardingStatutesListContainer as HTMLDivElement).scrollLeft -= 150;
    // });

    // const scrollRight = (divElement as HTMLDivElement).querySelector('#scroll-overlay-right') as HTMLButtonElement;
    // scrollRight.addEventListener('click', () => {
    //   //console.log('right');
    //   //var scrollLeft = ((divElement as HTMLDivElement).querySelector('#statutes-list-container') as HTMLDivElement).scrollLeft;
    //   //((divElement as HTMLDivElement).querySelector('#statutes-list-container') as HTMLDivElement).scrollLeft += 100;
    //   (this._SfOnboardingStatutesListContainer as HTMLDivElement).scrollLeft += 150;
    // });

    // Extra field handlers

    for (var i = 0; i < extraFields.length; i++) {

      const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field-' + i) as NodeListOf<HTMLInputElement>;
      // console.log('i='+i, arrExtraFields.length)
      for (var j = 0; j < arrExtraFields.length; j++) {

        // console.log('j='+j, jsonData[j], arrExtraFields.length)
        // const extraField = (divElement as HTMLDivElement).querySelector('#extra-field-' + jsonData[j].id + '-' + i);
        // extraField?.addEventListener('focusout', () => {
        //   ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
        // });

        // extraField?.addEventListener('keyup', async (_e:any) => {
        //   if(extraFieldPosition === 1) {
        //     await this.saveMapping (divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, true)
        //   }

        // });

      }

    }

    // // Filter field handlers

    // const inputFilter = (divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement;
    // inputFilter.addEventListener('keyup', (e: any) => {

    //   if (e.key == 'Enter') {
    //     //console.log(inputFilter.value);
    //     if (this._SfLoader != null) {
    //       this._SfLoader.innerHTML = '<div class="lds-dual-ring"></div>';
    //       this._SfLoader.innerHTML += ('<div class="lds-text"><div class="lds-text-c"></div></div>');
    //     }
    //     setTimeout(() => {
    //       this.renderMappingTable(divElement, jsonData, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, inputFilter.value, statuteColName, extraHintsArr)
    //       this._SfLoader.innerHTML = '';
    //     }, 1000);

    //   }

    // });

    // More button handlers

    const buttonToggleMoreBack = (divElement as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (divElement as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');

      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'flex';

      const buttonDownloadBackupsNew = Util.clearListeners(buttonDownloadBackups);
      buttonDownloadBackupsNew.addEventListener('click', async () => {

        const result = await this.fetchGetStoredMapping(colName);

        for (var i = 0; i < result.data.length; i++) {

          const blob = new Blob([result.data[i].mappings != null ? JSON.stringify(result.data[i].mappings) : JSON.stringify(result.data[i])], { type: 'text/html' });
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', url)
          a.setAttribute('download', 'report_' + colName + '_' + i + '.json');
          a.click()

        }

        (buttonToggleMoreBack as HTMLButtonElement).click();

        if (result.data.length === 0) {

          this.setError("No backups found!")
          setTimeout(() => {
            this.clearMessages();
          }, 3000);

        }

      });

      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'flex';

      //console.log('buttonExportMapping', buttonExportMapping);

      const buttonExportMappingNew = Util.clearListeners(buttonExportMapping);
      buttonExportMappingNew.addEventListener('click', async () => {

        // const outerHTML = '<h3>This extract is generated on ' + new Date() + '</h3>' + ((divElement as HTMLDivElement).querySelector('#span-filtered') as HTMLHeadingElement).outerHTML + '<br /><h4><span class="chosen" style="border: solid 1px black;">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;Mapped compliances</h4><h4><span style="border: solid 1px black;">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;Un-mapped compliances</h4>' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML;
        const outerHTML = '<h3>This extract is generated on ' + new Date() + '</h3><br /><h4><span class="chosen" style="border: solid 1px black;">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;Mapped compliances</h4><h4><span style="border: solid 1px black;">&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;Un-mapped compliances</h4>' + ((divElement as HTMLDivElement).querySelector('#table-data') as HTMLTableElement).outerHTML;

        const tableHTML = this.MAPPING_HTML.replace(/TABLE_DATA/g, outerHTML);

        const blob = new Blob([tableHTML], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_' + colName + '_' + new Date().getTime() + '.html');
        a.click()

      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {


      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (divElement as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (divElement as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';

    });

    // Statute filters

    const arrFilterPlain = (divElement as HTMLDivElement).querySelectorAll('.plain-filter-icon') as NodeListOf<HTMLInputElement>;
    for (var i = 0; i < arrFilterPlain.length; i++) {
      arrFilterPlain[i].addEventListener('click', (e: any) => {
        const value = ((e.currentTarget as HTMLSpanElement).nextSibling as SfIElasticText).text;
        ((divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement).value = value;
        const event = new KeyboardEvent('keyup', {
          key: 'Enter',
          code: 'Enter',
          which: 13,
          keyCode: 13,
        });
        ((divElement as HTMLDivElement).querySelector('.input-filter') as HTMLInputElement).dispatchEvent(event);
        //console.log('filter click');
      })
    }


    // Expand handlers

    const arrExpands = (divElement as HTMLDivElement).querySelectorAll('.button-expand') as NodeListOf<HTMLInputElement>;
    for (var i = 0; i < arrExpands.length; i++) {
      arrExpands[i].addEventListener('click', (e: any) => {

        (divElement as HTMLDivElement).querySelector('#detail-overlay')?.classList.remove('hide');
        const id = e.currentTarget.id;
        const index = id.split("-")[2];
        //console.log(id, index);
        var html = '';

        html += '<div class="d-flex flex-wrap">';
        for (var j = 0; j < JSON.parse(jsonData[0].data.cols).length; j++) {

          html += '<div class="p-10">';
          html += ('<div part="td-head">' + JSON.parse(jsonData[0].data.cols)[j] + '</div>');
          if (JSON.parse(jsonData[0].data.cols)[j] == "state") {
            //console.log('state value', JSON.parse(jsonData[index].data.data)[j]);
          }
          if (Array.isArray(JSON.parse(jsonData[index].data.data)[j])) {

            html += '<div part="td-body">';
            if (JSON.parse(jsonData[index].data.data)[j].length === 0) {

              html += ('-<br />');

            } else {
              for (var k = 0; k < JSON.parse(jsonData[index].data.data)[j].length; k++) {

                var val = JSON.parse(jsonData[index].data.data)[j][k];
                if (val == '') {
                  val = '-';
                }
                html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + val + '" minLength="80"></sf-i-elastic-text>');

              }
            }

            html += '</div>';

          } else {

            var val = JSON.parse(jsonData[index].data.data)[j];
            if (val == '') {
              val = '-';
            }
            html += ('<div part="td-body">' + '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + val + '" minLength="80"></sf-i-elastic-text>' + '</div><br />')

          }
          html += '</div>';
        }
        html += '</div>';

        (divElement as HTMLDivElement).querySelector('#detail-overlay-list')!.innerHTML = html;

      })

    }

    // Detail close

    ((divElement as HTMLDivElement).querySelector('.detail-close') as HTMLButtonElement).addEventListener('click', (_e: any) => {
      (divElement as HTMLDivElement).querySelector('#detail-overlay')?.classList.add('hide');
    });

    // Checkbox handlers

    const arrCheckBoxes = (divElement as HTMLDivElement).querySelectorAll('.checkbox-row') as NodeListOf<HTMLInputElement>;
    for (var i = 0; i < arrCheckBoxes.length; i++) {
      arrCheckBoxes[i].addEventListener('change', async (_e: any) => {
        //console.log(e.currentTarget, (e.currentTarget as HTMLInputElement).checked);
        ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;
        if (extraFieldPosition === 1) {
          await this.saveMapping(divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, true, mappedStatutes)
        }
      });
    }

    (divElement as HTMLDivElement).querySelector('.checkbox-all')?.addEventListener('change', (e: any) => {

      //console.log('cb-length', arrCheckBoxes.length);
      for (var i = 0; i < arrCheckBoxes.length; i++) {
        const tableRow = (divElement as HTMLDivElement).querySelector('#tablerow-' + (i)) as HTMLElement;
        //console.log('tablerow', i, tableRow);
        if (tableRow != null) {
          if (tableRow.style.display != 'none') {
            //console.log('tablerow setting', e.currentTarget.checked, (arrCheckBoxes[i] as HTMLInputElement));
            (arrCheckBoxes[i] as HTMLInputElement).checked = e.currentTarget.checked;
          }
        }
      }
      ((divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement).disabled = false;

    });

    // Next, previous, save handlers

    (this._SfButtonNext as HTMLButtonElement)?.addEventListener('click', async () => {
      const resultFunction = await fetchFunction(searchString, cursor[cursor.length - 1].next);
      //console.log(resultFunction);
      if (resultFunction != null) {
        const jsonData1 = [];
        for (var i = 0; i < resultFunction.values.length; i++) {
          var mapped = false;
          for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) {
            if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) {
              if (mappedArray.data.mappings.mappings[j].selected) {
                mapped = true;
              }
            }
          }
          for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) {
            if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) {
              if (mappedArray.data.mappings.mappings[j].selected) {
                mapped = true;
              }
            }
          }

          jsonData1.push({ id: resultFunction.values[i].id, mapped: mapped, data: resultFunction.values[i].fields, cols: jsonData[0].cols })
        }

        cursor.push({ prev: cursor[cursor.length - 1].next, next: resultFunction.cursor })
        this.renderMappingTable(divElement, jsonData1, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, subfilter, statuteColName, extraHintsArr)
      }
    });

    (this._SfButtonPrev as HTMLButtonElement)?.addEventListener('click', async () => {
      cursor.pop();
      const resultFunction = await fetchFunction(searchString, cursor[cursor.length - 1].prev);
      //console.log(resultFunction);
      if (resultFunction != null) {
        const jsonData1 = [];
        for (var i = 0; i < resultFunction.values.length; i++) {
          var mapped = false;
          for (var j = 0; j < mappedArray.data.mappings.mappings.length; j++) {
            if (mappedArray.data.mappings.mappings[j].id == resultFunction.values[i].id) {
              if (mappedArray.data.mappings.mappings[j].selected) {
                mapped = true;
              }
            }
          }
          jsonData1.push({ id: resultFunction.values[i].id, mapped: mapped, data: resultFunction.values[i].fields, cols: jsonData[0].cols })
        }
        //console.log('clicked', jsonData1);
        this.renderMappingTable(divElement, jsonData1, cursor, fetchFunction, searchString, mappedArray, found, uploadFunction, refreshFunction, extraFields, uploadBlock, extraFieldPosition, colName, subfilter, statuteColName, extraHintsArr)
      }
    });

    (this._SfButtonSave as HTMLButtonElement)?.addEventListener('click', async () => {

      await this.saveMapping(divElement, uploadBlock, jsonData, extraFields, searchString, uploadFunction, refreshFunction, false, mappedStatutes)

    });

    // const arrExtraFields = (divElement as HTMLDivElement).querySelectorAll('.extra-field') as NodeListOf<SfIMultitextarea>;
    // var totalFields = 0;
    // var filledFields = 0;
    // for(var i = 0; i < arrExtraFields.length; i++) {
    //   const extraField = arrExtraFields[i] as SfIMultitextarea;
    //   if(extraField.parentElement?.parentElement?.parentElement?.style.display != "none" && (extraField.parentElement?.parentElement?.parentElement?.firstChild?.firstChild?.firstChild as HTMLInputElement).checked) {
    //     if(extraField.getFilled()) {
    //       filledFields++;
    //     }
    //     totalFields++;
    //   }
    // }
    // (divElement as HTMLDivElement).querySelector("#span-extra-filled")!.innerHTML = "Fields: " + filledFields + "/" + totalFields + " completed";
    //console.log('Total fields = ' + totalFields + ', filled fields = ' + filledFields);
    console.log('totalmapped', mappedCount, this.selectedCbs.length, this.selectedCbs);

  }

  getPreviousExtraFields = (i: number, previousExtraFields: any, locationsForThisItem: any, showSearch: boolean) => {

    var userHtml = '';

    if (previousExtraFields != null && previousExtraFields.length === 9 && Object.keys(previousExtraFields[0]).length > 0) {

      userHtml += '<table class="proposed-users-table proposed-users-table-' + i + '">';
      userHtml += '<tr>';
      userHtml += '<th part="td-head">';
      userHtml += 'Reporter';
      userHtml += '</th>';
      userHtml += '<th part="td-head">';
      userHtml += 'Approver';
      userHtml += '</th>';
      userHtml += '<th part="td-head">';
      userHtml += 'Functionhead';
      userHtml += '</th>';
      userHtml += '<th part="td-head">';
      userHtml += 'Auditor';
      userHtml += '</th>';
      userHtml += '<th part="td-head">';
      userHtml += 'Viewer';
      userHtml += '</th>';
      userHtml += '</tr>';
      userHtml += '<tr>';
      userHtml += '<th part="td-head">';

      let strLocationsForThisItem: string = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
      let valuesForThisItem: any = (previousExtraFields != null ? (previousExtraFields[3] != null ? previousExtraFields[3] : "") : "");
      let strValuesForThisItem: string = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');
      userHtml += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea class="extra-field" fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" showCollapsed="true"></sf-i-multitextarea></div>';

      userHtml += '</th>';
      userHtml += '<th part="td-head">';

      strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
      valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[4] != null ? previousExtraFields[4] : "") : "");
      strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');
      userHtml += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea class="extra-field" fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" showCollapsed="true"></sf-i-multitextarea></div>';

      userHtml += '</th>';
      userHtml += '<th part="td-head">';

      strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
      valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[5] != null ? previousExtraFields[5] : "") : "");
      strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');
      userHtml += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea class="extra-field" fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" showCollapsed="true"></sf-i-multitextarea></div>';

      userHtml += '</th>';
      userHtml += '<th part="td-head">';

      strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
      valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[6] != null ? previousExtraFields[6] : "") : "");
      strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');
      userHtml += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea class="extra-field" fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" showCollapsed="true"></sf-i-multitextarea></div>';

      userHtml += '</th>';
      userHtml += '<th part="td-head">';

      strLocationsForThisItem = JSON.stringify(locationsForThisItem).replace(/"/g, '&quot;');
      valuesForThisItem = (previousExtraFields != null ? (previousExtraFields[7] != null ? previousExtraFields[7] : "") : "");
      strValuesForThisItem = JSON.stringify(valuesForThisItem).replace(/"/g, '&quot;');
      userHtml += '<div class="' + (!showSearch ? 'truncate' : '') + '"><sf-i-multitextarea class="extra-field" fields="' + strLocationsForThisItem + '" values="' + strValuesForThisItem + '" showCollapsed="true"></sf-i-multitextarea></div>';

      userHtml += '</th>';
      userHtml += '</tr>';
      userHtml += '</table>';
      userHtml += '';

    }

    return userHtml;

  }

  refreshCalendar = async () => {

    //console.log('tabs',this.myOnboardingTab,this.TAB_CALENDAR);

    if (this.myOnboardingTab == this.TAB_CALENDAR) {

      const calendarJobs = await this.fetchCalendarJobs();

      if (calendarJobs.data.status == "0" || calendarJobs.data.status == "1") {

        setTimeout(async () => {
          await this.loadOnboardingCalendar();
          this.refreshCalendar();
        }, 10000);
      }

    }

  }

  renderNewOnboarding = () => {

    var html = '';

    html += '<div class="w-100 d-flex justify-center">';
    html += '<div>';
    html += '<div part="rcm-section-title" class="d-flex mt-20 mb-20 justify-center"><span>Client Sign Off</span></div><br />';
    html += '<label part="input-label" class="mt-5">Remarks</label><br />';
    html += '<textarea id="rcm-signoff" part="input" type="text"></textarea><br /><br />'
    html += '<label part="input-label" class="mt-5">Signature</label><br />';
    html += '<input id="rcm-signature" part="input" type="text" class="w-90"/><br /><br />'
    html += '<div class="d-flex justify-end align-center mt-20"><button part="button" class="d-flex align-center submit-signoff"><span class="material-symbols-outlined">signature</span>&nbsp;&nbsp;  Submit</button></div>'
    html += '<div class="mt-20 mb-10"></div>';
    html += '</div>';
    html += '</div>';

    (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = html;



  }

  renderOnboardingSignoff = (signoff: any) => {

    var html = '';

    // if(signoff.result == null) {

    this.renderNewOnboarding();

    // } else {

    html += '<div class="w-100 d-flex justify-evenly">';
    html += '<div>';
    html += '<div part="rcm-section-title" class="d-flex mt-20 mb-20"><span>New Sign Off</span></div><br />';
    html += '<label part="input-label" class="mt-5">Remarks</label><br />';
    html += '<textarea id="rcm-signoff" part="input" type="text"></textarea><br /><br />'
    html += '<label part="input-label" class="mt-5">Signature</label><br />';
    html += '<input id="rcm-signature" part="input" type="text" class="w-90"/><br /><br />'
    html += '<div class="d-flex justify-end align-center mt-20"><button part="button" class="d-flex align-center submit-signoff"><span class="material-symbols-outlined">signature</span>&nbsp;&nbsp;  Submit</button></div>'
    html += '<div class="mt-20 mb-10"></div>';
    html += '</div>';
    html += '<div>';
    html += '<div class="d-flex justify-between align-center">';
    html += '<div part="rcm-section-title" class="d-flex mt-20 mb-20 justify-center"><span>Sign Offs</span></div>';
    html += (this.disablesignoff == "yes" ? "" : '<button part="button" class="button-new d-flex align-center mt-20 mb-20"><span class="material-symbols-outlined">add</span><span>&nbsp;&nbsp;New</span></button>');
    html += '</div>';
    html += '<table class="mt-20">';
    html += '<thead>';
    html += '<th part="td-head" class="td-head">';
    html += 'Name';
    html += '</th>';
    html += '<th part="td-head" class="td-head">';
    html += 'Remarks';
    html += '</th>';
    html += '<th part="td-head" class="td-head">';
    html += 'Signature';
    html += '</th>';
    html += '<th part="td-head" class="td-head">';
    html += 'Timestamp';
    html += '</th>';
    html += '</thead>';
    const jsonData = JSON.parse(signoff.result.data.S);
    for (var i = 0; i < jsonData.length; i++) {

      var classBg = "";
      if (i % 2 === 0) {
        classBg = 'td-light';
      }
      else {
        classBg = 'td-dark';
      }
      html += '<tr>';
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jsonData[i].username != null ? jsonData[i].username : "";
      html += '</td>';
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jsonData[i].signofftext;
      html += '</td>';
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jsonData[i].signature;
      html += '</td>';
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += new Date(parseInt(jsonData[i].timestamp));
      html += '</td>';
      //console.log(jsonData[i]);
    }
    html += '</table>';
    html += '</div>';
    html += '</div>';

    html += '<div class="w-100 d-flex justify-center">';

    html += '</div>';

    // }

    (this._SfOnboardingSignoffContainer as HTMLDivElement).innerHTML = html;
    (this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('.submit-signoff')?.addEventListener('click', async (_e: any) => {

      const signofftext = ((this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('#rcm-signoff') as HTMLInputElement).value;
      const signoffsignature = ((this._SfOnboardingSignoffContainer as HTMLDivElement).querySelector('#rcm-signature') as HTMLInputElement).value;
      await this.fetchUpdateSignOff(signofftext, signoffsignature);
      this.loadOnboardingSignoff();

    })

  }

  getAllPastFiscals = (startDate: Date) => {
    const retArr: number[] = [];

    // Normalize startDate to its fiscal year start
    const startFY = new Date(startDate);
    startFY.setDate(1);
    startFY.setMonth(3); // April

    if (startDate.getMonth() < 3) {
      startFY.setFullYear(startFY.getFullYear() - 1);
    }

    // Current fiscal year anchor
    let date = new Date();
    date.setDate(1);
    date.setMonth(3);

    // If today is before April, shift to last FY start
    if (new Date().getMonth() < 3) {
      date.setFullYear(date.getFullYear() - 1);
    }

    while (date.getTime() >= startFY.getTime()) {
      retArr.push(date.getFullYear());
      date.setFullYear(date.getFullYear() - 1);
    }

    return retArr;
  };

  renderOnboardingGovUsers = (sourceLocationsArray: any, mappedModuleUsers: any, changedIndices: number[] = []) => {

    console.log('sourceLocationsArray', sourceLocationsArray);
    console.log('modulesMapping', mappedModuleUsers);
    if (changedIndices.length == 0) {
      this.changedOnboardingItemIds = []
    } else {
      for (let changedIndex of changedIndices) {
        let changedId = sourceLocationsArray[changedIndex].id
        if (this.changedOnboardingItemIds.indexOf(changedId) < 0) {
          this.changedOnboardingItemIds.push(changedId)
        }
      }
    }
    let sourceCols = ["id", "name", "modulename"]
    let uniqCols = ["users"]

    var html: string = '';
    html += '<div id="gov-modules-list-container" class="pb-10 pt-10 w-100">';
    html += '<div class="d-flex justify-between flex-wrap align-center"> ';

    let tagged = 0
    var changed = 0
    for (let item of sourceLocationsArray) {
      let locationModuleKey = item.id + ";" + item.moduleid
      console.log('locationKey', locationModuleKey, item)
      if (mappedModuleUsers[locationModuleKey] != null && mappedModuleUsers[locationModuleKey].users != null && mappedModuleUsers[locationModuleKey].users.length > 0) {
        tagged++;
      }
      if (this.changedOnboardingItemIds.indexOf(locationModuleKey) >= 0) {
        changed++;
      }
    }
    var status = '';
    if (tagged < sourceLocationsArray.length) {
      status = '<span class="color-pending material-icons">pending</span>';
    } else {
      status = '<span class="color-done material-icons">check_circle</span>';
    }
    html += (`<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">${status}&nbsp;&nbsp; ${tagged} Locations mapped out of ${sourceLocationsArray.length}</h4></div>`);


    if (changed > 0) {
      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0"><span class="color-pending material-icons">pending</span>&nbsp;&nbsp;' + changed + ' Items changed</h4></div>')
    }
    html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="span-extra-filled" class="m-0" part="results-title"></h4></div>')

    html += '<div class="d-flex align-center">';
    // html += '<input part="input" type="text" placeholder="Filter" class="input-filter mr-10" value="'+subfilter+'" />';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'
    // html += '<div class="d-flex justify-end"><button part="button" class="align-center button-download-backups hide" style="position: absolute; margin-top: 5px;"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button></div>'
    html += '<div style="position: absolute; margin-top: 5px;">'
    html += '<button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping-csv" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">data_table</span><span>Export CSV</span></button>'

    // console.log('jobs', jobs);
    html += ('<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>');
    html += '</div>';
    html += '</div>';
    html += '<button part="button" class="button-apply d-flex align-center mr-10"><span class="material-symbols-outlined mr-10">touch_app</span><span>Apply</span></button>'
    html += '<button part="button" class="button-save d-flex align-center"><span class="material-symbols-outlined mr-10">save</span><span>Save On Cloud</span></button>'
    html += '</div>';

    html += '</div>';

    html += `
        <div class="sf-i-form-modal-container d-flex flex-col align-stretch hide" part="sf-i-form-modal-container" id="sf-i-form-modal-container">
          <div class="sf-i-form-modal-button-container d-flex justify-between align-center p-10" part="sf-i-form-modal-button-container">
            <button id="button-close-form" part="button-icon" class="button-icon-click"><span class="material-icons">keyboard_backspace</span></button>
            <button id="button-save-form" part="button-icon" class="button-icon-click"><span class="material-icons">check</span></button>
          </div>
          <div class="d-flex p-10" id="sf-i-form-container" part="sf-i-form-container"></div>
        </div>
        `

    html += '<table id="table-data" class="mt-20" style="height: 200px">';

    html += '<thead>';
    html += '<th part="td-head" class="td-head">'
    html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox"/></div>';
    html += '</th>'

    for (let i = 0; i < sourceCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += sourceCols[i];
      html += '</th>'
    }
    for (let i = 0; i < uniqCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += uniqCols[i];
      html += '</th>'
    }
    html += '</thead>';
    html += '<tbody>';

    for (let i = 0; i < sourceLocationsArray.length; i++) {

      var classBg = "";
      let item = sourceLocationsArray[i]
      let locationModuleKey = item.id + ";" + item.moduleid
      if (i % 2 === 0) {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = locationModuleKey
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-light-selected';
          } else {
            classBg = 'td-light';
          }
        } else {
          classBg = 'td-light';
        }
      } else {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = locationModuleKey
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-dark-selected';
          } else {
            classBg = 'td-dark';
          }
        } else {
          classBg = 'td-dark';
        }
      }

      html += '<tr class="" id="tablerow-' + i + '">';

      // html += '<td class="left-sticky td-body ' + classBg + '" ><div class=""><input id="cb-' + i + '" type="checkbox" class="checkbox-row cb-select"/></div></td>';

      html += '<td class="left-sticky td-body ' + classBg + '" part="td-key">'
      html += '<div class="">';
      html += '<input id="locations-' + i + '" type="checkbox" part="input-checkbox" class="locations-input"/>';


      html += '</div>';
      html += '</td>'




      for (var l = 0; l < sourceCols.length; l++) {
        html += '<td class="td-body ' + classBg + '" part="td-body">';
        html += '<div class="">';

        html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + sourceLocationsArray[i][sourceCols[l]]) + '" minLength="20" lineSize="4"></sf-i-elastic-text>'
        html += '</div>';
        html += '</td>';

      }

      // let users = mappedModuleUsers[locationModuleKey] ?? []
      // let moduleNames = modules.map((m: any) => {
      //   return m.locationname;
      // })
      html += '<td class="' + classBg + '" part="td-key">'
      html += '<sf-i-form id="tags-' + i + '" class="tags-input tags-' + i + '" name="Tags" label="Select Users" apiId="' + this.apiIdUsers + '" mode="multiselect-dropdown" searchPhrase="' + this.projectName + '" selectProjection="name" mandatory></sf-i-form>'
      html += '</div>';
      html += '</td>'

      html += '</tr>';
      //console.log('i=', i);

    }
    html += '</tbody>';
    html += '</table>';


    // html += '</div>';

    html += '</div>';

    (this._SfOnboardingGovUsersContainer as HTMLDivElement).innerHTML = html;

    const selectAllCheckbox = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#select-all') as HTMLInputElement
    selectAllCheckbox.addEventListener('change', (e) => {
      let selCheckbox = e.target as HTMLInputElement
      let inputCheckboxes = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf<HTMLInputElement>
      console.log('input checkboxes found', inputCheckboxes.length, selCheckbox.checked)
      for (let inputCheckbox of inputCheckboxes) {
        inputCheckbox.checked = selCheckbox.checked;
      }
    })

    let usersInputs = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.tags-input') as NodeListOf<SfIForm>;
    for (let usersInput of usersInputs) {
      let index = parseInt(usersInput.id.split('-')[1]);
      let locationModuleKey = sourceLocationsArray[index].id + ";" + sourceLocationsArray[index].moduleid
      let preselctedVals = mappedModuleUsers[locationModuleKey]?.users ?? []
      usersInput.preselectedValues = JSON.stringify(preselctedVals);
      usersInput.loadMode();
      usersInput.addEventListener('valueChanged', (e: any) => {
        let input = e.currentTarget as SfIForm;
        let index = parseInt(input.id.split('-')[1]);
        console.log('edit button clicked', index)
        let tempModulesUsers = mappedModuleUsers
        let locationModuleKey = sourceLocationsArray[index].id + ";" + sourceLocationsArray[index].moduleid
        tempModulesUsers[locationModuleKey] = {
          moduleid: sourceLocationsArray[index].moduleid,
          modulename: sourceLocationsArray[index].modulename,
          users: input.selectedValues()
        }
        let indices = [index]
        let inputCheckboxes = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf<HTMLInputElement>
        for (let inputCheckbox of inputCheckboxes) {
          let inputId = inputCheckbox.id ?? ""
          let inputIndex = inputId.split('locations-')[1]
          if (inputCheckbox.checked && inputIndex != null && sourceLocationsArray[parseInt(inputIndex)] != null) {
            let locationModuleKey = sourceLocationsArray[parseInt(inputIndex)].id + ";" + sourceLocationsArray[parseInt(inputIndex)].moduleid
            tempModulesUsers[locationModuleKey] = {
              moduleid: sourceLocationsArray[parseInt(inputIndex)].moduleid,
              modulename: sourceLocationsArray[parseInt(inputIndex)].modulename,
              users: input.selectedValues()
            }
            indices.push(parseInt(inputIndex))
          }
        }
        console.log('changed indices', indices, tempModulesUsers)
        this.renderOnboardingGovUsers(sourceLocationsArray, tempModulesUsers, indices)
      })
    }

    const buttonApply = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
    buttonApply.addEventListener('click', () => {
      this.renderOnboardingGovUsers(sourceLocationsArray, mappedModuleUsers)
    })

    const buttonSave = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
    buttonSave.addEventListener('click', async () => {
      console.log('saving gov location', mappedModuleUsers);
      let response = await this.uploadMappedGovUsers(mappedModuleUsers)
      console.log('gov users save response', response);
      this.loadOnboardingMappedGovUsers()
    })

    const buttonToggleMoreBack = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');

      const buttonExportMappingCSV = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'flex';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'flex';
      const buttonLoadLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'flex';
      const buttonSaveLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'flex';
      const buttonSave = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      buttonSave.style.display = 'flex';

      const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV);
      buttonExportMappingCSVNew?.addEventListener('click', async () => {
        let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj

          let locationModuleKey = tempCsvObj.id + ";" + tempCsvObj.moduleid;
          tempCsvObj.users = mappedModuleUsers[locationModuleKey] ?? [];

          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        let csvData = Util.convertToCSV(csvArray);
        // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings);
        console.log('csvData', csvData);
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_gov_users_' + new Date().getTime() + '.csv');
        a.click()
      })

      const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal);
      buttonLoadLocalNew?.addEventListener('click', async () => {
        console.log('load-local');
        ((this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
      });

      const fileInput = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement;
      fileInput.value = '';
      const fileInputNew = Util.clearListeners(fileInput);
      fileInputNew.addEventListener('change', (e: any) => {

        var frCsv = new FileReader();
        frCsv.onload = () => {
          console.log('taggingarray onload called');
          console.log('csv result', frCsv.result);
          const tempArr = Util.parseCsv(frCsv.result + "");
          console.log('csv data', tempArr)
          let changeCount = 0;
          let tempModulesList: any = {}
          for (let obj of tempArr) {
            let locationModuleKey = obj.id + ";" + obj.moduleid;
            if (JSON.stringify(mappedModuleUsers[locationModuleKey]) != JSON.stringify(obj.users)) {
              if (mappedModuleUsers[locationModuleKey] == null && (obj.users == null || obj.users.length == 0)) {
                console.log('not adding to modules change', locationModuleKey, mappedModuleUsers[locationModuleKey], obj.users)
              } else {
                console.log('adding to modules change', locationModuleKey, mappedModuleUsers[locationModuleKey], obj.users)
                this.changedOnboardingItemIds.push(locationModuleKey)
                changeCount++
              }
            }
            tempModulesList[locationModuleKey] = {
              moduleid: obj.moduleid,
              modulename: obj.modulename,
              users: obj.users
            }
          }
          this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [
            () => {
              this.clearMessages();
              this.changedOnboardingItemIds = [];
              (buttonToggleMoreBack as HTMLButtonElement).click();
            },
            () => {
              this.clearMessages();
              this.renderOnboardingGovUsers(sourceLocationsArray, tempModulesList);
            }
          ])
          // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}}
          // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}}


        }
        if (e.target.files[0].name.toLowerCase().indexOf("users".toLowerCase()) >= 0) {
          frCsv.readAsText(e.target.files[0]);
        }
      })

      const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal);
      buttonSaveLocalNew?.addEventListener('click', async () => {
        console.log('save-local');
        let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj

          let locationModuleKey = tempCsvObj.id + ";" + tempCsvObj.moduleid;
          tempCsvObj.users = mappedModuleUsers[locationModuleKey] ?? [];

          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        const blob = new Blob([JSON.stringify(csvArray)], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_gov_users_' + new Date().toLocaleString() + '.txt');
        a.click()
      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';
      const buttonExportMappingCSV = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'none';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'none';
      const buttonLoadLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'none';
      const buttonSaveLocal = (this._SfOnboardingGovUsersContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'none';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'none';

    });

    this.changedOnboardingItemIds = [];
  }

  renderOnboardingGovLocations = (sourceLocationsArray: any, modulesMapping: any, changedIndices: number[] = [], changedValue: any = null) => {

    console.log('sourceLocationsArray', sourceLocationsArray);
    console.log('modulesMapping', modulesMapping);
    if (changedIndices.length == 0) {
      this.changedOnboardingItemIds = []
    } else {
      for (let changedIndex of changedIndices) {
        let changedId = sourceLocationsArray[changedIndex].id
        if (this.changedOnboardingItemIds.indexOf(changedId) < 0) {
          this.changedOnboardingItemIds.push(changedId)
        }
        modulesMapping[changedId] = changedValue
      }
    }
    let sourceCols = ["id", "name"]
    let uniqCols = ["modules"]

    var html: string = '';
    html += '<div id="gov-modules-list-container" class="pb-10 pt-10 w-100">';
    html += '<div class="d-flex justify-between flex-wrap align-center"> ';

    let tagged = 0
    var changed = 0
    for (let item of sourceLocationsArray) {
      let locationKey = item.id
      console.log('locationKey', locationKey, item)
      if (modulesMapping[locationKey] != null && modulesMapping[locationKey].length > 0) {
        tagged++;
      }
      if (this.changedOnboardingItemIds.indexOf(locationKey) >= 0) {
        changed++;
      }
    }
    var status = '';
    if (tagged < sourceLocationsArray.length) {
      status = '<span class="color-pending material-icons">pending</span>';
    } else {
      status = '<span class="color-done material-icons">check_circle</span>';
    }
    html += (`<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">${status}&nbsp;&nbsp; ${tagged} Locations mapped out of ${sourceLocationsArray.length}</h4></div>`);


    if (changed > 0) {
      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0"><span class="color-pending material-icons">pending</span>&nbsp;&nbsp;' + changed + ' Items changed</h4></div>')
    }
    html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="span-extra-filled" class="m-0" part="results-title"></h4></div>')

    html += '<div class="d-flex align-center">';
    // html += '<input part="input" type="text" placeholder="Filter" class="input-filter mr-10" value="'+subfilter+'" />';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'
    // html += '<div class="d-flex justify-end"><button part="button" class="align-center button-download-backups hide" style="position: absolute; margin-top: 5px;"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button></div>'
    html += '<div style="position: absolute; margin-top: 5px;">'
    html += '<button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping-csv" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">data_table</span><span>Export CSV</span></button>'

    // console.log('jobs', jobs);
    html += ('<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>');
    html += '</div>';
    html += '</div>';
    html += '<button part="button" class="button-apply d-flex align-center mr-10"><span class="material-symbols-outlined mr-10">touch_app</span><span>Apply</span></button>'
    html += '<button part="button" class="button-save d-flex align-center"><span class="material-symbols-outlined mr-10">save</span><span>Save On Cloud</span></button>'
    html += '</div>';

    html += '</div>';

    html += `
        <div class="sf-i-form-modal-container d-flex flex-col align-stretch hide" part="sf-i-form-modal-container" id="sf-i-form-modal-container">
          <div class="sf-i-form-modal-button-container d-flex justify-between align-center p-10" part="sf-i-form-modal-button-container">
            <button id="button-close-form" part="button-icon" class="button-icon-click"><span class="material-icons">keyboard_backspace</span></button>
            <button id="button-save-form" part="button-icon" class="button-icon-click"><span class="material-icons">check</span></button>
          </div>
          <div class="d-flex p-10" id="sf-i-form-container" part="sf-i-form-container"></div>
        </div>
        `

    html += '<table id="table-data" class="mt-20" style="height: 200px">';

    html += '<thead>';
    html += '<th part="td-head" class="td-head">'
    html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox"/></div>';
    html += '</th>'

    for (let i = 0; i < sourceCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += sourceCols[i];
      html += '</th>'
    }
    for (let i = 0; i < uniqCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += uniqCols[i];
      html += '</th>'
    }
    html += '</thead>';
    html += '<tbody>';

    for (let i = 0; i < sourceLocationsArray.length; i++) {

      var classBg = "";
      let item = sourceLocationsArray[i]
      let locationid = item.id
      if (i % 2 === 0) {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = locationid
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-light-selected';
          } else {
            classBg = 'td-light';
          }
        } else {
          classBg = 'td-light';
        }
      } else {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = locationid
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-dark-selected';
          } else {
            classBg = 'td-dark';
          }
        } else {
          classBg = 'td-dark';
        }
      }

      html += '<tr class="" id="tablerow-' + i + '">';

      // html += '<td class="left-sticky td-body ' + classBg + '" ><div class=""><input id="cb-' + i + '" type="checkbox" class="checkbox-row cb-select"/></div></td>';

      html += '<td class="left-sticky td-body ' + classBg + '" part="td-key">'
      html += '<div class="">';
      html += '<input id="locations-' + i + '" type="checkbox" part="input-checkbox" class="locations-input"/>';


      html += '</div>';
      html += '</td>'




      for (var l = 0; l < sourceCols.length; l++) {
        html += '<td class="td-body ' + classBg + '" part="td-body">';
        html += '<div class="">';

        html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + sourceLocationsArray[i][sourceCols[l]]) + '" minLength="20" lineSize="4"></sf-i-elastic-text>'
        html += '</div>';
        html += '</td>';

      }

      let modules = modulesMapping[locationid] ?? []
      // let moduleNames = modules.map((m: any) => {
      //   return m.locationname;
      // })
      html += '<td class="' + classBg + '" part="td-key">'
      html += `<div class="d-flex align-center" part="form-selected-value">
                            ${modules.map((m: any) => `
                              <div class="selected-option d-flex justtify-center align-center" part="selected-option" id="selected-option-${m.id}" dataid="${m.id}">
                                <label class="selected-option-label" part="selected-option-label">${m.name}</label>
                              </div>`).join('')}`
      html += '<button id="button-edit-form-' + i + '" part="button-icon" class="material-icons button-edit-form button-icon-click">edit</button>';
      html += '</div>';
      html += '</td>'

      html += '</tr>';
      //console.log('i=', i);

    }
    html += '</tbody>';
    html += '</table>';


    // html += '</div>';

    html += '</div>';

    (this._SfOnboardingGovLocationsContainer as HTMLDivElement).innerHTML = html;

    const selectAllCheckbox = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#select-all') as HTMLInputElement
    selectAllCheckbox.addEventListener('change', (e) => {
      let selCheckbox = e.target as HTMLInputElement
      let inputCheckboxes = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf<HTMLInputElement>
      console.log('input checkboxes found', inputCheckboxes.length, selCheckbox.checked)
      for (let inputCheckbox of inputCheckboxes) {
        inputCheckbox.checked = selCheckbox.checked;
      }
    })
    let editButtons = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.button-edit-form') as NodeListOf<HTMLButtonElement>
    console.log("edit buttons found", editButtons.length)
    for (let editButton of editButtons) {
      editButton.addEventListener('click', (e) => {
        let targetElement = e.target as HTMLButtonElement
        let targetId = targetElement.id ?? ""
        let index = targetId.split('button-edit-form-')[1]
        console.log('edit button clicked', index)
        let indices: number[] = [parseInt(index)]
        let inputCheckboxes = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelectorAll('.locations-input') as NodeListOf<HTMLInputElement>
        for (let inputCheckbox of inputCheckboxes) {
          let inputId = inputCheckbox.id ?? ""
          let inputIndex = inputId.split('locations-')[1]
          if (inputCheckbox.checked && inputIndex != null) {
            if (indices.indexOf(parseInt(inputIndex)) < 0) {
              indices.push(parseInt(inputIndex))
            }
          }
        }
        this.populateMultipleSelectModal(indices, 'Modules', modulesMapping[sourceLocationsArray[index].id] ?? [], (indices: number[], value: any) => { this.renderOnboardingGovLocations(sourceLocationsArray, modulesMapping, indices, value) })
      })
    }

    const buttonApply = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
    buttonApply.addEventListener('click', () => {
      this.renderOnboardingGovLocations(sourceLocationsArray, modulesMapping)
    })

    const buttonSave = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
    buttonSave.addEventListener('click', async () => {
      console.log('saving gov location', modulesMapping);
      let response = await this.uploadMappedGovLocations(modulesMapping)
      console.log('gov locations save response', response);
      this.loadOnboardingMappedGovLocations()
    })

    const buttonToggleMoreBack = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');

      const buttonExportMappingCSV = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'flex';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'flex';
      const buttonLoadLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'flex';
      const buttonSaveLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'flex';
      const buttonSave = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      buttonSave.style.display = 'flex';

      const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV);
      buttonExportMappingCSVNew?.addEventListener('click', async () => {
        let csvArray = JSON.parse(JSON.stringify(sourceLocationsArray))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj

          let locationKey = tempCsvObj.id;
          tempCsvObj.modules = modulesMapping[locationKey] ?? [];

          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        let csvData = Util.convertToCSV(csvArray);
        // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings);
        console.log('csvData', csvData);
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_gov_locations_' + new Date().getTime() + '.csv');
        a.click()
      })

      const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal);
      buttonLoadLocalNew?.addEventListener('click', async () => {
        console.log('load-local');
        ((this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
      });

      const fileInput = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement;
      fileInput.value = '';
      const fileInputNew = Util.clearListeners(fileInput);
      fileInputNew.addEventListener('change', (e: any) => {

        var frCsv = new FileReader();
        frCsv.onload = () => {
          console.log('taggingarray onload called');
          console.log('csv result', frCsv.result);
          const tempArr = Util.parseCsv(frCsv.result + "");
          console.log('csv data', tempArr)
          let changeCount = 0;
          let tempModulesList: any = {}
          for (let obj of tempArr) {
            let locationKey = obj.id
            if (JSON.stringify(modulesMapping[locationKey]) != JSON.stringify(obj.modules)) {
              if (modulesMapping[locationKey] == null && (obj.modules == null || obj.modules.length == 0)) {
                console.log('not adding to modules change', locationKey, modulesMapping[locationKey], obj.modules)
              } else {
                console.log('adding to modules change', locationKey, modulesMapping[locationKey], obj.modules)
                this.changedOnboardingItemIds.push(locationKey)
                changeCount++
              }
            }
            tempModulesList[locationKey] = obj.modules
          }
          this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [
            () => {
              this.clearMessages();
              this.changedOnboardingItemIds = [];
              (buttonToggleMoreBack as HTMLButtonElement).click();
            },
            () => {
              this.clearMessages();
              this.renderOnboardingGovLocations(sourceLocationsArray, tempModulesList);
            }
          ])
          // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}}
          // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}}


        }
        if (e.target.files[0].name.toLowerCase().indexOf("locations".toLowerCase()) >= 0) {
          frCsv.readAsText(e.target.files[0]);
        }
      })

      const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal);
      buttonSaveLocalNew?.addEventListener('click', async () => {
        console.log('save-local');
        const blob = new Blob([JSON.stringify(sourceLocationsArray)], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_suspense_' + new Date().toLocaleString() + '.txt');
        a.click()
      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';
      const buttonExportMappingCSV = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'none';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'none';
      const buttonLoadLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'none';
      const buttonSaveLocal = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'none';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'none';

    });

    this.changedOnboardingItemIds = [];
  }

  populateMultipleSelectModal = (indices: number[], label: string, value: any, saveCallback: Function) => {

    if (value.length == 0) {
      value.push('')
    }
    let formHtml = `
      <div part="select-container" class="d-flex flex-col flex-grow mt-20">
        ${value.map((_: any, i: number) => `
          <div class="d-flex align-end">
            <div class="d-flex flex-col flex-grow mr-10 mb-10">
            <sf-i-select class="reporting-sf-i-select" exportparts="input-select" id="input-select-${i}" part="input-sf-i-select" label="${label}" apiId="${this.apiIdModules}"></sf-i-select>
            </div>
            <button class="material-icons delete-subselect-button mb-20" part="button-icon-light" id="button-delete-${i}">delete</button>
          </div>
        `).join('')}
        <button class="add-subselect-button align-self-end mt-10" part="button" id="add-${indices[0]}">Add</button>
      </div>
    `
    console.log("rendering sf-i-muliple-subselect", indices)
    let selectContainer = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#sf-i-form-container') as HTMLDivElement
    selectContainer.innerHTML = formHtml
    let selectModalContainer = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#sf-i-form-modal-container') as HTMLDivElement
    selectModalContainer.style.display = 'block'
    let selectCloseButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#button-close-form') as HTMLButtonElement
    selectCloseButton.addEventListener('click', () => {
      selectModalContainer.style.display = 'none'
    })
    let selectAddButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#' + 'add-' + indices[0]) as HTMLButtonElement
    selectAddButton.addEventListener('click', () => {
      let elementValue: any = []
      if (value != null && value != '') {
        elementValue = value
      }
      if (elementValue.length == 0) {
        elementValue.push('')
      }
      console.log('add button clicked', elementValue);
      elementValue.push('')
      this.populateMultipleSelectModal(indices, label, elementValue, saveCallback);
    })
    let selectSaveButton = (this._SfOnboardingGovLocationsContainer as HTMLDivElement).querySelector('#button-save-form') as HTMLButtonElement
    let selectElements = selectContainer.querySelectorAll('sf-i-select') as NodeListOf<SfISelect>
    console.log('populateMultipleSelectModal value', value)
    for (let [i, selectElement] of selectElements.entries()) {
      if (value[i] != null && value[i] != '') {
        console.log('value found', value[i])
        let valObj = value[i]
        selectElement.selectedId = valObj.id
        selectElement.loadMode();
      }

      selectElement.addEventListener('valueChanged', (e) => {
        let target = e.target as SfISelect
        let selectId = target.id
        let selectIndex = selectId.split('input-select-')[1]
        console.log('selected value changed', selectId, target.selectedValues(), target.selectedTexts())
        let elementValue: any = []
        if (value != null && value != '') {
          elementValue = value
        }
        elementValue[selectIndex] = {
          name: target.selectedTexts()[0],
          id: target.selectedValues()[0]
        }
        if (JSON.stringify(value) !== JSON.stringify(elementValue)) {
          this.populateMultipleSelectModal(indices, label, elementValue, saveCallback);
        }
      })
    }

    let selectDeleteButtons = selectContainer.querySelectorAll('.delete-subselect-button') as NodeListOf<HTMLButtonElement>
    for (let deleteButton of selectDeleteButtons) {
      deleteButton.addEventListener('click', () => {
        let targetId = deleteButton.id
        let index = parseInt(targetId.split('-').slice(-1)[0])
        console.log('delete button clicked', targetId, index)
        let elementValue: any = []
        if (value != null && value != '') {
          elementValue = value
        }
        elementValue.splice(index, 1)
        value = elementValue
        this.populateMultipleSelectModal(indices, label, elementValue, saveCallback);
      })
    }

    selectSaveButton.addEventListener('click', async () => {
      let selectElements = selectContainer.querySelectorAll('sf-i-select') as NodeListOf<SfISelect>
      let valArr = []
      for (let selectElement of selectElements) {
        if (selectElement.selectedValues()[0] == null || selectElement.selectedValues()[0] == '') {
          continue;
        }
        let valObj: any = {
          name: selectElement.selectedTexts()[0],
          id: selectElement.selectedValues()[0]
        }
        valArr.push(valObj)
      }
      console.log('Values Selected', valArr)
      saveCallback(indices, valArr);
      selectModalContainer.style.display = 'none'
    })
    /* if (childElement.dependencies != null && childElement.dependencies.length > 0) {
      this.updateShortlistedSearchPhrases(childElement.id);
    } */
  }

  renderOnboardingSuspense = (sourceArray: any, suspenseList: any, year: string) => {

    console.log('sourceList', sourceArray);
    console.log('suspenseList', suspenseList, Object.keys(suspenseList).length);
    let sourceCols = ["shortid", "obligationtitle", "obligationtype"]
    let uniqCols = ["id", "entityname", "locationname"]
    let colName = 'suspense'
    var html: string = '';

    html += '<div id="suspense-list-container" class="pb-10 pt-10 w-100">';

    html += '<div class="d-flex justify-between flex-wrap align-center"> ';

    var status = '';
    status = '<span class="color-done material-icons">check_circle</span>';
    let tagged = 0
    var changed = 0
    let tempSourceArray = sourceArray
    console.log('suspensekey length', tempSourceArray.data.mappings.mappings.length)
    for (let [itemIndex, item] of tempSourceArray.data.mappings.mappings.entries()) {
      let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id
      if (item.id == "de6ecf68-673d-41ef-9b13-4d2042910f16") {
        console.log('suspensekey', suspenseKey, suspenseList[suspenseKey], item)
      }
      if (suspenseList[suspenseKey] != null && suspenseList[suspenseKey] != false) {
        tagged++;
      }
      tempSourceArray.data.mappings.mappings[itemIndex].suspense = suspenseList[suspenseKey] != null
      if (this.changedOnboardingItemIds.indexOf(suspenseKey) >= 0) {
        changed++;
      }
    }
    let pastFiscals = [parseInt(this.getCurrentYearGeneric())]
    if (this.contractStartDate != null) {
      console.log('contractStartDate', this.contractStartDate);
      let startDD = this.contractStartDate.split('/')[0]
      let startMM = this.contractStartDate.split('/')[1]
      let startYYYY = this.contractStartDate.split('/')[2]
      pastFiscals = this.getAllPastFiscals(new Date(startMM + '/' + startDD + '/' + startYYYY));
    }
    console.log('pastFiscals', pastFiscals)
    html += (`<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">${status}&nbsp;&nbsp; ${tagged} in Suspense List out of ${sourceArray.data.mappings.mappings.length}</h4><h6 class="ml-20" part="onboarding-suspense-year-label">Year</h6><select id="select-year" part="input">${pastFiscals.map((fiscal) => {
      return `<option value="${fiscal}"${fiscal == parseInt(year) ? " selected" : ""}>${fiscal}-${(fiscal % 100) + 1}</option>`
    })}</select></div>`);


    if (changed > 0) {
      html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 part="results-title" class="d-flex align-center m-0"><span class="color-pending material-icons">pending</span>&nbsp;&nbsp;' + changed + ' Items changed</h4></div>')
    }
    html += ('<div class="left-sticky d-flex justify-between align-center mr-10"><h4 id="span-extra-filled" class="m-0" part="results-title"></h4></div>')

    html += '<div class="d-flex align-center">';
    // html += '<input part="input" type="text" placeholder="Filter" class="input-filter mr-10" value="'+subfilter+'" />';
    html += '<div class="mr-10">';
    html += '<div class="d-flex justify-end"><button part="calendar-tab-icon-not-selected" class="material-icons button-toggle-more">expand_more</button><button part="calendar-tab-icon-selected" class="material-icons button-toggle-more-back hide">expand_less</button></div>'
    // html += '<div class="d-flex justify-end"><button part="button" class="align-center button-download-backups hide" style="position: absolute; margin-top: 5px;"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button></div>'
    html += '<div style="position: absolute; margin-top: 5px;">'
    html += '<button part="button" class="hide d-flex align-center button-download-backups" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">file_save</span><span>Download Backups</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">export_notes</span><span>Export Mapping</span></button><button part="button" class="mt-10 hide d-flex align-center button-export-mapping-csv" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">data_table</span><span>Export CSV</span></button>'

    // console.log('jobs', jobs);
    html += ('<input id="fileInput" type="file" style="display:none;" /><button part="button" class="mt-10 hide button-local-load d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">upload_file</span><span>Load From Local</span></button><button part="button" class="mt-10 hide button-local-save d-flex align-center mr-10" style="margin-left: -80px"><span class="material-symbols-outlined mr-10">save</span><span>Save Locally</span></button>');
    html += '</div>';
    html += '</div>';
    html += '<button part="button" class="button-apply d-flex align-center mr-10"><span class="material-symbols-outlined mr-10">touch_app</span><span>Apply</span></button>'
    html += '<button part="button" class="button-save d-flex align-center"><span class="material-symbols-outlined mr-10">save</span><span>Save On Cloud</span></button>'
    html += '</div>';

    html += '</div>';

    html += '<div>';
    html += '<h4 id="span-filtered" part="results-title"></h4>'
    html += '<div id="div-subfiltered"></div>'
    html += '</div>';

    html += '<br />';

    // html += '<div class="d-flex justify-center align-center w-100 mt-20 scroll-x">';
    html += '<table id="table-data" class="mt-20" style="height: 200px">';

    html += '<thead>';
    // html += '<th part="td-head" class="td-head">'
    // html += '<div id="select-all"><input class="checkbox checkbox-all" part="input-checkbox" type="checkbox" ' + ((this.disableflagggrcresponse.toLowerCase() == "yes") ? 'disabled' : '') + '/></div>';
    // html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += colName;
    html += '</th>'
    for (let i = 0; i < uniqCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += uniqCols[i];
      html += '</th>'
    }
    for (let i = 0; i < sourceCols.length; i++) {
      html += '<th part="td-head" class="td-head">'
      html += sourceCols[i];
      html += '</th>'
    }
    html += '</thead>';
    html += '<tbody>';
    // console.log('changedIds', this.changedOnboardingItemIds);
    for (let i = 0; i < sourceArray.data.mappings.mappings.length; i++) {

      var classBg = "";
      let item = sourceArray.data.mappings.mappings[i]
      let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id
      if (i % 2 === 0) {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = suspenseKey
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-light-selected';
          } else {
            classBg = 'td-light';
          }
        } else {
          classBg = 'td-light';
        }
      } else {
        if (this.changedOnboardingItemIds.length > 0) {
          let changedId = item.entityid + ';' + item.locationid + ';' + item.id
          if (this.changedOnboardingItemIds.indexOf(changedId) >= 0) {
            classBg = 'td-dark-selected';
          } else {
            classBg = 'td-dark';
          }
        } else {
          classBg = 'td-dark';
        }
      }

      html += '<tr class="" id="tablerow-' + i + '">';

      // html += '<td class="left-sticky td-body ' + classBg + '" ><div class=""><input id="cb-' + i + '" type="checkbox" class="checkbox-row cb-select"/></div></td>';

      html += '<td class="left-sticky td-body ' + classBg + '" part="td-key">'
      html += '<div class="">';
      html += '<input id="suspense-' + i + '" type="checkbox" class="suspense-input"' + ((suspenseList[suspenseKey] != null && suspenseList[suspenseKey] != false) ? ' checked' : '') + '/>';


      html += '</div>';
      html += '</td>'

      for (var l = 0; l < uniqCols.length; l++) {
        // console.log('uniqcolval', uniqCols[l], sourceArray.data.mappings.mappings[i], sourceArray.data.mappings.mappings[i][uniqCols[l]]);
        html += '<td class="' + classBg + '" part="td-body">'
        html += '<div class="">';
        html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + sourceArray.data.mappings.mappings[i][uniqCols[l]].replace(/ *\([^)]*\) */g, "") + '" minLength="20"></sf-i-elastic-text>';
        html += '</div>';
        html += '</td>'
      }


      for (l = 0; l < sourceCols.length; l++) {

        for (var j = 0; j < JSON.parse(sourceArray.data.mappings.mappings[0].cols).length; j++) {

          if (sourceCols[l] == JSON.parse(sourceArray.data.mappings.mappings[0].cols)[j]) {

            if (sourceArray.data.mappings.mappings[i].data != null) {

              html += '<td class="td-body ' + classBg + '" part="td-body">';
              html += '<div class="">';

              //console.log('isArray', sourceCols[l], Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j]));
              if (Array.isArray(JSON.parse(sourceArray.data.mappings.mappings[i].data)[j])) {

                for (var k = 0; k < JSON.parse(sourceArray.data.mappings.mappings[i].data)[j].length; k++) {
                  html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[j][k] + '" minLength="100" lineSize="4"></sf-i-elastic-text>');
                }

              } else {
                html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(sourceArray.data.mappings.mappings[i].data)[j] + '" minLength="100" lineSize="4"></sf-i-elastic-text>')
              }

              html += '</div>';
              html += '</td>';

            }

          }

        }

      }

      html += '</tr>';
      //console.log('i=', i);

    }
    html += '</tbody>';
    html += '</table>';


    // html += '</div>';

    html += '</div>';

    (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = html;
    const inputYear = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#select-year') as HTMLSelectElement;
    inputYear.addEventListener('change', (e: any) => {
      const selectedYear = e.currentTarget.value;
      this.loadOnboardingSuspense(selectedYear);
    })

    const buttonApply = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
    buttonApply.addEventListener('click', () => {
      let inputSuspenseCheckboxes = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelectorAll('.suspense-input') as NodeListOf<HTMLInputElement>;
      let tempSuspenseList: any = {}
      for (let inputSuspenseCheckbox of inputSuspenseCheckboxes) {
        let index = inputSuspenseCheckbox.id.split("-")[1]
        if (inputSuspenseCheckbox.checked) {
          let item = sourceArray.data.mappings.mappings[index]
          let suspenseKey = item.entityid + ';' + item.locationid + ';' + item.id
          tempSuspenseList[suspenseKey] = true
        }
      }
      this.renderOnboardingSuspense(sourceArray, tempSuspenseList, year)
    })

    const buttonSave = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
    buttonSave.addEventListener('click', async () => {
      console.log('saving suspense', suspenseList, Object.keys(suspenseList).length);
      let response = await this.uploadMappedSuspense(suspenseList, year)
      console.log('suspense save response', response);
      this.loadOnboardingSuspense(year)
    })

    const buttonToggleMoreBack = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-toggle-more-back') as HTMLButtonElement;
    const buttonToggleMore = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-toggle-more') as HTMLButtonElement;

    buttonToggleMore.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMoreBack.classList.remove('hide');

      const buttonExportMappingCSV = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'flex';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'flex';
      const buttonLoadLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'flex';
      const buttonSaveLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'flex';
      const buttonSave = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      buttonSave.style.display = 'flex';

      const buttonExportMappingCSVNew = Util.clearListeners(buttonExportMappingCSV);
      buttonExportMappingCSVNew?.addEventListener('click', async () => {
        let csvArray = JSON.parse(JSON.stringify(sourceArray.data.mappings.mappings))
        for (let [i, obj] of csvArray.entries()) {
          let tempCsvObj = obj
          if (obj['cols'] != null && obj['data'] != null) {
            let dataArr = JSON.parse(obj['data'])
            let colsArr = JSON.parse(obj['cols'])
            for (let [j, colKey] of colsArr.entries()) {
              tempCsvObj['cols_' + colKey] = dataArr[j]
            }
          }
          let suspenseKey = tempCsvObj.entityid + ';' + tempCsvObj.locationid + ';' + tempCsvObj.id;
          tempCsvObj.suspense = (suspenseList[suspenseKey] != null && suspenseList[suspenseKey] != false) ? true : false;

          csvArray[i] = tempCsvObj
        }
        console.log('csv array', csvArray)
        let csvData = Util.convertToCSV(csvArray);
        // let csvData = Util.convertToCSV(taggingArray.data.mappings.mappings);
        console.log('csvData', csvData);
        const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_suspense_' + new Date().getTime() + '.csv');
        a.click()
      })

      const buttonLoadLocalNew = Util.clearListeners(buttonLoadLocal);
      buttonLoadLocalNew?.addEventListener('click', async () => {
        console.log('load-local');
        ((this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#fileInput') as HTMLInputElement).click();
      });

      const fileInput = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('#fileInput') as HTMLButtonElement;
      fileInput.value = '';
      const fileInputNew = Util.clearListeners(fileInput);
      fileInputNew.addEventListener('change', (e: any) => {

        var frCsv = new FileReader();
        frCsv.onload = () => {
          console.log('taggingarray onload called');
          console.log('csv result', frCsv.result);
          const tempArr = Util.parseCsv(frCsv.result + "");
          console.log('csv data', tempArr)
          let changeCount = 0;
          let tempSuspenseList: any = {}
          for (let obj of tempArr) {
            let suspenseKey = obj.entityid + ';' + obj.locationid + ';' + obj.id
            if ((suspenseList[suspenseKey] == null && obj.suspense == true) || (suspenseList[suspenseKey] != null && obj.suspense == false)) {
              console.log('adding to suspense change', suspenseKey, suspenseList[suspenseKey], obj.suspense)
              this.changedOnboardingItemIds.push(suspenseKey)
              changeCount++
            }
            tempSuspenseList[suspenseKey] = obj.suspense
          }
          this.setSuccessBtn(changeCount + " items changed. Do you wish to apply?", ["No", "Yes"], [
            () => {
              this.clearMessages();
              this.changedOnboardingItemIds = [];
              (buttonToggleMoreBack as HTMLButtonElement).click();
            },
            () => {
              this.clearMessages();
              this.renderOnboardingSuspense(sourceArray, tempSuspenseList, year);
            }
          ])
          // let tempObj:any = {"data":{"mappings":{"mappings":tempArr}}}
          // let tempObj:{data:{mappings:{mappings:any[]}}} = {data:{mappings:{mappings:tempArr}}}


        }
        if (e.target.files[0].name.toLowerCase().indexOf("suspense".toLowerCase()) >= 0) {
          frCsv.readAsText(e.target.files[0]);
        }
      })

      const buttonSaveLocalNew = Util.clearListeners(buttonSaveLocal);
      buttonSaveLocalNew?.addEventListener('click', async () => {
        console.log('save-local');
        const blob = new Blob([JSON.stringify(sourceArray)], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'mapping_suspense_' + new Date().toLocaleString() + '.txt');
        a.click()
      });

    });

    buttonToggleMoreBack.addEventListener('click', async (ev: any) => {

      ev.target.classList.add('hide');
      buttonToggleMore.classList.remove('hide');
      const buttonDownloadBackups = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-download-backups') as HTMLButtonElement;
      buttonDownloadBackups.style.display = 'none';
      const buttonExportMapping = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping') as HTMLButtonElement;
      buttonExportMapping.style.display = 'none';
      const buttonExportMappingCSV = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-export-mapping-csv') as HTMLButtonElement;
      buttonExportMappingCSV.style.display = 'none';
      // const buttonApply = (divElement as HTMLDivElement).querySelector('.button-apply') as HTMLButtonElement;
      // buttonApply.style.display = 'none';
      const buttonLoadLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-load') as HTMLButtonElement;
      buttonLoadLocal.style.display = 'none';
      const buttonSaveLocal = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelector('.button-local-save') as HTMLButtonElement;
      buttonSaveLocal.style.display = 'none';
      // const buttonSave = (divElement as HTMLDivElement).querySelector('.button-save') as HTMLButtonElement;
      // buttonSave.style.display = 'none';

    });

    this.changedOnboardingItemIds = [];
  }

  renderOnboardingSuspenseOld = (_suspenseList: any) => {

    //console.log('calendarjobs', calendarJobs);

    var html = '';

    html += '<div id="suspense-list-container" class="pb-10 pt-10 w-100">';



    html += '<div class="d-flex justify-center align-center w-100 mt-20 scroll-x">';
    if (Object.keys(_suspenseList).length === 0) {
      html += '<div part="no-suspense-title-container" class="d-flex mb-20"><span part="no-suspense-title">No Suspense Items</span></div>';
    } else {
      html += '<table>';
      let tableBodyHtml = ''
      for (var j = 0; j < Object.keys(_suspenseList).length; j++) {

        let uniqueKey = Object.keys(_suspenseList)[j];
        console.log('uniqueKey', uniqueKey);
        let eventid = uniqueKey.split(';')[2];
        let suspenseObj = _suspenseList[uniqueKey];
        console.log('suspenseObj', suspenseObj);
        tableBodyHtml += '<tr>';
        tableBodyHtml += ('<td class="td-body left-sticky" part="td-body-suspense"><button part="button-icon" id="button-icon-suspense-done-' + j + '" class="button-icon-suspense-done d-flex align-center"><span class="material-symbols-outlined">done</span>&nbsp;&nbsp;Done</button></td>');

        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + eventid + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + suspenseObj.obligationtitle + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + suspenseObj.obligation + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + suspenseObj.entityname + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + suspenseObj.locationname + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        let reporters = ""
        if (suspenseObj.reporters != null && suspenseObj.reporters.length > 0 && Array.isArray(suspenseObj.reporters)) {
          for (let reporter of suspenseObj.reporters) {
            reporters += reporter.split(';')[0]
            if (suspenseObj.reporters.indexOf(reporter) < suspenseObj.reporters.length - 1) {
              reporters += ', '
            }
          }
        }
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + reporters + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        let approvers = ""
        if (suspenseObj.approvers != null && suspenseObj.approvers.length > 0 && Array.isArray(suspenseObj.approvers)) {
          for (let approver of suspenseObj.approvers) {
            approvers += approver.split(';')[0]
            if (suspenseObj.approvers.indexOf(approver) < suspenseObj.approvers.length - 1) {
              approvers += ', '
            }
          }
        }
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + approvers + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        let functionheads = ""
        if (suspenseObj.functionheads != null && suspenseObj.functionheads.length > 0 && Array.isArray(suspenseObj.functionheads)) {
          for (let functionhead of suspenseObj.functionheads) {
            functionheads += functionhead.split(';')[0]
            if (suspenseObj.functionheads.indexOf(functionhead) < suspenseObj.functionheads.length - 1) {
              functionheads += ', '
            }
          }
        }
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + functionheads + '" minLength="10" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += ('<td class="td-body" part="td-body-suspense"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + (suspenseObj.message ?? "") + '" minLength="30" lineSize="4"></sf-i-elastic-text></td>');
        tableBodyHtml += '</tr>';
      }
      html += '<thead><tr>';
      html += '<th class="td-body" part="td-body-suspense"><span part="td-head" style="padding-left: 0px !important"></span></th>'


      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Complaince Id</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Obligation Title</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Obligation</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Entity</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Location</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Reporter</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Approver</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Functionhead</span></th>'
      html += '<th class="td-body" part="td-body-suspense"><div class="d-flex align-start"><span part="td-head">Message</span></th>'

      html += '</tr></thead>';
      html += tableBodyHtml;
      html += '</table>';
    }
    html += '</div>';

    html += '</div>';

    (this._SfOnboardingSuspenseContainer as HTMLDivElement).innerHTML = html;

    const arrButtonsDone = (this._SfOnboardingSuspenseContainer as HTMLDivElement).querySelectorAll('.button-icon-suspense-done') as NodeListOf<HTMLInputElement>;
    for (var i = 0; i < arrButtonsDone.length; i++) {
      arrButtonsDone[i].addEventListener('click', async (e: any) => {
        const id = e.currentTarget.id;
        const index = id.split("-")[4];
        await this.deleteFromSuspense(Object.keys(_suspenseList)[index], this.getCurrentYearGeneric());
        await this.loadOnboardingSuspense();
      });
    }
  }

  renderOnboardingCalendar = (_calendarJobs: any) => {

    //console.log('calendarjobs', calendarJobs);

    var html = '';

    html += '<div id="calendar-list-container" class="pb-10 pt-10 w-100">';

    // html += '<div class="d-flex justify-center align-center w-100">';
    //   html += '<h2 part="results-title">Calendar</h2>';
    // html += '</div>';

    // if(calendarJobs.data != null) {

    //   html += '<div class="d-flex justify-center align-center w-100">';

    //     html += '<div class="p-10">';
    //       html += '<div part="input-label" class="text-center">Job Status</div>';
    //       html += '<div class="d-flex align-center text-center">' + (calendarJobs.data.status == "0" ? "<span class=\"color-not-started material-icons\">schedule</span>&nbsp;Initialized" : calendarJobs.data.status == "1" ? "<span class=\"color-pending material-icons\">pending</span>&nbsp;In-Progress" : "<span class=\"color-done material-icons\">check_circle</span>&nbsp;Complete" ) + '</div>';
    //     html += '</div>';

    //     html += '<div class="p-10">';
    //       html += '<div part="input-label" class="text-center">Last Updated</div>';
    //       html += '<div class="text-center">' + new Date(calendarJobs.data.lastupdated).toLocaleString() + '</div>';
    //     html += '</div>';
    //   html += '</div>';

    // }

    html += '<div class="d-flex justify-center align-center w-100 mt-20">';
    html += '<select id="select-year" class="mr-10"><option value="2026">2026-27</option><option value="2025">2025-26</option><option value="2024">2024-25</option><option value="2023">2023-24</option></select>'
    html += '<button part="button" class="button-submit d-flex align-center"><span class="material-icons">bolt</span>&nbsp;<span>Update Calendar</span></button>';
    html += '</div>';

    html += '</div>';

    (this._SfOnboardingCalendarContainer as HTMLDivElement).innerHTML = html;

    (this._SfOnboardingCalendarContainer as HTMLDivElement).querySelector('.button-submit')?.addEventListener('click', async () => {
      const year = ((this._SfOnboardingCalendarContainer as HTMLDivElement).querySelector('#select-year') as HTMLSelectElement).value;
      //console.log(year);
      await this.fetchGetMappedCalendar(year);
      // const usermap = await this.fetchGetMappedCalendar(year);
      this.setSuccess('Calendar Job scheduled. Please check back after a few minutes.')
      setTimeout(() => {
        this.clearMessages()
      }, 5000)
      // if(usermap == null || usermap.usermap == null) {
      //   this.setError(usermap.error);
      //   setTimeout(() => {
      //     this.clearMessages()
      //   }, 10000);
      // } else {
      //   await this.fetchUpdateUsermap(usermap.usermap);
      // }

    });

    //this.refreshCalendar();

  }

  renderOnboardingTriggers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedTriggers: any) => {

    this.renderTaggingTableNew((this._SfOnboardingTriggersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedTriggers, ["shortid", "obligationtitle", "obligationtype"], this.uploadTriggersMapping, this.loadOnboardingTriggers, "triggers", ["id"], '', "", ["triggers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingInternalControls = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedInternalControls: any) => {

    this.renderTaggingTableNew((this._SfOnboardingInternalControlsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedInternalControls, ["shortid", "obligationtitle", "obligationtype"], this.uploadInternalControlsMapping, this.loadOnboardingInternalControls, "internalcontrols", ["id", "entityname", "locationname"], '', "", ["internalcontrols"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingReportedLocations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedReportedLocations: any) => {

    this.renderTaggingTableNew((this._SfOnboardingReportedLocationsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedReportedLocations, ["shortid", "obligationtitle", "obligationtype"], this.uploadReportedLocationsMapping, this.loadOnboardingReportedLocations, "reportedlocations", ["id", "entityname", "locationname"], '', "", ["reportedlocations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingActivations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedActivations: any) => {

    this.renderTaggingTableNew((this._SfOnboardingActivationListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedActivations, ["shortid", "obligationtitle", "obligationtype"], this.uploadActivationsMapping, this.loadOnboardingActivations, "activations", ["id", "entityname", "locationname"], '', "", ["activations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingInvalidations = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedInvalidations: any) => {

    this.renderTaggingTableNew((this._SfOnboardingInvalidationListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedInvalidations, ["shortid", "obligationtitle", "obligationtype"], this.uploadInvalidationsMapping, this.loadOnboardingInvalidations, "invalidations", ["id", "entityname", "locationname"], '', "", ["invalidations"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingAlertSchedules = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedAlertSchedules: any) => {

    this.renderTaggingTableNew((this._SfOnboardingAlertSchedulesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedAlertSchedules, ["shortid", "obligationtitle", "obligationtype"], this.uploadAlertSchedulesMapping, this.loadOnboardingAlertSchedules, "alertschedules", ["id", "entityname", "locationname"], '', "", ["alertschedules"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingExtensions = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedExtensions: any) => {

    this.renderTaggingTableNew((this._SfOnboardingExtensionsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedExtensions, ["shortid", "obligationtitle", "obligationtype"], this.uploadExtensionsMapping, this.loadOnboardingExtensions, "extensions", ["id", "entityname", "locationname"], '', "", ["extensions"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingDuedates = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedDuedates: any) => {

    this.renderTaggingTableNew((this._SfOnboardingDuedatesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedDuedates, ["shortid", "obligationtitle", "obligationtype"], this.uploadDuedatesMapping, this.loadOnboardingDuedates, "duedates", ["id", "entityname", "locationname"], '', "", ["duedates"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingReporters = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedReporters: any) => {

    this.renderTaggingTableNew((this._SfOnboardingReportersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedReporters, ["shortid", "obligationtitle", "obligationtype"], this.uploadReportersMapping, this.loadOnboardingReporters, "reporters", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["reporters"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", "");

  }

  renderOnboardingApprovers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedApprovers: any) => {

    this.renderTaggingTableNew((this._SfOnboardingApproversListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedApprovers, ["shortid", "obligationtitle", "obligationtype"], this.uploadApproversMapping, this.loadOnboardingApprovers, "approvers", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["approvers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", "");

  }

  renderOnboardingFunctionHeads = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedFunctionHeads: any) => {


    this.renderTaggingTableNew((this._SfOnboardingFunctionHeadsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedFunctionHeads, ["shortid", "obligationtitle", "obligationtype"], this.uploadFunctionHeadsMapping, this.loadOnboardingFunctionHeads, "functionheads", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["functionheads"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", "");

  }

  renderOnboardingMakerCheckers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedMakerCheckers: any) => {

    this.renderTaggingTableNew((this._SfOnboardingMakerCheckersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedMakerCheckers, ["shortid", "obligationtitle", "obligationtype"], this.uploadMakerCheckersMapping, this.loadOnboardingMakerCheckers, "makercheckers", ["id", "entityname", "locationname"], this.apiIdTags, "&MakerChecker", ["makercheckers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingDocs = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedDocs: any) => {

    this.renderTaggingTableNew((this._SfOnboardingDocsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedDocs, ["shortid", "obligationtitle", "obligationtype"], this.uploadDocsMapping, this.loadOnboardingDocs, "docs", ["id", "entityname", "locationname"], this.apiIdTags, "&MakerChecker", ["docs"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingAuditors = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedAuditors: any) => {

    this.renderTaggingTableNew((this._SfOnboardingAuditorsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedAuditors, ["shortid", "obligationtitle", "obligationtype"], this.uploadAuditorsMapping, this.loadOnboardingAuditors, "auditors", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["auditors"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", "");

  }

  renderOnboardingViewers = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedViewers: any) => {

    this.renderTaggingTableNew((this._SfOnboardingViewersListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedViewers, ["shortid", "obligationtitle", "obligationtype"], this.uploadViewersMapping, this.loadOnboardingViewers, "viewers", ["id", "entityname", "locationname"], this.apiIdUsers, "", ["viewers"], ["id", "countryid", "entityid", "locationid"], null, [], null, "Guidelines", "");

  }

  renderOnboardingTags = (selectedStatutes: any, mappedCompliances: any, mappedFunctions: any, mappedTags: any) => {

    this.renderTaggingTableNew((this._SfOnboardingTagsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedFunctions, mappedTags, ["shortid", "obligationtitle", "obligationtype"], this.uploadTagsMapping, this.loadOnboardingTags, "tags", ["id", "entityname", "locationname"], this.apiIdTags, "&Tag", ["tags"], ["id", "countryid", "entityid", "locationid"], "tagtype", [], null, "", "");

  }

  renderOnboardingFunctions = (selectedStatutes: any, mappedCompliances: any, mappedLocations: any, mappedFunctions: any) => {

    this.renderTaggingTableNew((this._SfOnboardingFunctionsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedLocations, mappedFunctions, ["shortid", "obligationtitle", "obligationtype"], this.uploadFunctionsMapping, this.loadOnboardingFunctions, "functions", ["id", "entityname", "locationname"], this.apiIdTags, "&Function", ["functions"], ["id", "countryid", "entityid", "locationid"], null, [], null, "", "");

  }

  renderOnboardingLocations = (selectedStatutes: any, mappedCompliances: any, mappedEntities: any, mappedLocations: any) => {

    this.renderTaggingTableNew((this._SfOnboardingLocationsListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedEntities, mappedLocations, ["shortid", "applicability", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute", "reference", "activations", "invalidations"], this.uploadLocationsMapping, this.loadOnboardingLocations, "locations", ["id", "entityname"], this.apiIdTags, "&Location", ["locationname", "locationid"], ["id", "countryid", "entityid"], null, [], null, "", "");

  }

  renderOnboardingStatutesDropdownMapping = (container: HTMLDivElement, mappedStatutes: any, selectedStatutes: any, fetchtaggingfunction: Function, rendermappingfunction: Function) => {
    console.log('rendering dropdown', mappedStatutes.length);
    var html = '';

    html += '<div class="d-flex flex-col w-100" style="height: 75vh">';
    html += '<div class="d-flex flex-col justify-center align-stretch w-100">';
    html += '<label part="input-label">Select Statute</label>';
    html += '<sf-multiselect-search part="sf-multiselect-onboarding" mode="edit" exportparts="input:multiselect-input, button-icon:multiselect-button-icon, button-icon-light:multiselect-button-icon-light, multiselect-item:multiselect-item, multiselect-checkbox:multiselect-checkbox, multiselect-checkbox-label:multiselect-checkbox-label, multiselect-item-select-all:multiselect-item-select-all, multiselect-checkbox-select-all-label:multiselect-checkbox-select-all-label, selected-list:multiselect-selected-list, selected-item:multiselect-selected-item, selected-unselect:multiselect-selected-unselect, selected-label:multiselect-selected-label" id="statute-select"></sf-multiselect-search>';
    html += '</div>';

    html += '<div id="compliances-list-container" class="d-flex flex-col w-100 scroll-x">';
    html += '</div>';
    html += '</div>';
    console.log('attaching html', html);
    container.innerHTML = html;

    let multiselectStatute = container.querySelector('#statute-select') as SfMultiselectSearch;
    multiselectStatute.listelements = mappedStatutes;
    let selectedStatutesObj: any = {}
    for (let statuteObj of selectedStatutes) {
      selectedStatutesObj[statuteObj.id] = true
    }
    multiselectStatute.listselection = selectedStatutesObj;
    multiselectStatute.loadMode();
    multiselectStatute.addEventListener('valueChanged', async (e: any) => {
      let multiselect = e.currentTarget as SfMultiselectSearch;
      console.log('selected statutes', multiselect.selectedValuesNames());
      if (Object.keys(multiselect.selectedValuesNames()).length == 0) {
        return;
      }
      let selectedStatutes = [];
      const regex = /^\[.*?\] - /;
      for (let statuteid of Object.keys(multiselect.selectedValuesNames())) {
        selectedStatutes.push({ id: statuteid, selected: true, statutename: multiselect.selectedValuesNames()[statuteid].name.replace(regex, '') });
      }

      let mappedCompliances = await fetchtaggingfunction(Object.keys(multiselect.selectedValuesNames()));

      rendermappingfunction({ data: { mappings: { mappings: selectedStatutes } } }, mappedCompliances);
    })
  }

  renderOnboardingStatutesDropdownTagging = (container: HTMLDivElement, listcontainerid: string, mappedStatutes: any, selectedStatutes: any, fetchcompliancesfunction: Function, fetchsourcemapping: Function, fetchtaggingfunction: Function, rendertaggingfunction: Function) => {
    console.log('rendering dropdown', mappedStatutes.length);
    var html = '';

    html += '<div class="d-flex justify-start align-center mb-10">';
    html += '<button id="mapping-count-button" part="button-icon" class="d-flex align-center"><span class="material-symbols-outlined">event_list</span>&nbsp;&nbsp;Mapping Count</button>'
    html += '<div id="mapping-count-container" part="mapping-count-container"></div>'
    html += '</div>'
    html += '<div class="d-flex flex-col w-100" style="height: 75vh">';
    html += '<div class="d-flex flex-col justify-center align-stretch w-100">';
    html += '<label part="input-label">Select Statute</label>';
    html += '<sf-multiselect-search part="sf-multiselect-onboarding" mode="edit" exportparts="input:multiselect-input, button-icon:multiselect-button-icon, button-icon-light:multiselect-button-icon-light, multiselect-item:multiselect-item, multiselect-checkbox:multiselect-checkbox, multiselect-checkbox-label:multiselect-checkbox-label, multiselect-item-select-all:multiselect-item-select-all, multiselect-checkbox-select-all-label:multiselect-checkbox-select-all-label, selected-list:multiselect-selected-list, selected-item:multiselect-selected-item, selected-unselect:multiselect-selected-unselect, selected-label:multiselect-selected-label" id="statute-select"></sf-multiselect-search>';
    html += '</div>';

    html += '<div id="' + listcontainerid + '" class="d-flex flex-col w-100 scroll-x mt-20">';
    html += '</div>';
    html += '</div>';
    console.log('attaching html', html);
    container.innerHTML = html;

    let multiselectStatute = container.querySelector('#statute-select') as SfMultiselectSearch;
    multiselectStatute.listelements = mappedStatutes;
    let selectedStatutesObj: any = {}
    for (let statuteObj of selectedStatutes) {
      selectedStatutesObj[statuteObj.id] = true
    }
    multiselectStatute.listselection = selectedStatutesObj;
    multiselectStatute.loadMode();
    multiselectStatute.addEventListener('valueChanged', async (e: any) => {
      let multiselect = e.currentTarget as SfMultiselectSearch;
      console.log('selected statutes', multiselect.selectedValuesNames());
      if (Object.keys(multiselect.selectedValuesNames()).length == 0) {
        return;
      }
      let selectedStatutes = [];
      const regex = /^\[.*?\] - /;
      for (let statuteid of Object.keys(multiselect.selectedValuesNames())) {
        selectedStatutes.push({ id: statuteid, selected: true, statutename: multiselect.selectedValuesNames()[statuteid].name.replace(regex, '') });
      }

      let sourceMappingArray = await fetchsourcemapping(Object.keys(multiselect.selectedValuesNames()));
      let mappingArray = await fetchtaggingfunction(Object.keys(multiselect.selectedValuesNames()));
      let mappedCompliances = await fetchcompliancesfunction(Object.keys(multiselect.selectedValuesNames()));
      let mappedCompliancesArr: any = { data: { mappings: {} } };
      console.log('mapped compliances', mappedCompliances)
      for (let statuteObj of selectedStatutes) {
        for (let complianceid of Object.keys(mappedCompliances.data.mappings[statuteObj.id] ?? {})) {
          let pushObj = mappedCompliances.data.mappings[statuteObj.id][complianceid];
          pushObj.id = complianceid;
          pushObj.statuteid = statuteObj.id;
          mappedCompliancesArr.data.mappings[complianceid] = pushObj;
        }
      }
      rendertaggingfunction(selectedStatutes, mappedCompliancesArr, sourceMappingArray, mappingArray);
    })

    let mappingCountButton = container.querySelector('#mapping-count-button') as HTMLButtonElement
    mappingCountButton.addEventListener('click', () => {
      this.getMappingCount(container)
    })
  }

  getMappingCount = async (container: HTMLDivElement) => {
    let id = container.id
    let onboardingstep = id.split('-')[0]
    let countResult = await this.fetchMappingCount(onboardingstep)
    console.log('count result', countResult)
    if (countResult.result == true) {
      let total = countResult.totalCount;
      let tagged = countResult.mappedCount;
      var status = '';
      if (tagged < total) {
        status = '<span class="color-pending material-icons">pending</span>';
      } else {
        status = '<span class="color-done material-icons">check_circle</span>';
      }
      let html = ('<div class="d-flex justify-between align-center ml-10"><h4 id="mapped-stats-title" part="results-title" class="d-flex align-center m-0">' + status + '&nbsp;&nbsp;Mapped ' + tagged + ' out of ' + total + '</h4></div>');

      (container.querySelector('#mapping-count-container') as HTMLDivElement).innerHTML = html
    }
  }

  renderOnboardingCompliances = async (mappedStatutes: any, mappedCompliancesArr: any) => {

    //console.log('mappedcompliances', mappedCompliances);
    //console.log('mappedstatutes', mappedStatutes);

    var searchString = "";
    let mappedCompliances: any = { data: { mappings: { mappings: [] } } };
    for (var i = 0; i < (mappedStatutes.data.mappings.mappings as Array<any>).length; i++) {
      if ((mappedStatutes.data.mappings.mappings as Array<any>)[i].selected) {
        let statuteid = (mappedStatutes.data.mappings.mappings as Array<any>)[i].id
        if (mappedCompliancesArr.data.mappings[statuteid] != null) {
          for (let complianceid of Object.keys(mappedCompliancesArr.data.mappings[statuteid])) {
            let pushObj = mappedCompliancesArr.data.mappings[statuteid][complianceid];
            pushObj.id = complianceid;
            mappedCompliances.data.mappings.mappings.push(pushObj);
          }
        }
        searchString += statuteid + "|";
      }
    }
    searchString = searchString.slice(0, -1);

    //console.log('searchstring', searchString);

    var initCursor = "";

    // var html = '';

    // html += '<div class="d-flex flex-col w-100" style="height: 75vh">';
    // html += '<div class="d-flex flex-col w-100">';
    // html += '<label part="input-label">Search Compliances</label>';
    // html += '<div class="d-flex">';
    // html += '<input part="input" type="text" class="w-100 input-search" placeholder="Use | to separate..." disabled/>'
    // html += '<button part="button-icon" class="ml-10 material-icons button-search">search</button>'
    // html += '</div>';
    // html += '</div>';

    // html += '<div id="compliances-list-container" class="d-flex flex-col w-100 scroll-x">';
    // html += '</div>';
    // html += '</div>';

    // (this._SfOnboardingCompliancesContainer as HTMLDivElement).innerHTML = html;

    // (this._SfButtonSearch as HTMLButtonElement)?.addEventListener('click', async () => {
    //   //console.log('clicked', mappedStatutes.data.mappings.mappings);
    //   const searchString = (this._SfInputSearch as HTMLButtonElement).value;
    //   //console.log('searchstring', searchString);
    //   if (searchString.length > 0) {

    //     const arrSearchString = searchString.split('|');

    //     const arrSearchStringProcessed: any = [];

    //     arrSearchString.forEach((complianceId: string) => {

    //       if (complianceId.length === 36) {
    //         arrSearchStringProcessed.push(complianceId);
    //       }

    //     });

    //     var resultCompliances: any = {};
    //     resultCompliances.values = [];
    //     const chunkSize = 20;
    //     for (let k = 0; k < arrSearchStringProcessed.length; k += chunkSize) {

    //       const chunk = arrSearchStringProcessed.slice(k, k + chunkSize);
    //       console.log('chunk', chunk);
    //       // do whatever
    //       const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchStringProcessed.length);
    //       console.log(tempResultCompliances)
    //       resultCompliances.values.push(...tempResultCompliances.values);
    //       //console.log(resultCompliances);

    //     }

    //     // var resultCompliances : any = {};
    //     // resultCompliances.values = [];
    //     // const chunkSize = 20;
    //     // for (let k = 0; k < arrSearchString.length; k += chunkSize) {

    //     //   const chunk = arrSearchString.slice(k, k + chunkSize);
    //     //   console.log('chunk', chunk);
    //     //     // do whatever
    //     //   const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchString.length);
    //     //   console.log(tempResultCompliances)
    //     //   resultCompliances.values.push(...tempResultCompliances.values);
    //     //   //console.log(resultCompliances);

    //     // }

    //     if (resultCompliances != null) {

    //       const jsonData = [];

    //       const arrCompliancesFrequencies: any = {};

    //       for (var i = 0; i < resultCompliances.values.length; i++) {

    //         if (arrCompliancesFrequencies[resultCompliances.values[i].id] != null) {
    //           continue;
    //         } else {
    //           arrCompliancesFrequencies[resultCompliances.values[i].id] = 0;
    //         }

    //         var mapped = false;
    //         var extraFields = null;
    //         var previousExtraFields = null;
    //         console.log('mappedcompliances', mappedCompliances)
    //         for (var j = 0; j < mappedCompliances.data.mappings.mappings.length; j++) {
    //           if (mappedCompliances.data.mappings.mappings[j].id == resultCompliances.values[i].id) {
    //             if (mappedCompliances.data.mappings.mappings[j].selected) {
    //               mapped = true;
    //             }
    //             extraFields = mappedCompliances.data.mappings.mappings[j].extraFields;
    //           }
    //         }

    //         for (j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) {

    //           // console.log('mappedStatutes.data.mappings.mappings[j]', mappedStatutes.data.mappings.mappings[j]);
    //           if (Array.isArray(mappedStatutes.data.mappings.mappings[j].statutename)) {
    //             // sometimes this error occurs
    //             continue;

    //           }

    //           if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == JSON.parse(resultCompliances.values[i].fields.data[0])[6][0].trim()) {

    //             // if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == "Corporation Act, 2001") {
    //             //   console.log('pushpreviousvalues', mappedStatutes.data.mappings.mappings[j], Object.keys(mappedStatutes.data.mappings.mappings[j].extraFields[0]));
    //             // }
    //             previousExtraFields = mappedStatutes.data.mappings.mappings[j].extraFields
    //           }
    //         }
    //         jsonData.push({ id: resultCompliances.values[i].id, mapped: mapped, data: resultCompliances.values[i].fields, cols: ["country", "jurisdiction", "state", "category", "subcategory", "statute", "applicability", "obligationtitle", "obligation", "risk", "riskarea", "frequency", "penalty", "reference", "form", "subfrequency", "obligationtype", "duedate"], extraFields: extraFields, previousExtraFields: previousExtraFields })
    //       }


    //       this.renderMappingTable((this._SfOnboardingCompliancesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultCompliances.cursor }], this.fetchSearchCompliances, searchString, mappedCompliances, resultCompliances.values.length, this.uploadCompliancesMapping, this.loadOnboardingCompliances, ["Client remarks", "FlaggGRC response"], -1, 0, "compliances", "", "statute", ["optional", "optional"]);

    //     }

    //   }

    // });

    //console.log('compliances searchstring', searchString);

    // if (searchString != "") {
    //   (this._SfInputSearch as HTMLInputElement).value = searchString;
    //   (this._SfButtonSearch as HTMLButtonElement).click();
    // }

    if (searchString.length > 0) {

      const arrSearchString = searchString.split('|');

      const arrSearchStringProcessed: any = [];

      arrSearchString.forEach((complianceId: string) => {

        if (complianceId.length === 36) {
          arrSearchStringProcessed.push(complianceId);
        }

      });

      var resultCompliances: any = {};
      resultCompliances.values = [];
      const chunkSize = 20;
      for (let k = 0; k < arrSearchStringProcessed.length; k += chunkSize) {

        const chunk = arrSearchStringProcessed.slice(k, k + chunkSize);
        console.log('chunk', chunk);
        // do whatever
        const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchStringProcessed.length);
        console.log(tempResultCompliances)
        resultCompliances.values.push(...tempResultCompliances.values);
        //console.log(resultCompliances);

      }

      // var resultCompliances : any = {};
      // resultCompliances.values = [];
      // const chunkSize = 20;
      // for (let k = 0; k < arrSearchString.length; k += chunkSize) {

      //   const chunk = arrSearchString.slice(k, k + chunkSize);
      //   console.log('chunk', chunk);
      //     // do whatever
      //   const tempResultCompliances = await this.fetchSearchCompliances(chunk.join('|'), "", k, arrSearchString.length);
      //   console.log(tempResultCompliances)
      //   resultCompliances.values.push(...tempResultCompliances.values);
      //   //console.log(resultCompliances);

      // }

      if (resultCompliances != null) {

        const jsonData = [];

        const arrCompliancesFrequencies: any = {};

        for (var i = 0; i < resultCompliances.values.length; i++) {

          if (arrCompliancesFrequencies[resultCompliances.values[i].id] != null) {
            continue;
          } else {
            arrCompliancesFrequencies[resultCompliances.values[i].id] = 0;
          }

          var mapped = false;
          var extraFields = null;
          var previousExtraFields = null;
          console.log('mappedcompliances', mappedCompliances)
          if (mappedCompliances.data.mappings.mappings == null) {
            for (var j = 0; j < Object.keys(mappedCompliances.data.mappings).length; j++) {
              let statuteKey = Object.keys(mappedCompliances.data.mappings)[j];
              for (var k = 0; k < Object.keys(mappedCompliances.data.mappings[statuteKey]).length; k++) {
                let complianceKey = Object.keys(mappedCompliances.data.mappings[statuteKey])[k];
                if (mappedCompliances.data.mappings[statuteKey][complianceKey].id == resultCompliances.values[i].id) {
                  mapped = true;
                  extraFields = mappedCompliances.data.mappings[statuteKey][complianceKey].extraFields;
                }
              }
            }
          } else {
            for (var j = 0; j < mappedCompliances.data.mappings.mappings.length; j++) {
              if (mappedCompliances.data.mappings.mappings[j].id == resultCompliances.values[i].id) {
                mapped = true;
                extraFields = mappedCompliances.data.mappings.mappings[j].extraFields;
              }
            }


            for (j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) {

              // console.log('mappedStatutes.data.mappings.mappings[j]', mappedStatutes.data.mappings.mappings[j]);
              if (Array.isArray(mappedStatutes.data.mappings.mappings[j].statutename)) {
                // sometimes this error occurs
                continue;

              }

              if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == JSON.parse(resultCompliances.values[i].fields.data[0])[6][0].trim()) {

                // if (mappedStatutes.data.mappings.mappings[j].statutename.trim() == "Corporation Act, 2001") {
                //   //console.log('pushpreviousvalues', mappedStatutes.data.mappings.mappings[j], Object.keys(mappedStatutes.data.mappings.mappings[j].extraFields[0]));
                // }
                previousExtraFields = mappedStatutes.data.mappings.mappings[j].extraFields
              }
            }
          }
          jsonData.push({ id: resultCompliances.values[i].id, mapped: mapped, data: resultCompliances.values[i].fields, cols: ["country", "jurisdiction", "state", "category", "subcategory", "statute", "applicability", "obligationtitle", "obligation", "risk", "riskarea", "frequency", "penalty", "reference", "form", "subfrequency", "obligationtype", "duedate"], extraFields: extraFields, previousExtraFields: previousExtraFields })
        }


        this.renderMappingTable((this._SfOnboardingCompliancesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultCompliances.cursor }], this.fetchSearchCompliances, searchString, mappedCompliances, resultCompliances.values.length, this.uploadCompliancesMapping, this.loadOnboardingCompliances, [], -1, 0, "compliances", "", "statute", ["optional", "optional"], mappedStatutes.data.mappings.mappings);

      }

    }

  }

  renderOnboardingEntities = (selectedStatutes: any, mappedCompliances: any, mappedCountries: any, mappedEntities: any) => {

    this.renderTaggingTableNew((this._SfOnboardingEntitiesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, mappedCountries, mappedEntities, ["shortid", "applicability", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute"], this.uploadEntitiesMapping, this.loadOnboardingEntities, "entities", ["id", "countryname"], this.apiIdTags, "&Entity", ["entityname", "entityid"], ["id", "countryid"], null, [], [], "Guideline", "");

  }

  renderOnboardingCountries = (selectedStatutes: any, mappedCompliances: any, sourceMapping: any, mappedCountries: any) => {
    sourceMapping = {}
    this.renderTaggingTableNew((this._SfOnboardingCountriesListContainer as HTMLDivElement), selectedStatutes, mappedCompliances, sourceMapping, mappedCountries, ["shortid", "firstlineofdefence", "obligationtitle", "obligationtype", "country", "statute", "state", "subcategory"], this.uploadCountriesMapping, this.loadOnboardingCountries, "countries", ["id"], this.apiIdTags, "-Country", ["countryname", "countryid"], ["id"], null, [], null, "", "");
  }

  renderOnboardingStatutes = (mappedStatutes: any) => {

    var initCursor = "";

    var html = '';

    html += '<div class="d-flex flex-col w-100" style="height: 75vh">';
    html += '<div class="d-flex flex-col w-100">';
    html += '<label part="input-label">Search Statutes</label>';
    html += '<div class="d-flex">';
    html += '<input part="input" type="text" class="w-100 input-search" placeholder="Use | to separate..." autofocus/>'
    html += '<button part="button-icon" class="ml-10 material-icons button-search">search</button>'
    html += '</div>';
    html += '</div>';

    html += '<div id="statutes-list-container" class="d-flex flex-col w-100 scroll-x">';
    html += '</div>';

    html += '<div>';

    (this._SfOnboardingStatutesContainer as HTMLDivElement).innerHTML = html;

    (this._SfInputSearch as HTMLInputElement).addEventListener('keyup', (e: any) => {
      if (e.key == 'Enter') {
        (this._SfButtonSearch as HTMLButtonElement).click();
      }
    });

    (this._SfButtonSearch as HTMLButtonElement).addEventListener('click', async () => {
      //console.log('clicked', mappedStatutes.data.mappings.mappings);
      const searchString = (this._SfInputSearch as HTMLButtonElement).value;
      //console.log('clicked', searchString);
      if (searchString.length > 0) {
        const resultStatutes = await this.fetchSearchStatutes(searchString, "");
        if (resultStatutes != null) {
          const jsonData = [];
          let countMapped = 0
          for (var i = 0; i < resultStatutes.values.length; i++) {
            var mapped = false;
            var extraFields = null;
            if (mappedStatutes.data != null && mappedStatutes.data.mappings != null && mappedStatutes.data.mappings.mappings != null) {
              for (var j = 0; j < mappedStatutes.data.mappings.mappings.length; j++) {
                if (mappedStatutes.data.mappings.mappings[j].id == resultStatutes.values[i].id) {
                  countMapped++
                  console.log('comparing', mappedStatutes.data.mappings.mappings[j].id, resultStatutes.values[i].id, countMapped);
                  // if (mappedStatutes.data.mappings.mappings[j].selected) {
                  mapped = true;
                  // }
                  extraFields = mappedStatutes.data.mappings.mappings[j].extraFields;
                }
              }
            }

            jsonData.push({ id: resultStatutes.values[i].id, mapped: mapped, data: resultStatutes.values[i].fields, cols: ["country", "jurisdiction", "state", "name", "category", "subcategory", "applicability"], extraFields: extraFields })
          }
          console.log('clicked', jsonData);
          // let diffArr = []
          // for(let mappedObj of mappedStatutes.data.mappings.mappings){
          //   let flagFound = false
          //   for(let jsonObj of jsonData){
          //     if(jsonObj.id == mappedObj.id){
          //       flagFound = true;
          //       break;
          //     }
          //   }
          //   if(!flagFound){
          //     diffArr.push(mappedObj)
          //   }
          // }
          // console.log('compareDiff', diffArr)
          this.renderMappingTable((this._SfOnboardingStatutesListContainer as HTMLDivElement), jsonData, [{ prev: initCursor, next: resultStatutes.cursor }], this.fetchSearchStatutes, searchString, mappedStatutes, jsonData.length, this.uploadStatutesMapping, this.loadOnboardingStatutes, ["Client remarks<br ><span class=\"title-byline\">(mention your queries, else leave blank)<span>", "Entity applicability<br /><span class=\"title-byline\">(only applicable in case of multiple corporate entities, else leave blank)<span>", "Locations applicability<br /><span class=\"title-byline\">(mention in case there is location-wise variance of applicability, else leave blank)<span>", "Reporters<br /><span class=\"title-byline\">(details of personnel who have the reponsibility of reporting)<span>", "Approvers<br /><span class=\"title-byline\">(details of personnel who have the reponsibility of approving)", "Functionheads<br /><span class=\"title-byline\">(details of personnel who head the function)", "Auditors<br /><span class=\"title-byline\">(mention details of auditors in case they are known)</span>", "Viewers<br /><span class=\"title-byline\">(mention details personnel who need to be given readonly access)</span>", "FlaggGRC response"], -1, 1, "statutes", "", "name", ["optional", "optional", "optional", "name - email@company.com", "name - email@company.com", "optional", "optional", "optional", "optional"])

        }
      }
    });

    if (mappedStatutes.data.mappings.searchstring != "" && mappedStatutes.data.mappings.searchstring != null) {
      (this._SfInputSearch as HTMLInputElement).value = mappedStatutes.data.mappings.searchstring;
      (this._SfButtonSearch as HTMLButtonElement).click();
    }

  }

  clickOnboardingTabs = () => {

    if (this.myOnboardingTab == this.TAB_STATUTES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-statutes') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_COMPLIANCES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-compliances') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_COUNTRIES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-countries') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_ENTITIES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-entities') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_LOCATIONS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-locations') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_FUNCTIONS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-functions') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_TAGS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-tags') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_REPORTERS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-reporters') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_APPROVERS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-approvers') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_FUNCTION_HEADS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-functionheads') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_AUDITORS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-auditors') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_VIEWERS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-viewers') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_DOCS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-docs') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_MAKER_CHECKERS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-makercheckers') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_DUEDATES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-duedates') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_EXTENSIONS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#extensions-tab-duedates') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_ALERTSCHEDULES) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-alertschedules') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_ACTIVATIONS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-activations') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_INVALIDATION) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-invalidations') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_INTERNALCONTROLS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-internalcontrols') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_REPORTEDLOCATIONS) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-reportedlocations') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_CALENDAR) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-calendar') as HTMLButtonElement).click();
    }
    if (this.myOnboardingTab == this.TAB_SUSPENSE) {
      ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-suspense') as HTMLButtonElement).click();
    }

  }

  renderOnboardingStatus = (status: any) => {

    for (var i = 0; i < status.length; i++) {

      const arrStatus = status[i].split(';');
      if (arrStatus[0].toLowerCase().indexOf('statutes') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-statutes')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('compliances') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-compliances')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('countries') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-countries')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('entities') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-entities')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('locations') >= 0 && arrStatus[0].toLowerCase().indexOf('reportedlocations') < 0 && arrStatus[0].toLowerCase().indexOf('govlocations') < 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-locations')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('functions') >= 0
      ) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-functions')!.innerHTML = arrStatus[1];
      }

      if (arrStatus[0].toLowerCase().indexOf('tags') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-tags')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('reporters') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-reporters')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('approvers') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-approvers')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('functionheads') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-functionheads')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('auditors') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-auditors')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('viewers') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-viewers')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('docs') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-docs')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('makercheckers') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-makercheckers')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('duedates') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-duedates')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('extensions') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-extensions')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('alertschedules') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-alertschedules')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('activations') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-activations')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('invalidations') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-invalidations')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('triggers') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-triggers')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('internalcontrols') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-internalcontrols')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('reportedlocations') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-reportedlocations')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('govlocations') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-govlocations')!.innerHTML = arrStatus[1];
      }
      if (arrStatus[0].toLowerCase().indexOf('govusers') >= 0) {
        (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#button-status-govusers')!.innerHTML = arrStatus[1];
      }

    }

  }

  renderClearOnboardingContent = () => {

    (this._SfOnboardingCountriesContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingEntitiesContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingLocationsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingFunctionsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingTagsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingReportersContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingApproversContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingFunctionHeadsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingAuditorsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingViewersContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingDocsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingMakerCheckersContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingDuedatesContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingAlertSchedulesContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingInternalControlsContainer as HTMLDivElement)!.innerHTML = '';
    (this._SfOnboardingReportedLocationsContainer as HTMLDivElement)!.innerHTML = '';

  }

  renderOnboardingTabs = async () => {

    //console.log('render onboarding tabs', this.myOnboardingTabGroup);
    let initialLoad = false;

    if (this.myOnboardingTabGroup == "") {
      this.myOnboardingTabGroup = this.TAB_GROUP_BUSINESS_UNDERSTANDING
      initialLoad = true;
    }

    //console.log('render onboarding tabs', this.myOnboardingTabGroup);

    this.selectedCbs = [];

    (this._SfOnboardingTabContainer as HTMLDivElement).innerHTML = '';

    var html = '';

    html += '<div class="d-flex w-100 justify-center">';
    html += '<button id="onboarding-tab-group-button-0" class="tab-button mb-10" part="' + (this.myOnboardingTabGroup == this.TAB_GROUP_BUSINESS_UNDERSTANDING ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Business Insights</button>';
    html += '<button id="onboarding-tab-group-button-1" class="tab-button mb-10" part="' + (this.myOnboardingTabGroup == this.TAB_GROUP_GOVERNANCE_MAPPING ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">GRC Integration</button>';
    html += '<button id="onboarding-tab-group-button-2" class="tab-button mb-10" part="' + (this.myOnboardingTabGroup == this.TAB_GROUP_CUSTOMIZATION ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Customization</button>';
    html += '<button id="onboarding-tab-group-button-3" class="tab-button mb-10" part="' + (this.myOnboardingTabGroup == this.TAB_GROUP_ROLLOUT ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Rollout</button>';
    html += '<button id="onboarding-tab-group-button-4" class="tab-button mb-10" part="' + (this.myOnboardingTabGroup == this.TAB_GROUP_GOVERNANCE ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Governance</button>';
    html += '</div>';

    html += '<div id="onboarding-tab-group-0" class="' + (this.myOnboardingTabGroup == this.TAB_GROUP_BUSINESS_UNDERSTANDING ? '' : 'hide') + ' d-flex justify-center sub-button align-center">';
    html += '<button class="tab-button mb-10" id="onboarding-tab-statutes" part="' + (this.myOnboardingTab == this.TAB_STATUTES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Statutes<br /><span id="button-status-statutes" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<div part="onboarding-tab-arrow" class="mb-10"><span class="material-symbols-outlined">arrow_right</span></div>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-compliances" part="' + (this.myOnboardingTab == this.TAB_COMPLIANCES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Compliances<br /><span id="button-status-compliances" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<div part="onboarding-tab-arrow" class="mb-10"><span class="material-symbols-outlined">arrow_right</span></div>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-countries" part="' + (this.myOnboardingTab == this.TAB_COUNTRIES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Countries<br /><span id="button-status-countries" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<div part="onboarding-tab-arrow" class="mb-10"><span class="material-symbols-outlined">arrow_right</span></div>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-entities" part="' + (this.myOnboardingTab == this.TAB_ENTITIES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Entities<br /><span id="button-status-entities" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<div part="onboarding-tab-arrow" class="mb-10"><span class="material-symbols-outlined">arrow_right</span></div>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-locations" part="' + (this.myOnboardingTab == this.TAB_LOCATIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Locations<br /><span id="button-status-locations" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '</div>';

    html += '<div id="onboarding-tab-group-1" class="' + (this.myOnboardingTabGroup == this.TAB_GROUP_GOVERNANCE_MAPPING ? '' : 'hide') + ' d-flex justify-center flex-wrap sub-button">';
    html += '<button class="tab-button mb-10" id="onboarding-tab-functions" part="' + (this.myOnboardingTab == this.TAB_FUNCTIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Functions<br /><span id="button-status-functions" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-tags" part="' + (this.myOnboardingTab == this.TAB_TAGS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Tags<br /><span id="button-status-tags" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-reporters" part="' + (this.myOnboardingTab == this.TAB_REPORTERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Reporters<br /><span id="button-status-reporters" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-approvers" part="' + (this.myOnboardingTab == this.TAB_APPROVERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Approvers<br /><span id="button-status-approvers" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-functionheads" part="' + (this.myOnboardingTab == this.TAB_FUNCTION_HEADS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Function Heads<br /><span id="button-status-functionheads" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-auditors" part="' + (this.myOnboardingTab == this.TAB_AUDITORS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Auditors<br /><span id="button-status-auditors" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-viewers" part="' + (this.myOnboardingTab == this.TAB_VIEWERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Viewers<br /><span id="button-status-viewers" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '</div>';

    html += '<div id="onboarding-tab-group-2" class="' + (this.myOnboardingTabGroup == this.TAB_GROUP_CUSTOMIZATION ? '' : 'hide') + ' d-flex justify-center flex-wrap sub-button">';
    html += '<button class="tab-button mb-10" id="onboarding-tab-docs" part="' + (this.myOnboardingTab == this.TAB_DOCS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Docs<br /><span id="button-status-docs" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-makercheckers" part="' + (this.myOnboardingTab == this.TAB_MAKER_CHECKERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Maker Checkers<br /><span id="button-status-makercheckers" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-duedates" part="' + (this.myOnboardingTab == this.TAB_DUEDATES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Duedates<br /><span id="button-status-duedates" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-extensions" part="' + (this.myOnboardingTab == this.TAB_EXTENSIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Extensions<br /><span id="button-status-extensions" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-alertschedules" part="' + (this.myOnboardingTab == this.TAB_ALERTSCHEDULES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Alert Schedules<br /><span id="button-status-alertschedules" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-activations" part="' + (this.myOnboardingTab == this.TAB_ACTIVATIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Activations<br /><span id="button-status-activations" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-invalidations" part="' + (this.myOnboardingTab == this.TAB_INVALIDATION ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Invalidations<br /><span id="button-status-invalidations" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-triggers" part="' + (this.myOnboardingTab == this.TAB_TRIGGERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Triggers<br /><span id="button-status-triggers" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-internalcontrols" part="' + (this.myOnboardingTab == this.TAB_INTERNALCONTROLS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Internal Controls<br /><span id="button-status-internalcontrols" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-reportedlocations" part="' + (this.myOnboardingTab == this.TAB_REPORTEDLOCATIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Reported Locations<br /><span id="button-status-reportedlocations" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '</div>';

    html += '<div id="onboarding-tab-group-3" class="' + (this.myOnboardingTabGroup == this.TAB_GROUP_ROLLOUT ? '' : 'hide') + ' d-flex justify-center flex-wrap sub-button">';
    html += '<button class="tab-button mb-10" id="onboarding-tab-signoff" part="' + (this.myOnboardingTab == this.TAB_SIGNOFF ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Sign Off<br /><span id="button-status-signoff" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-calendar" part="' + (this.myOnboardingTab == this.TAB_CALENDAR ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Calendar<br /><span id="button-status-calendar" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-suspense" part="' + (this.myOnboardingTab == this.TAB_SUSPENSE ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Suspense<br /><span id="button-status-suspense" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '</div>';

    html += '<div id="onboarding-tab-group-4" class="' + (this.myOnboardingTabGroup == this.TAB_GROUP_GOVERNANCE ? '' : 'hide') + ' d-flex justify-center flex-wrap sub-button">';
    html += '<button class="tab-button mb-10" id="onboarding-tab-govlocations" part="' + (this.myOnboardingTab == this.TAB_GOV_LOCATIONS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Gov Locations<br /><span id="button-status-govlocations" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '<button class="tab-button mb-10" id="onboarding-tab-govusers" part="' + (this.myOnboardingTab == this.TAB_GOV_USERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Gov Users<br /><span id="button-status-govusers" class="d-flex button-status align-center justify-center" part="button-status">...</span></button>';
    html += '</div>';

    (this._SfOnboardingTabContainer as HTMLDivElement).innerHTML = html;

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-statutes')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_STATUTES;
      await this.renderOnboardingTabs();
      await this.loadOnboardingStatutes();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-compliances')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_COMPLIANCES;
      await this.renderOnboardingTabs();
      this.loadOnboardingCompliances();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-countries')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_COUNTRIES;
      await this.renderOnboardingTabs();
      this.loadOnboardingCountries();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-entities')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_ENTITIES;
      await this.renderOnboardingTabs();
      this.loadOnboardingEntities();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-locations')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_LOCATIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingLocations();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-functions')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_FUNCTIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingFunctions();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-tags')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_TAGS;
      await this.renderOnboardingTabs();
      this.loadOnboardingTags();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-reporters')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_REPORTERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingReporters();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-approvers')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_APPROVERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingApprovers();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-functionheads')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_FUNCTION_HEADS;
      await this.renderOnboardingTabs();
      this.loadOnboardingFunctionHeads();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-auditors')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_AUDITORS;
      await this.renderOnboardingTabs();
      this.loadOnboardingAuditors();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-viewers')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_VIEWERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingViewers();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-makercheckers')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_MAKER_CHECKERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingMakerCheckers();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-docs')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_DOCS;
      await this.renderOnboardingTabs();
      this.loadOnboardingDocs();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-duedates')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_DUEDATES;
      await this.renderOnboardingTabs();
      this.loadOnboardingDuedates();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-alertschedules')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_ALERTSCHEDULES;
      await this.renderOnboardingTabs();
      this.loadOnboardingAlertSchedules();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-activations')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_ACTIVATIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingActivations();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-invalidations')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_INVALIDATION;
      await this.renderOnboardingTabs();
      this.loadOnboardingInvalidations();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-triggers')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_TRIGGERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingTriggers();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-extensions')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_EXTENSIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingExtensions();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-internalcontrols')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_INTERNALCONTROLS;
      await this.renderOnboardingTabs();
      this.loadOnboardingInternalControls();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-reportedlocations')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_REPORTEDLOCATIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingReportedLocations();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-signoff')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_SIGNOFF;
      this.renderOnboardingTabs();
      this.loadOnboardingSignoff();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-calendar')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_CALENDAR;
      this.renderOnboardingTabs();
      this.loadOnboardingCalendar();

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-suspense')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_SUSPENSE;
      this.renderOnboardingTabs();
      this.loadOnboardingSuspense();
      console.log('Suspense tab clicked')

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-govlocations')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_GOV_LOCATIONS;
      await this.renderOnboardingTabs();
      this.loadOnboardingMappedGovLocations();
      console.log('Governance Locations tab clicked')

    });

    (this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-govusers')?.addEventListener('click', async () => {

      this.myOnboardingTab = this.TAB_GOV_USERS;
      await this.renderOnboardingTabs();
      this.loadOnboardingMappedGovUsers();
      console.log('Governance Users tab clicked')

    });

    (this._SfOnboardingTabGroupButton0 as HTMLDivElement).addEventListener('click', () => {

      this.myOnboardingTabGroup = this.TAB_GROUP_BUSINESS_UNDERSTANDING;
      this.hideTabContainers();
      this.myOnboardingTab = '';
      this.renderOnboardingTabs();

    });

    (this._SfOnboardingTabGroupButton1 as HTMLDivElement).addEventListener('click', () => {

      this.myOnboardingTabGroup = this.TAB_GROUP_GOVERNANCE_MAPPING;
      this.hideTabContainers();
      this.myOnboardingTab = '';
      this.renderOnboardingTabs();

    });

    (this._SfOnboardingTabGroupButton2 as HTMLDivElement).addEventListener('click', () => {

      this.myOnboardingTabGroup = this.TAB_GROUP_CUSTOMIZATION;
      this.hideTabContainers();
      this.myOnboardingTab = '';
      this.renderOnboardingTabs();

    });

    (this._SfOnboardingTabGroupButton3 as HTMLDivElement).addEventListener('click', () => {

      this.myOnboardingTabGroup = this.TAB_GROUP_ROLLOUT;
      this.hideTabContainers();
      this.myOnboardingTab = '';
      this.renderOnboardingTabs();

    });

    (this._SfOnboardingTabGroupButton4 as HTMLDivElement).addEventListener('click', () => {

      this.myOnboardingTabGroup = this.TAB_GROUP_GOVERNANCE;
      this.hideTabContainers();
      this.myOnboardingTab = '';
      this.renderOnboardingTabs();

    });

    const statusOnboarding = await this.fetchOnboardingStatus();
    this.renderOnboardingStatus(statusOnboarding.result)
    this.renderClearOnboardingContent();

    if (initialLoad) {
      //   ((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-statutes') as HTMLButtonElement).click();
    }

  }

  renderRcmProceed = (div: HTMLDivElement, button: HTMLButtonElement | null) => {

    var html = '';

    html += '<div class="mb-20 mt-20">';
    html += '<button id="button-proceed" part="button">Proceed</button>';
    html += '</div>';

    div.innerHTML += html;

    div.querySelector('#button-proceed')?.addEventListener('click', () => {
      button?.click();
    });

  }

  renderRcmSelectedComplianceInProject = (div: HTMLDivElement) => {

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mb-10">Selected Compliance</div>';

    if (this.rcmSelectedCompliance == null || this.rcmSelectedCompliance.values == null || this.rcmSelectedCompliance.values.length === 0) {
      html += '<p part="rcm-section-error-message" class="mt-20 mb-10">No compliances found</p></div>';
      div.innerHTML += html;
      return;
    }

    html += '<table>';

    html += '<thead>';
    html += '<th part="td-head" class="td-head">'
    html += 'Id';
    html += '</th>'
    for (var i = 0; i < Object.keys(this.rcmSelectedCompliance.values).length; i++) {
      if (this.arrCols.includes(Object.keys(this.rcmSelectedCompliance.values)[i])) {
        html += '<th part="td-head" class="td-head">'
        html += Object.keys(this.rcmSelectedCompliance.values)[i]
        html += '</th>'
      }
    }
    html += '</thead>';

    html += '<tbody>';

    var classBg = "";
    classBg = 'td-light';

    html += '<tr>';
    html += '<td part="td-body" class="' + classBg + '">';
    html += '<sf-i-elastic-text exportparts="highlight,highlight-count" class="statute id-' + i + '" text="' + (this.rcmSelectedCompliance.id) + '" minLength="80"></sf-i-elastic-text>';
    html += '</td>';
    //let data = JSON.parse(jsonData[i].fields.data);
    for (var j = 0; j < Object.keys(this.rcmSelectedCompliance.values).length; j++) {

      const objectKey = Object.keys(this.rcmSelectedCompliance.values)[j];
      if (this.arrCols.includes(objectKey)) {
        html += '<td part="td-body" class="td-body ' + classBg + '">';
        if (Array.isArray(this.rcmSelectedCompliance.values[objectKey].value)) {

          for (var k = 0; k < this.rcmSelectedCompliance.values[objectKey].value.length; k++) {
            if (this.rcmSelectedCompliance.values[objectKey].text != null) {
              html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.rcmSelectedCompliance.values[objectKey].text[k] + '" minLength="80"></sf-i-elastic-text>');
            } else {
              html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.rcmSelectedCompliance.values[objectKey].value[k] + '" minLength="80"></sf-i-elastic-text>');
            }

            if (k < (this.rcmSelectedCompliance.values[objectKey].value.length - 1)) {
              html += "; ";
            }
          }

        } else {
          if (this.rcmSelectedCompliance.values[objectKey].text != null) {
            html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.rcmSelectedCompliance.values[objectKey].value + '" minLength="80"></sf-i-elastic-text>')
          } else {
            html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + this.rcmSelectedCompliance.values[objectKey].value + '" minLength="80"></sf-i-elastic-text>')
          }
        }
        html += '</td>';
      }

    }
    html += '</tr>';
    html += '</tbody>'
    html += '</table>';
    html += '</div>';

    div.innerHTML += html;

  }

  renderRcmCompliances = (updatedCompliances: any) => {

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mb-10">Recently Updated Compliances</div>';

    html += '<div part="rcm-setting" class="d-flex mt-20 mb-20 align-center"><div class="mr-10">Show Completed</div><input id="cb-completed" type="checkbox" /></div>';

    html += '<table>';

    html += '<thead>';
    html += '<th part="td-head" class="td-head left-sticky">'
    html += 'Select';
    html += '</th>'
    html += '<th part="td-head" class="td-head left-sticky">'
    html += 'Complete';
    html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += 'Id';
    html += '</th>'
    for (var i = 0; i < Object.keys(updatedCompliances[0].values).length; i++) {
      if (this.arrCols.includes(Object.keys(updatedCompliances[0].values)[i])) {
        html += '<th part="td-head" class="td-head">'
        html += Object.keys(updatedCompliances[0].values)[i]
        html += '</th>'
      }
    }
    html += '</thead>'

    html += '<tbody>'
    for (var i = 0; i < updatedCompliances.length; i++) {

      var classBg = "";

      if (i % 2 === 0) {
        classBg = 'td-light';
      } else {
        classBg = 'td-dark';
      }

      html += '<tr id="row-' + (updatedCompliances[i].id) + '">';
      html += '<td part="td-body" class="' + classBg + ' left-sticky">';
      html += '<div id="select-' + i + '"><button id="button-' + (updatedCompliances[i].id) + '" class="buttonselect-icon button-' + i + '" part="button-icon-small"><span class="material-symbols-outlined">navigate_next</span></button></div>';
      html += '</td>';
      html += '<td part="td-body" class="' + classBg + '">';
      html += '<div class="d-flex"><button id="button-lock-' + (updatedCompliances[i].id) + '" class="mr-10 button-lock-icon button-lock-' + i + '" part="button-icon-small"><span class="material-symbols-outlined">done</span></button></div>';
      html += '</td>';
      html += '<td part="td-body" class="' + classBg + '">';
      html += '<sf-i-elastic-text exportparts="highlight,highlight-count" class="statute id-' + i + '" text="' + (updatedCompliances[i].id) + '" minLength="80"></sf-i-elastic-text>';
      html += '</td>';
      //let data = JSON.parse(jsonData[i].fields.data);
      for (var j = 0; j < Object.keys(updatedCompliances[i].values).length; j++) {

        const objectKey = Object.keys(updatedCompliances[i].values)[j];
        if (this.arrCols.includes(objectKey)) {
          html += '<td part="td-body" class="td-body ' + classBg + '">';
          if (Array.isArray(updatedCompliances[i].values[objectKey].value)) {

            for (var k = 0; k < updatedCompliances[i].values[objectKey].value.length; k++) {
              if (updatedCompliances[i].values[objectKey].text != null) {
                html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + updatedCompliances[i].values[objectKey].text[k] + '" minLength="80"></sf-i-elastic-text>');
              } else {
                html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + updatedCompliances[i].values[objectKey].value[k] + '" minLength="80"></sf-i-elastic-text>');
              }

              if (k < (updatedCompliances[i].values[objectKey].value.length - 1)) {
                html += "; ";
              }
            }

          } else {
            if (updatedCompliances[i].values[objectKey].text != null) {
              html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + updatedCompliances[i].values[objectKey].value + '" minLength="80"></sf-i-elastic-text>')
            } else {
              html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + updatedCompliances[i].values[objectKey].value + '" minLength="80"></sf-i-elastic-text>')
            }
          }
          html += '</td>';
        }

      }
      html += '</tr>';
    }
    html += '</tbody>'
    html += '</table>';
    html += '</div>';

    (this._SfRcmComplianceContainer as HTMLDivElement).innerHTML = html;



  }

  renderRcmLockedCompliances = (lockedCompliances: any) => {

    //console.log('rendering locked', lockedCompliances);

    for (var i = 0; i < lockedCompliances.data.length; i++) {

      // //console.log(lockedCompliances.data[i].complianceid);
      // //console.log(((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement));
      // ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'none';
      ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#row-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'none';
      ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#button-lock-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).classList.add('gone');

    }

  }

  renderRcmUnlockedCompliances = (lockedCompliances: any) => {

    //console.log('rendering unlocked', lockedCompliances);

    for (var i = 0; i < lockedCompliances.data.length; i++) {

      //console.log('#row-' + lockedCompliances.data[i].complianceid.S);
      ((this._SfRcmComplianceContainer as HTMLDivElement).querySelector('#row-' + lockedCompliances.data[i].complianceid.S) as HTMLButtonElement).style.display = 'table-row';


    }

  }

  renderRcmProjects = (div: HTMLDivElement, projects: any) => {

    //console.log('projects', projects);

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mt-20 mb-10">Affected Projects</div>';

    if (projects == null || projects.length === 0) {
      html += '<p part="rcm-section-error-message" class="mt-20 mb-10">No projects found</p></div>';
      div.innerHTML += html;
      return;
    }

    // //console.log(updatedCompliances);
    html += '<table>';

    html += '<thead>';
    // html += '<th part="td-head" class="td-head left-sticky">'
    // html += 'Select';
    // html += '</th>'
    html += '<th part="td-head" class="td-head">';
    html += 'Id';
    html += '</th>';
    for (var i = 0; i < Object.keys(projects[0]).length; i++) {
      if (this.arrRcmProjectCols.includes(Object.keys(projects[0])[i])) {
        html += '<th part="td-head" class="td-head">'
        html += Object.keys(projects[0])[i]
        html += '</th>'
      }
    }
    html += '</thead>';

    html += '<tbody>';
    for (var i = 0; i < projects.length; i++) {

      var classBg = "";

      if (i % 2 === 0) {
        classBg = 'td-light';
      } else {
        classBg = 'td-dark';
      }

      html += '<tr>';
      //   html += '<td part="td-action" class="left-sticky">';
      //   html += '<div id="select-'+i+'"><button id="button-'+i+'" class="button-icon button-'+i+'"><span class="material-symbols-outlined">navigate_next</span></button></div>';
      //   html += '</td>';
      html += '<td part="td-body" class="' + classBg + '">';
      html += '<sf-i-elastic-text exportparts="highlight,highlight-count" class="statute id-' + i + '" text="' + (projects[i].id) + '" minLength="80"></sf-i-elastic-text>';
      html += '</td>';
      //   //let data = JSON.parse(jsonData[i].fields.data);
      for (var j = 0; j < Object.keys(projects[i]).length; j++) {

        const objectKey = Object.keys(projects[i])[j];

        if (this.arrRcmProjectCols.includes(objectKey)) {
          html += '<td part="td-body" class="td-body ' + classBg + '">';
          //console.log('value',projects[i][objectKey]);
          if (Array.isArray(projects[i][objectKey])) {

            for (var k = 0; k < projects[i][objectKey].value.length; k++) {
              html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + projects[i][objectKey][0] + '" minLength="80"></sf-i-elastic-text>');
            }

          } else {
            //console.log('not array');
            html += ('<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + projects[i][objectKey].replace(/"/g, '') + '" minLength="80"></sf-i-elastic-text>')
          }
          html += '</td>';
        }

      }
      html += '</tr>';
    }
    html += '</tbody>'
    html += '</table>';
    html += '</div>';

    div.innerHTML += html;

    // const arrButtons = (this._SfRcmComplianceContainer as HTMLDivElement).querySelectorAll('.button-icon') as NodeListOf<HTMLButtonElement>;
    // for(i = 0; i < arrButtons.length; i++) {

    //   arrButtons[i].addEventListener('click', (e: any) => {

    //     const index = e.currentTarget.id.split('-')[1];
    //     this.rcmSelectedCompliance = updatedCompliances[index];
    //     ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects') as HTMLButtonElement).click();

    //   })

    // }

  }

  renderRcmSelectedDate = (div: HTMLDivElement) => {

    var html = "";

    html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mt-20 mb-20">Trigger Information</div>';

    if (this.rcmSelectedDate == null || this.rcmSelectedMessage == null) {
      html += '<p part="rcm-section-error-message" class="mt-20 mb-10">No trigger information found</p></div>';
      div.innerHTML += html;
      return;
    }


    html += '<label part="input-label" class="mt-5">Date of Trigger</label><br />';
    html += '<p>' + this.rcmSelectedDate + '</p>'
    html += '<label part="input-label" class="mt-5">Notification Message</label><br />';
    html += '<p>' + this.rcmSelectedMessage + '</p>'

    html += '<div class="mt-20 mb-10"></div></div>';

    div.innerHTML += html;


  }

  renderRcmDate = (div: HTMLDivElement) => {

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mt-20 mb-20">Trigger Information</div>';
    html += '<label part="input-label" class="mt-5">Date of Trigger</label><br />';
    html += '<input id="rcm-date" part="input" type="date" /><br /><br />'
    html += '<label part="input-label" class="mt-5">Notification Message</label><br />';
    html += '<textarea id="rcm-message" class="w-100" part="input" ></textarea>'

    html += '<div class="mt-20 mb-10"></div></div>';

    div.innerHTML += html;


  }

  renderRcmJobs = (div: HTMLDivElement) => {

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mb-20">New RCM Update Job</div>';
    html += '<button id="button-submit"part="button-icon-small" class="material-icons button-expand mt-5">add_circle</button><br />';
    html += '</div>';

    div.innerHTML += html;

  }

  renderRcmSelectedJobs = (div: HTMLDivElement, jobs: any) => {

    var html = '<div class="w-100" part="rcm-section">';

    html += '<div part="rcm-section-title" class="mb-10">Previous Jobs For The Selected Compliance</div>';

    if (jobs.data.length === 0) {
      html += '<p part="rcm-section-error-message" class="mt-20 mb-10">No jobs found</p></div>';
      div.innerHTML += html;
      return;
    }

    html += '<table>';

    html += '<thead>';
    html += '<th part="td-head" class="td-head">'
    html += 'Id';
    html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += 'Creation Time';
    html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += 'Status';
    html += '</th>'
    html += '<th part="td-head" class="td-head">'
    html += '';
    html += '</th>'

    html += '</thead>';

    html += '<tbody>';

    for (var i = jobs.data.length - 1; i >= 0; i--) {

      var classBg = "";
      if (i % 2 === 0) {
        classBg = 'td-light';
      } else {
        classBg = 'td-dark';
      }

      html += '<tr>';
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jobs.data[i].id.S;
      html += '</td>'
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jobs.data[i].lastupdated.S;
      html += '</td>'
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jobs.data[i].status.S == "0" ? "created" : jobs.data[i].status.S == "1" ? "in-progress" : jobs.data[i].status.S == "2" ? "completed" : "notified";
      html += '</td>'
      html += '<td part="td-body" class="td-body ' + classBg + '">';
      html += jobs.data[i].status.S == "0" ? "<span class=\"color-not-started material-icons\">schedule</span>" : jobs.data[i].status.S == "1" ? "<span class=\"color-pending material-icons\">pending</span>" : jobs.data[i].status.S == "2" ? "<span class=\"color-done material-icons\">check_circle</span>" : "<span class=\"color-done material-icons\">notifications</span>";
      html += '</td>'
      html += '</tr>';

    }

    html += '</thead>';

    html += '</tbody>';
    html += '</table></div>';

    div.innerHTML += html;

  }

  renderRcmNotifications = (notifs: any) => {

    var html = '';

    //console.log('inside rcm notifications', notifs);

    if (notifs.data.length > 0) {

      if (this.flowRcmNotification === 0) {
        html += '<div class="d-flex align-center">';
        html += '<span part="rcm-section-title-icon" class="material-symbols-outlined mr-10">notifications</span>';
        html += '<div part="rcm-section-title" class="mr-10">Regulatory Alerts</div>';
        html += ('<div part="notif-icon-badge" class="mr-20" >' + notifs.data.length + '</div>');
        html += '<button id="button-expand" part="icon-button-small" class="material-symbols-outlined">keyboard_arrow_down</button>'
        html += '</div>';
      } else {
        html += '<div class="w-100" part="rcm-section-notification">';
        html += '<div class="d-flex align-center mb-20">';
        html += '<span part="rcm-section-title-icon" class="material-symbols-outlined mr-10">notifications</span>';
        html += '<div part="rcm-section-title">Regulatory Alerts</div>';
        html += '</div>';
        html += '<div id="rcm-container-list" class="mb-10">';
        for (var i = 0; i < notifs.data.length; i++) {
          html += '<div part="rcm-container-list-item">';
          html += notifs.data[i].message;
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';
      }

    } else {

    }

    (this._SfRcmContainer as HTMLDivElement).innerHTML = html;

    if (notifs.data.length > 0) {

      if (this.flowRcmNotification === 0) {
        ((this._SfRcmContainer as HTMLDivElement).querySelector('#button-expand') as HTMLButtonElement).addEventListener('click', () => {
          this.flowRcmNotification = 1;
          this.renderRcmNotifications(notifs);
        })
      }

    }

  }

  renderRcmTabs = () => {

    //console.log('render rcm tabs');

    (this._SfRcmTabContainer as HTMLDivElement).innerHTML = '';

    var html = '';

    html += '<button class="tab-button mb-10" id="rcm-tab-compliances" part="' + (this.myRcmTab == this.TAB_RCM_COMPLIANCES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Compliances</button>';
    html += '<button class="tab-button mb-10" id="rcm-tab-projects" part="' + (this.myRcmTab == this.TAB_RCM_PROJECTS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Projects</button>';
    html += '<button class="tab-button mb-10" id="rcm-tab-date" part="' + (this.myRcmTab == this.TAB_RCM_DATE ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Trigger</button>';
    html += '<button class="tab-button mb-10" id="rcm-tab-jobs" part="' + (this.myRcmTab == this.TAB_RCM_JOBS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Jobs</button>';


    (this._SfRcmTabContainer as HTMLDivElement).innerHTML = html;

    (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-compliances')?.addEventListener('click', async () => {

      this.myRcmTab = this.TAB_RCM_COMPLIANCES;
      this.renderRcmTabs();
      await this.loadRcmCompliances();

    });

    (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-projects')?.addEventListener('click', async () => {

      this.myRcmTab = this.TAB_RCM_PROJECTS;
      this.renderRcmTabs();
      await this.loadRcmProjects();
      //await this.loadOnboardingStatutes();

    });

    (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-date')?.addEventListener('click', async () => {

      this.myRcmTab = this.TAB_RCM_DATE;
      this.renderRcmTabs();
      await this.loadRcmDate();
      //await this.loadOnboardingStatutes();

    });

    (this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-jobs')?.addEventListener('click', async () => {

      this.myRcmTab = this.TAB_RCM_JOBS;
      this.renderRcmTabs();
      await this.loadRcmJobs();
      //await this.loadOnboardingStatutes();

    });

  }

  proceedToCalendar = async () => {
    this.renderRoleTabs();
    await this.fetchAndYearlyRenderUserCalendar_2();
    this.enableCalendar();
    if (this.events != null) {
      this.renderTabs(this.TAB_YEAR);
      this.renderCalendar();
    }
  }

  renderRoleTabs = () => {

    //console.log('render role tabs');

    (this._SfRoleTabContainer as HTMLDivElement).innerHTML = '';

    var html = '';

    html += '<button class="tab-button" id="consumer-tab-reporter" part="' + (this.myRole == this.TAB_REPORTER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Reporter</button>';
    html += '<button class="tab-button" id="consumer-tab-approver" part="' + (this.myRole == this.TAB_APPROVER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Approver</button>';
    html += '<button class="tab-button" id="consumer-tab-functionhead" part="' + (this.myRole == this.TAB_FUNCTION_HEAD ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Function Head</button>';
    html += '<button class="tab-button" id="consumer-tab-auditor" part="' + (this.myRole == this.TAB_AUDITOR ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Auditor</button>';
    html += '<button class="tab-button" id="consumer-tab-viewer" part="' + (this.myRole == this.TAB_VIEWER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Viewer</button>';

    (this._SfRoleTabContainer as HTMLDivElement).innerHTML = html;

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-reporter')?.addEventListener('click', async () => {

      this.myRole = this.TAB_REPORTER;
      this.renderRoleTabs();
      // this.proceedToCalendar();
      if (this.selectedFeatures.indexOf('contracts') >= 0) {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
      } else {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-approver')?.addEventListener('click', async () => {

      this.myRole = this.TAB_APPROVER;
      this.renderRoleTabs();
      // this.proceedToCalendar();
      if (this.selectedFeatures.indexOf('contracts') >= 0) {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
      } else {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-functionhead')?.addEventListener('click', async () => {

      this.myRole = this.TAB_FUNCTION_HEAD;
      this.renderRoleTabs();
      // this.proceedToCalendar();
      if (this.selectedFeatures.indexOf('contracts') >= 0) {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
      } else {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-auditor')?.addEventListener('click', async () => {

      this.myRole = this.TAB_AUDITOR;
      this.renderRoleTabs();
      // this.proceedToCalendar();
      if (this.selectedFeatures.indexOf('contracts') >= 0) {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
      } else {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }

    });


    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-viewer')?.addEventListener('click', async () => {

      this.myRole = this.TAB_VIEWER;
      this.renderRoleTabs();
      // this.proceedToCalendar();
      if (this.selectedFeatures.indexOf('contracts') >= 0) {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
      } else {
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }

    });

  }

  csvmaker = (data: any) => {

    // Empty array for storing the values
    let csvRows = [];

    // Headers is basically a keys of an
    // object which is id, name, and
    // profession
    const headers = Object.keys(data);

    // As for making csv format, headers 
    // must be separated by comma and
    // pushing it into array
    csvRows.push(headers.join(','));

    // Pushing Object values into array
    // with comma separation
    const values = Object.values(data).join(',');
    csvRows.push(values)

    // Returning the array joining with new line 
    return csvRows.join('\n')
  }

  renderChartSettingsFilters = (container: HTMLDivElement, ctx: any) => {

    //console.log(container);

    var html = `
    
      <div class="m-10" part="filters-container">
        <div class="d-flex justify-end">
          <button id="chart-control-cancel" class="material-icons" part="button-icon-small">close</button>
        </div>
        <div class="d-flex justify-center align-end flex-wrap">
          <sf-i-form id="input-multi-entry-tags" name="Tags" label="Select Tags" apiId="${this.apiIdTags}" mode="multiselect-dropdown" searchPhrase="${this.projectName}" selectProjection="name" mandatory></sf-i-form>
          <button id="chart-control-plot" part="button" class="ml-20">Plot</button>          
        </div>
      </div>
    
    `;

    container.innerHTML = html;

    container.querySelector('#chart-control-plot')?.addEventListener('click', () => {

      const query = (container.querySelector('#input-multi-entry-tags') as SfIForm).selectedValues();
      this.filterTags = query;

      let eventContainer = null;

      if (this.getCurrentTab() == this.TAB_STREAM) {
        eventContainer = (this._SfStreamContainer as HTMLDivElement);
      }

      if (this.getCurrentTab() == this.TAB_UPCOMING) {
        eventContainer = (this._SfUpcomingContainer as HTMLDivElement);
      }

      if (this.getCurrentTab() == this.TAB_THIS) {
        eventContainer = (this._SfThisContainer as HTMLDivElement);
      }

      if (this.getCurrentTab() == this.TAB_PAST) {
        eventContainer = (this._SfPastContainer as HTMLDivElement);
      }

      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        eventContainer = (this._SfCustomContainer as HTMLDivElement);
      }

      const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf<HTMLElement>;
      const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf<HTMLTableElement>;
      const hiddenTitles = eventContainer!.querySelectorAll('.hidden-title') as NodeListOf<HTMLDivElement>;
      const hiddenFilternames = eventContainer!.querySelectorAll('.hidden-filtername') as NodeListOf<HTMLDivElement>;
      const filternames = eventContainer!.querySelectorAll('.filtername') as NodeListOf<HTMLTableCellElement>;
      const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement;

      if (this.filterTags.length > 0) {
        streamEventSummary.style.display = 'none';
      } else {
        streamEventSummary.style.display = 'block';
      }

      //console.log('divs', divs);

      for (var i = 0; i < divs.length; i++) {

        var found = false;
        var filterMatched = "";
        const tagsEmbedded = JSON.parse((divs[i] as HTMLDivElement).querySelector('.hidden-tags')?.innerHTML + "");
        //console.log(tagsEmbedded);
        for (var count1 = 0; count1 < tagsEmbedded.length; count1++) {
          for (var count2 = 0; count2 < this.filterTags.length; count2++) {
            if (tagsEmbedded[count1].toLowerCase().indexOf(this.filterTags[count2].toLowerCase()) >= 0) {
              found = true;
              filterMatched += (this.filterTags[count2].split(';')[0] + ", ");
            }
          }
        }
        if (!found) {
          (tables[i] as HTMLDivElement).style.display = 'none';
          (hiddenTitles[i] as HTMLDivElement).style.display = 'block';
          (hiddenFilternames[i] as HTMLDivElement).style.display = 'none';
          filternames[i].innerHTML = '';
        } else {
          (tables[i] as HTMLDivElement).style.display = 'block';
          (hiddenTitles[i] as HTMLDivElement).style.display = 'none';
          (hiddenFilternames[i] as HTMLDivElement).style.display = 'block';
          filternames[i].innerHTML = filterMatched.replace(/,\s*$/, "");;
        }
      }

      this.filterEventsInWindow(query, ctx, eventContainer);

    });

    container.querySelector('#chart-control-cancel')?.addEventListener('click', (e) => {

      let targetDiv = e.target as HTMLDivElement;
      let containerDiv = targetDiv.parentElement?.parentElement as HTMLDivElement;
      if (containerDiv != null) {
        containerDiv.innerHTML = '';
        containerDiv.parentElement?.parentElement?.querySelector('#chart-control-settings')?.setAttribute('part', 'calendar-tab-button-not-selected');
        containerDiv.parentElement?.parentElement?.querySelector('#chart-control-summary')?.setAttribute('part', 'calendar-tab-button-not-selected');
        // containerDiv.dispatchEvent(new CustomEvent('canceled', { bubbles: true }));
      }

      // container.innerHTML = '';
      // container.dispatchEvent(new CustomEvent('canceled', { bubbles: true }));

    });

  }

  renderChartSettingsSettings = (container: HTMLDivElement, selectedTab: number = 1, fromStats: boolean = false) => {

    var html = ``
    if (selectedTab == -1) {
      html = `
      
        <div class="m-10" part="settings-container">
          <div class="d-flex justify-end">
            <button id="chart-control-cancel" class="material-icons" part="button-icon-small">close</button>
          </div>

          <div class="d-flex justify-center">
            <div class="p-10 mr-10 w-100">
              <div part="td-head">Reports</div>
              <div part="td-body" class="d-flex align-center mt-10 flex-wrap">
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-csv" class="switch-csv" value="Excel" checked name="radio-report" part="radio-download"/>
                  <label for="radio-csv" part="label-radio-download" class="mr-10">Summary (CSV)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-image" class="switch-image" value="Image" name="radio-report" part="radio-download"/>
                  <label for="radio-image" part="label-radio-download" class="mr-10">Image (PNG)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-stats" class="switch-image" value="Stats" name="radio-report" part="radio-download"/>
                  <label for="radio-stats" part="label-radio-download" class="mr-10">Stats (HTML)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-list" class="switch-image" value="List" name="radio-report" part="radio-download"/>
                  <label for="radio-list" part="label-radio-download" class="mr-10">List (HTML)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-list-csv" class="switch-image" value="List" name="radio-report" part="radio-download"/>
                  <label for="radio-list-csv" part="label-radio-download" class="mr-10">List (CSV)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-consolidated" class="switch-image" value="Consolidated" name="radio-report" part="radio-download"/>
                  <label for="radio-consolidated" part="label-radio-download" class="mr-10">Consolidated (HTML)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-certificate" class="switch-image" value="Certificate" name="radio-report" part="radio-download"/>
                  <label for="radio-certificate" part="label-radio-download" class="mr-10">Certificate (HTML)</label>
                </div>
              </div>
              <div class="d-flex mt-10">
                <button id="button-download-stats" part="button" class="mt-5 ml-10">Download</button>
              </div>
            </div>
            <!-- <div class="p-10 ml-10 mr-10">
              <div part="td-head">Compliances</div>
              <div part="td-body" class="d-flex align-center mt-5">
                <input type="radio" id="radio-csv" class="switch-csv" value="Excel" checked part="radio-download"/>
                <label for="radio-html" part="label-radio-download">Html</label>
              </div>
              <div class="d-flex">
                <button id="button-download-compliances" part="button" class="mt-5">Download</button>
              </div>
            </div>
            <div class="p-10 ml-10">
              <div part="td-head">Certificate</div>
              <div part="td-body" class="d-flex align-center mt-5">
                <input type="radio" id="radio-html" class="switch-html" value="Html" checked part="radio-download"/>
                <label for="radio-html" part="label-radio-download">Html</label>
              </div>
              <div class="d-flex">
                <button id="button-download-certificate" part="button" class="mt-5">Download</button>
              </div>
            </div> -->
          </div>
        </div>
      
      `;
    } else if (selectedTab === 2) {
      html = `
      
        <div class="m-10" part="settings-container">
          <div class="d-flex justify-end">
            <button id="chart-control-cancel" class="material-icons" part="button-icon-small">close</button>
          </div>

          <div class="d-flex justify-center">
            <div class="p-10 mr-10 w-100">
              <div part="td-head">Reports</div>
              <div part="td-body" class="d-flex align-center mt-10 flex-wrap">
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-csv" class="switch-csv" value="Excel" checked name="radio-report" part="radio-download"/>
                  <label for="radio-csv" part="label-radio-download" class="mr-10">Summary (CSV)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-image" class="switch-image" value="Image" name="radio-report" part="radio-download"/>
                  <label for="radio-image" part="label-radio-download" class="mr-10">Image (PNG)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-stats" class="switch-image" value="Stats" name="radio-report" part="radio-download"/>
                  <label for="radio-stats" part="label-radio-download" class="mr-10">Stats (HTML)</label>
                </div>
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-list-csv" class="switch-image" value="List" name="radio-report" part="radio-download"/>
                  <label for="radio-list-csv" part="label-radio-download" class="mr-10">List (CSV)</label>
                </div>
              </div>
              <div class="d-flex mt-10">
                <button id="button-download-stats" part="button" class="mt-5 ml-10">Download</button>
              </div>
            </div>
          </div>
        </div>
      
      `;
    } else if (selectedTab === 3) {
      html = `
      
        <div class="m-10" part="settings-container">

          <div class="d-flex justify-center">
            <div class="p-10 mr-10 w-100">
              <div part="td-head">Reports</div>
              <div part="td-body" class="d-flex align-center mt-10 flex-wrap">
                <div class="mr-10 d-flex align-center mb-10">
                  <input type="radio" id="radio-list-csv" class="switch-image" value="List" checked name="radio-report" part="radio-download"/>
                  <label for="radio-list-csv" part="label-radio-download" class="mr-10">List (CSV)</label>
                </div>
              </div>
              <div class="d-flex mt-10">
                <button id="button-download-stats" part="button" class="mt-5 ml-10">Download</button>
              </div>
            </div>
          </div>
        </div>
      
      `;
    }

    container.innerHTML = html;

    container.querySelector('#chart-control-cancel')?.addEventListener('click', (e) => {

      let targetDiv = e.target as HTMLDivElement;
      let containerDiv = targetDiv.parentElement?.parentElement as HTMLDivElement;
      console.log('containerDiv', containerDiv);
      if (containerDiv != null) {
        containerDiv.innerHTML = '';
        containerDiv.parentElement?.parentElement?.querySelector('#chart-control-settings')?.setAttribute('part', 'calendar-tab-button-not-selected');
        containerDiv.parentElement?.parentElement?.querySelector('#chart-control-summary')?.setAttribute('part', 'calendar-tab-button-not-selected');
        // containerDiv.dispatchEvent(new CustomEvent('canceled', { bubbles: true }));
      }
    });

    container.querySelector('#button-download-stats')?.addEventListener('click', async () => {

      const radioCsv = (container.querySelector('#radio-csv') as HTMLInputElement);
      const radioImage = (container.querySelector('#radio-image') as HTMLInputElement);
      const radioStats = (container.querySelector('#radio-stats') as HTMLInputElement);
      const radioList = (container.querySelector('#radio-list') as HTMLInputElement);
      const radioListCsv = (container.querySelector('#radio-list-csv') as HTMLInputElement);
      const radioConsolidated = (container.querySelector('#radio-consolidated') as HTMLInputElement);
      const radioCertificate = (container.querySelector('#radio-certificate') as HTMLInputElement);
      if (selectedTab === -1 && !(radioImage.checked)) {
        let oldFilters = this.selectedFilters
        if (this.selectedFeatures.indexOf('compliances') >= 0) {
          await this.fetchAndYearlyRenderUserCalendar_2(this.sdate, this.edate, "", "no", "00", this.calendarStartYYYY, true)
        } else if (this.selectedFeatures.indexOf('notices') >= 0) {
          await this.fetchAndRenderNotices(this.sdate, this.edate, "", "no");
        } else if (this.selectedFeatures.indexOf('contracts') >= 0) {
          await this.fetchAndRenderContracts(this.sdate, this.edate, "", "no");
        } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
          await this.fetchAndRenderLicenses(this.sdate, this.edate, "", "no");
        } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
          await this.fetchAndRenderRCMResources(this.sdate, this.edate, "", "no");
        }
        // await this.fetchAndYearlyRenderUserCalendar_2(this.sdate, this.edate, "", "no");
        this.selectedFilters = oldFilters
      }

      //console.log('radiocsv checked', radioCsv.checked);
      //console.log('radioimage checked', radioImage.checked);

      if (radioCsv?.checked) {

        const blob2 = new Blob([this.csvGraphStats], { type: 'text/csv' });
        const url2 = window.URL.createObjectURL(blob2)
        const a2 = document.createElement('a')
        a2.setAttribute('href', url2)
        a2.setAttribute('download', 'download_' + new Date() + '.csv');
        a2.click()

      }

      if (radioImage?.checked) {
        setTimeout(() => {
          this.downloadChart(this.chart)
          // const a = document.createElement('a')
          // a.setAttribute('href', this.chartBase64)
          // a.setAttribute('download', 'download_' + new Date().getTime() + '.png');
          // a.click()
          console.log('this.chart2 Download', fromStats);
          // if (this.chart2Base64 != null) {
          this.downloadChart(this.chart2, fromStats ? 'functionwise' : 'completeness')
          // console.log('this.chart2 download', this.chart2Base64);
          // const a2 = document.createElement('a')
          // a2.setAttribute('href', this.chart2Base64)
          // a2.setAttribute('download', 'download_completeness_' + new Date().getTime() + '.png');
          // a2.click()
          // }

          // if (this.chart3Base64 != null) {
          this.downloadChart(this.chart3, fromStats ? 'locationwise' : 'timeliness')
          // const a3 = document.createElement('a')
          // a3.setAttribute('href', this.chart3Base64)
          // a3.setAttribute('download', 'download_timeliness_' + new Date().getTime() + '.png');
          // a3.click()
          // }

          // if (this.chart4Base64 != null) {
          this.downloadChart(this.chart4, fromStats ? 'reporterwise' : 'compliance')
          // const a4 = document.createElement('a')
          // a4.setAttribute('href', this.chart4Base64)
          // a4.setAttribute('download', 'download_compliance_' + new Date().getTime() + '.png');
          // a4.click()
          // }
        }, 2000)

      }

      if (radioStats?.checked) {
        const ts = new Date().getTime();
        console.log('htmlstatsfilter', this.htmlStatsFilter, selectedTab);
        var html = this.COMPLIANCES_HTML;
        html = html.replace(/PROJECT_NAME/g, this.projectName);
        if (selectedTab == -1) {
          html = html.replace(/FILTERS_DATA/g, '');
        } else {
          let filtersHtml = `
            <div>
              ${this.htmlStatsFilter}
            </div>
          `
          html = html.replace(/FILTERS_DATA/g, filtersHtml);
        }
        html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period);

        console.log('htmlsDataStats', this.htmlDataStats);
        let tempHtml: string = "";
        tempHtml += this.htmlDataStats;
        if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
        } else {
          tempHtml += ('<br />' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : ""));
          tempHtml += ('<br />' + (this.csvToHtmlTable(this.csvCompletenessStats) + '<br />' + this.csvToHtmlTable(this.csvTimelinessStats) + '<br />' + this.csvToHtmlTable(this.csvComplianceStats)));
        }

        html = html.replace(/PERSON_COMPLIANCES/g, tempHtml);

        const blob = new Blob([html], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'report_' + ts + '.html');
        a.click()
      }

      if (radioList?.checked) {
        const ts = new Date();

        var html = this.COMPLIANCES_HTML;
        html = html.replace(/PROJECT_NAME/g, this.projectName);
        html = html.replace(/FILTERS_DATA/g, '');
        html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period);

        let tempHtml: string = "";
        tempHtml += this.getFilteredString();
        html = html.replace(/PERSON_COMPLIANCES/g, tempHtml);

        const blob = new Blob([html], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'report_' + ts + '.html');
        a.click()
      }

      if (radioListCsv?.checked) {

        const ts = new Date();
        if (selectedTab == -1 || selectedTab == 3) {
          console.log(this.csvDataCompliances, this.selectedFilters);
          if (this.selectedFilters != null) {
            let filteredCsvDataCompliances: any[] = []
            let listContainer = this._SfThisContainer as HTMLDivElement

            if (this.selectedTab == this.TAB_STREAM) {
              listContainer = this._SfStreamContainer as HTMLDivElement
            }

            if (this.selectedTab == this.TAB_THIS) {
              listContainer = this._SfThisContainer as HTMLDivElement
            }
            if (this.selectedTab == this.TAB_CUSTOM) {
              listContainer = this._SfCustomContainer as HTMLDivElement
            }
            if (selectedTab === 3) {
              listContainer = this._SfDetailListContainer as HTMLDivElement
            }

            for (let mmdd of Object.keys(this.events)) {
              for (let [j, event] of this.events[mmdd].entries()) {
                const isBulk = event.isbulk === true;
                const hasReportFormat = event.reportformat?.length > 0;
                const hasCustomReporting = event.customreporting != null;
                const hasMakerCheckers = event.makercheckers?.length > 0;
                const hasDocs = event.docs?.length > 0;
                const moduleType = event.module ?? 'compliance';
                const partStatusSanitized = (event[this.FLOW_GRAPH_COMPLETENESS] ?? "").replace(/-/g, '_');
                const entityIdSanitized = event.entityid.replace(/-/g, '_');
                const locationIdSanitized = (event.locationid ?? "").replace(/-/g, '_');
                const eventIdSanitized = event.id.replace(/-/g, '_');
                const mmddSanitized = mmdd.replace(/\//g, '-');
                const dueDateParts = event.duedate.split('/');
                const isReportedLocation = event.reportedlocationsflag == true

                let inputId = `button-select-${mmddSanitized}-${j}-${hasMakerCheckers ? '1' : '0'}-${hasDocs ? '1' : '0'}-${entityIdSanitized}-${locationIdSanitized}-${eventIdSanitized}-${dueDateParts[1]}-${dueDateParts[0]}-${dueDateParts[2]}-${partStatusSanitized}-${moduleType}-${isBulk ? 'bulk' : ''}${(hasReportFormat || isBulk || hasCustomReporting) ? 'reportformat' : ''}${(isReportedLocation) ? 'reportedlocations' : ''}`

                let input = listContainer.querySelector('#' + inputId) as HTMLInputElement
                if (input == null || input.style.display == 'none') {
                  continue;
                }
                console.log('inputElement', input.style.display, mmdd, j);

                filteredCsvDataCompliances.push(event);
              }
            }

            console.log('filtered compliances found: ' + filteredCsvDataCompliances.length)

            let filteredCsv = 'Id,Country,Entity,Location,Function,Reporter,Approver,Functionhead,State,Jurisdiction,Category,Subcategory,Statute,Reference,Applicability,ObligationType,ObligationTitle,Obligation,Firstlineofdefence,Secondlineofdefence,Thirdlineofdefence,Internalcontrols,Penalty,Form,AdditionalUrl,Definition,Authority,RiskSeverity,RiskAreas,Frequency,SubFrequency,DueDate,Status,ReportParameter\n'

            for (let event of filteredCsvDataCompliances) {

              filteredCsv += ('"' + (event["id"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["countryname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["entityname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["locationname"] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((((event["functions"] ?? [])[0] ?? "").split(';')[0] + "").replace(/\((.*?)\)/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((((event["reporters"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((((event["approvers"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((((event["functionheads"] ?? [])[0] ?? "").split(';')[0] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (event["state"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (event["jurisdiction"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (event["category"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (event["subcategory"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (event["statute"] + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["reference"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["applicability"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["obligationtype"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["obligationtitle"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["obligation"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["firstlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["secondlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["thirdlineofdefence"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["internalcontrols"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["penalty"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["form"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["additionalurls"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["definition"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["authority"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["risk"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["riskarea"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["frequency"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["subfrequency"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + ((event["duedate"] + "").replace(/"/g, "") + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (this.renderStatusString(event[this.FLOW_GRAPH_COMPLETENESS], event[this.FLOW_GRAPH_TIMELINESS], event[this.FLOW_GRAPH_COMPLIANCE]) + '",').replace(/\n/g, ' '));
              filteredCsv += ('"' + (this.getGraphParam(event).replace(/\n/g, ' ') + '"\n'));

            }
            const blob = new Blob([filteredCsv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.setAttribute('href', url)
            a.setAttribute('download', 'report_' + ts + '.csv');
            a.click()
          } else {
            const blob = new Blob([this.csvDataCompliances], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.setAttribute('href', url)
            a.setAttribute('download', 'report_' + ts + '.csv');
            a.click()
          }
        } else {
          console.log(this.statisticsFiltersCsv);
          let csvData = Util.convertToCSVStats(this.statisticsFiltersCsv);
          console.log('csvData', csvData);
          const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', url)
          a.setAttribute('download', 'statistics_list_' + new Date().getTime() + '.csv');
          a.click()
        }
      }

      if (radioConsolidated?.checked) {

        const ts = new Date().getTime();

        var html = this.COMPLIANCES_HTML;
        html = html.replace(/PROJECT_NAME/g, this.projectName);
        html = html.replace(/FILTERS_DATA/g, '');
        html = html.replace(/REPORT_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear() + " " + new Date().getHours() + ":" + new Date().getMinutes() + ' for the period ' + this.period);

        let tempHtml: string = "";
        tempHtml += this.htmlDataStats;
        if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
        } else {
          tempHtml += ('<br />' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : ""));
          tempHtml += ('<br />' + (this.csvToHtmlTable(this.csvCompletenessStats) + '<br />' + this.csvToHtmlTable(this.csvTimelinessStats) + '<br />' + this.csvToHtmlTable(this.csvComplianceStats)));
        }
        tempHtml += this.getFilteredString();
        html = html.replace(/PERSON_COMPLIANCES/g, tempHtml);

        const blob = new Blob([html], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'report_' + ts + '.html');
        a.click()


      }

      if (radioCertificate?.checked) {

        var html = this.CERTIFICATE_HTML;
        html = html.replace(/PERSON_NAME/g, this.userName);
        html = html.replace(/PERSON_DESIGNATION/g, this.myRole);
        html = html.replace(/PERSON_COMPANY/g, this.projectName);
        html = html.replace(/PERSON_CRITERIA/g, this.selectedCriteria);
        html = html.replace(/PERSON_DATE/g, new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getFullYear());

        let tempHtml: string = "";
        tempHtml += this.htmlDataStats;
        if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
        } else {
          tempHtml += ('<br />' + (this.csvGraphStats.length > 0 ? this.csvToHtmlTable(this.csvGraphStats) : ""));
          tempHtml += ('<br />' + (this.csvToHtmlTable(this.csvCompletenessStats) + '<br />' + this.csvToHtmlTable(this.csvTimelinessStats) + '<br />' + this.csvToHtmlTable(this.csvComplianceStats)));
        }

        html = html.replace(/PERSON_COMPLIANCE_STATUS/g, tempHtml);
        html = html.replace(/PERSON_COMPLIANCES/g, this.getFilteredString());
        html = html.replace(/PERSON_PERIOD/g, this.period);

        //console.log('downloaded certificate');
        const blob = new Blob([html], { type: 'text/html' });
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', url)
        a.setAttribute('download', 'certificate.html');
        a.click()

      }

    })

    container.querySelector('.switch-solid')?.addEventListener('click', () => {

      this.fill = "solid";
      if (this.getCurrentTab() == this.TAB_STREAM) {
        this.renderStream(0, true, false);
      }

    });

    container.querySelector('.switch-pattern')?.addEventListener('click', () => {

      this.fill = "pattern";
      if (this.getCurrentTab() == this.TAB_STREAM) {
        this.renderStream(0, true, false);
      }

    });

  }

  renderChartSettings = (container: HTMLDivElement, selectedTab: number = -1, selectedSummary: number = -1, ctx: any, fromStats: boolean = false) => {
    console.log('rendering chart settings', selectedTab, selectedSummary, fromStats);
    var html = '';

    html += '<div class="d-flex justify-end align-start">';
    if ((this.selectedFeatures.indexOf('compliances') >= 0) && (this.selectedFeatures.indexOf('notices') < 0) && (this.selectedFeatures.indexOf('contracts') < 0) && (this.selectedFeatures.indexOf('licenses') < 0) && (this.selectedFeatures.indexOf('rcmresources') < 0) && selectedSummary < 2) {
      html += '<button class="tab-button" id="input-show-reported-locations" part="' + (this.showReportedLocations ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '" class="mr-10"><span class="material-symbols-outlined">arrow_or_edge</span></button>';
    }
    if (selectedTab === 0) {
      //html += '<button class="tab-button" id="chart-control-filters" part="calendar-tab-button-selected" class="mr-10"><span class="material-icons">filter_list</span></button>';
    } else {
      //html += '<button class="tab-button" id="chart-control-filters" part="calendar-tab-button-not-selected" class="mr-10"><span class="material-icons">filter_list</span></button>';
    }
    if (selectedTab === 1) {
      html += '<button class="tab-button" id="chart-control-settings" part="calendar-tab-button-selected" class="mr-10"><span class="material-icons">cloud_download</span></button>';
    } else {
      html += '<button class="tab-button" id="chart-control-settings" part="calendar-tab-button-not-selected" class="mr-10"><span class="material-icons">cloud_download</span></button>';
    }
    // if (selectedTab === 1) {
    //   html += '<button class="tab-button" id="chart-expand" part="calendar-tab-button-selected" class="mr-10"><span class="material-symbols-outlined">open_in_full</span></button>';
    // } else {
    html += '<button class="tab-button" id="chart-expand" part="calendar-tab-button-not-selected" class="mr-10"><span class="material-symbols-outlined">open_in_full</span></button>';
    // }
    if (selectedSummary === 1) {
      html += '<button class="tab-button" id="chart-control-summary" part="calendar-tab-button-selected" class="mr-10"><span class="material-icons">summarize</span></button>';
    } else if (selectedSummary < 2) {
      html += '<button class="tab-button" id="chart-control-summary" part="calendar-tab-button-not-selected" class="mr-10"><span class="material-icons">summarize</span></button>';
    }

    html += '</div>';

    console.log('ChartSettingsControls', container, container.querySelector('#chart-settings-controls') as HTMLDivElement)
    if ((container.querySelector('#chart-settings-controls') as HTMLDivElement) != null) {
      (container.querySelector('#chart-settings-controls') as HTMLDivElement).innerHTML = html;

      (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings')?.addEventListener('click', () => {

        this.renderChartSettings(container, 1, selectedSummary, ctx, fromStats);

      });
      (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-summary')?.addEventListener('click', () => {
        console.log('summary clicked');
        this.renderChartSummary();

      });
      const buttonRefresh = container.querySelector('#button-refresh') as HTMLButtonElement
      if (buttonRefresh != null) {
        const inputShowReportedLocations = container.querySelector('#input-show-reported-locations') as HTMLButtonElement
        inputShowReportedLocations?.addEventListener('click', () => {
          this.showReportedLocations = !this.showReportedLocations;
          let clickEvent = new Event('click', {})
          buttonRefresh?.dispatchEvent(clickEvent);
        })
      }


      const buttonChartExpand = container.querySelector('#chart-expand') as HTMLButtonElement
      if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
        if (buttonChartExpand != null) {
          buttonChartExpand.classList.add('hide')
        }
      } else {
        if (buttonChartExpand != null) {
          buttonChartExpand.classList.remove('hide')
        }
      }
      buttonChartExpand?.addEventListener('click', () => {
        const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement

        chartModalContainer.classList.remove('hide');

        // let chartModalTitle = chartModalContainer.querySelector('#chart-modal-title') as HTMLDivElement

        console.log('rendering chart', this.flowGraph);
        switch (this.flowGraph) {
          case this.FLOW_GRAPH_COMPLETENESS:
            this.renderCompletenessGraph(chartModalContainer);
            // chartModalTitle.innerHTML = "Completeness Distribution"
            break;
          case this.FLOW_GRAPH_TIMELINESS:
            this.renderTimelinessGraph(chartModalContainer);
            // chartModalTitle.innerHTML = "Timeliness Distribution"
            break;
          case this.FLOW_GRAPH_COMPLIANCE:
            this.renderComplianceGraph(chartModalContainer);
            // chartModalTitle.innerHTML = "Compliance Distribution"
            break;
          case this.FLOW_GRAPH_RISKAREAS:
            this.renderRiskGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "RiskAreas Distribution"
            break;
          case this.FLOW_GRAPH_RISKSEVERITY:
            this.renderRiskSeverityGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Risk Distribution"
            break;
          case this.FLOW_GRAPH_LOCATION:
            this.renderLocationGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Locations Distribution"
            break;
          case this.FLOW_GRAPH_FUNCTION:
            this.renderFunctionGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Functions Distribution"
            break;
          case this.FLOW_GRAPH_OBLIGATIONTYPE:
            this.renderObligationTypeGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "ObligationTypes Distribution"
            break;
          case this.FLOW_GRAPH_JURISDICTION:
            this.renderJurisdictionGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Jurisdictions Distribution"
            break;
          case this.FLOW_GRAPH_FREQUENCY:
            this.renderFrequencyGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Frequencies Distribution"
            break;
          case this.FLOW_GRAPH_SUBCATEGORY:
            this.renderSubcategoryGraph(chartModalContainer, false, true);
            // chartModalTitle.innerHTML = "Subcategories Distribution"
            break;

          default:
            this.renderCompletenessGraph(chartModalContainer);
            // chartModalTitle.innerHTML = "Completeness Distribution"
            break;
        }
      })

      const buttonCloseChartModal = container.querySelector('#chart-modal-close') as HTMLButtonElement
      buttonCloseChartModal?.addEventListener('click', () => {
        const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement

        chartModalContainer.classList.add('hide');
        this.clearGraph(chartModalContainer, 1)
        this.clearGraph(chartModalContainer, 2)
        this.clearGraph(chartModalContainer, 3)
        this.clearGraph(chartModalContainer, 4)
        let parentElement = chartModalContainer.parentElement as HTMLDivElement
        if (parentElement != null) {
          switch (this.flowGraph) {
            case this.FLOW_GRAPH_COMPLETENESS:
              this.renderCompletenessGraph(parentElement);
              break;
            case this.FLOW_GRAPH_TIMELINESS:
              this.renderTimelinessGraph(parentElement);
              break;
            case this.FLOW_GRAPH_COMPLIANCE:
              this.renderComplianceGraph(parentElement);
              break;
            case this.FLOW_GRAPH_RISKAREAS:
              this.renderRiskGraph(parentElement);
              break;
            case this.FLOW_GRAPH_RISKSEVERITY:
              this.renderRiskSeverityGraph(parentElement);
              break;
            case this.FLOW_GRAPH_LOCATION:
              this.renderLocationGraph(parentElement);
              break;
            case this.FLOW_GRAPH_FUNCTION:
              this.renderFunctionGraph(parentElement);
              break;
            case this.FLOW_GRAPH_OBLIGATIONTYPE:
              this.renderObligationTypeGraph(parentElement);
              break;
            case this.FLOW_GRAPH_JURISDICTION:
              this.renderJurisdictionGraph(parentElement);
              break;
            case this.FLOW_GRAPH_FREQUENCY:
              this.renderFrequencyGraph(parentElement);
              break;
            case this.FLOW_GRAPH_SUBCATEGORY:
              this.renderSubcategoryGraph(parentElement);
              break;
            default:
              this.renderCompletenessGraph(parentElement);
              break;
          }
        }
      })

      const buttonChartTypeOld = container.querySelector('#chart-modal-chart-type') as HTMLButtonElement
      if (buttonChartTypeOld != null) {
        let buttonChartType = Util.clearListeners(buttonChartTypeOld);
        buttonChartType?.addEventListener('click', (e) => {
          let button = e.target as HTMLButtonElement
          const chartModalContainer = container.querySelector('#chart-modal-container') as HTMLDivElement

          if (button.innerHTML === "bar_chart") {
            button.innerHTML = "donut_large"
            switch (this.flowGraph) {
              case this.FLOW_GRAPH_COMPLETENESS:
                this.renderCompletenessGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_TIMELINESS:
                this.renderTimelinessGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_COMPLIANCE:
                this.renderComplianceGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_RISKAREAS:
                this.renderRiskGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_RISKSEVERITY:
                this.renderRiskSeverityGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_LOCATION:
                this.renderLocationGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_FUNCTION:
                this.renderFunctionGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_OBLIGATIONTYPE:
                this.renderObligationTypeGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_JURISDICTION:
                this.renderJurisdictionGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_FREQUENCY:
                this.renderFrequencyGraph(chartModalContainer, true, true);
                break;
              case this.FLOW_GRAPH_SUBCATEGORY:
                this.renderSubcategoryGraph(chartModalContainer, true, true);
                break;
              default:
                this.renderCompletenessGraph(chartModalContainer);
                break;
            }
          } else {
            button.innerHTML = "bar_chart"
            switch (this.flowGraph) {
              case this.FLOW_GRAPH_COMPLETENESS:
                this.renderCompletenessGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_TIMELINESS:
                this.renderTimelinessGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_COMPLIANCE:
                this.renderComplianceGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_RISKAREAS:
                this.renderRiskGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_RISKSEVERITY:
                this.renderRiskSeverityGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_LOCATION:
                this.renderLocationGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_FUNCTION:
                this.renderFunctionGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_OBLIGATIONTYPE:
                this.renderObligationTypeGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_JURISDICTION:
                this.renderJurisdictionGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_FREQUENCY:
                this.renderFrequencyGraph(chartModalContainer);
                break;
              case this.FLOW_GRAPH_SUBCATEGORY:
                this.renderSubcategoryGraph(chartModalContainer);
                break;

              default:
                this.renderCompletenessGraph(chartModalContainer);
                break;
            }
          }
        })
      }

      const buttonChartDownloadOld = container.querySelector('#chart-modal-download') as HTMLButtonElement
      if (buttonChartDownloadOld != null) {
        let buttonChartDownload = Util.clearListeners(buttonChartDownloadOld);
        buttonChartDownload?.addEventListener('click', () => {
          setTimeout(() => {
            this.downloadChart(this.chart)
            // const a = document.createElement('a')
            // a.setAttribute('href', this.chartBase64)
            // a.style.backgroundColor = '#fff'
            // a.setAttribute('download', 'download_' + new Date().getTime() + '.png');
            // a.click()
            // console.log('this.chart2', (this.chart2Base64));
            // if (this.chart2Base64 != null) {
            // console.log('this.chart2 download', this.chart2Base64);
            // const a2 = document.createElement('a')
            // a2.setAttribute('href', this.chart2Base64)
            // a2.style.backgroundColor = '#fff'
            // a2.setAttribute('download', 'download_completeness_' + new Date().getTime() + '.png');
            // a2.click()
            this.downloadChart(this.chart2, 'completeness')
            // }

            // if (this.chart3Base64 != null) {
            // const a3 = document.createElement('a')
            // a3.setAttribute('href', this.chart3Base64)
            // a3.style.backgroundColor = '#fff'
            // a3.setAttribute('download', 'download_timeliness_' + new Date().getTime() + '.png');
            // a3.click()
            this.downloadChart(this.chart3, 'timeliness')
            // }

            // if (this.chart4Base64 != null) {
            // const a4 = document.createElement('a')
            // a4.setAttribute('href', this.chart4Base64)
            // a4.style.backgroundColor = '#fff'
            // a4.setAttribute('download', 'download_compliance_' + new Date().getTime() + '.png');
            // a4.click()
            this.downloadChart(this.chart4, 'compliance')
            // }
          }, 2000)
        })
      }
    }

    // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters')?.addEventListener('click', () => {

    //   this.renderChartSettings(container, 0, ctx);

    // });

    if (selectedTab === 0) {

      const radioCompleteness = container.querySelector('#radio-completeness') as HTMLButtonElement;
      radioCompleteness.click();
      this.renderChartSettingsFilters((container.querySelector('#chart-settings') as HTMLDivElement), ctx);
    }

    if (selectedTab === 1) {
      this.renderChartSettingsSettings((container.querySelector('#chart-settings') as HTMLDivElement), selectedSummary, fromStats);
    }

    if (selectedSummary === 3) {

      if (selectedTab === 3) {
        // let innerHtml = (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML
        let innerHtml = '<div class="m-10" part="settings-container"></div>';
        (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = innerHtml;

      } else {
        (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings')?.setAttribute('part', 'calendar-tab-button-selected');

        let newChartControlSettingsButton = Util.clearListeners((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement)
        newChartControlSettingsButton?.addEventListener('click', () => {

          this.renderChartSettings(container, 3, selectedSummary, ctx, fromStats);

        });

        this.renderChartSettingsSettings((container.querySelector('#chart-settings') as HTMLDivElement), selectedSummary, fromStats);
      }
    }

    (container.querySelector('#chart-settings') as HTMLDivElement)?.addEventListener('canceled', () => {
      //console.log('canceled');
      if (this.getCurrentTab() == this.TAB_STREAM) {
        this.renderChartSettings(container, -1, -1, ctx);
        this.renderStream(this.streamIndex, false, false);
      }
      // if(this.getCurrentTab() == this.TAB_UPCOMING) {
      //   this.renderChartSettings(container, -1, ctx);
      //   this.renderUpcoming(this.streamIndex);
      // }
      if (this.getCurrentTab() == this.TAB_THIS) {
        this.renderChartSettings(container, -1, -1, ctx);
        this.renderThis(this.streamIndex, false, false);
      }
      // if(this.getCurrentTab() == this.TAB_PAST) {
      //   this.renderChartSettings(container, -1, ctx);
      //   this.renderPast(this.streamIndex);
      // }
      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        if (selectedSummary === 2) {
          this.processDateSelectionViewer(container)
        } else {
          this.processDateSelection(container);
        }
      }
    })


    // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel')?.addEventListener('click', () => {

    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'flex';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'flex';
    //   (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = '';

    // });


    // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel')?.addEventListener('click', () => {

    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'flex';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'flex';
    //   (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = '';

    // });



    // (container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters')?.addEventListener('click', () => {

    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters-cancel') as HTMLButtonElement).style.display = 'flex';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings-cancel') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-settings') as HTMLButtonElement).style.display = 'none';
    //   ((container.querySelector('#chart-settings-controls') as HTMLDivElement).querySelector('#chart-control-filters') as HTMLButtonElement).style.display = 'none';
    //   (container.querySelector('#chart-settings') as HTMLDivElement).innerHTML = '';
    //   this.renderChartSettingsFilters((container.querySelector('#chart-settings') as HTMLDivElement));

    // })

  }

  downloadChart = (chart: Chart, name: string = "") => {
    const pluginOptions = chart.options.plugins?.exportBackground;

    if (!pluginOptions) return;

    // Enable export mode
    pluginOptions.exporting = true;

    chart.update();

    // Wait for next render frame
    requestAnimationFrame(() => {
      const image = chart.toBase64Image();

      // Disable export mode
      pluginOptions.exporting = false;
      chart.update();

      // Download
      const link = document.createElement('a');
      link.href = image;
      link.download = 'download_' + ((name == "") ? "" : (name + '_')) + new Date().getTime() + '.png'
      link.click();
    });
  }

  renderChartSummary = () => {
    var html = `
      <style>
        body {
          font-family: DM Sans;
          margin: 2px;
          padding: 20px;
        }
        .status-format {
          text-transform: uppercase;
        }
        .text-center {
          text-align: center;
        }
        .d-flex {
          display: flex;
        }
        .justify-center {
          justify-content: center;
        }
        .justify-between {
          justify-content: space-between;
        }
        .align-center {
          align-items: center;
        }
        .mt-10 {
          margin-top: 10px;
        }
        .w-25 {
          width: 25%;
        }
        .w-16 {
          width: 16%;
        }
        .w-14 {
          width: 14%;
        }
        .w-12 {
          width: 12%;
        }
        .w-100 {
          width: 100%;
        }
        .w-200px {
          width: 200px;
        }
        .text-center {
          text-align: center;
        }
        table {
          box-shadow: 1px 1px 10px 0 rgba(0, 0, 0, 0.25), -1px -1px 10px 0 rgba(255, 255, 255, 0.6);
          border-top: solid 1px rgba(255, 255, 255, 0.8);
          border-left: solid 1px rgba(255, 255, 255, 0.8);
          border-bottom: solid 1px rgba(255, 255, 255, 0.8);
          border-right: solid 1px rgba(255, 255, 255, 0.8);
          overflow:auto;
        }
        th {
          background-color: #6a6a6a;
          color: white;
          padding: 5px;
        }
        .td-thin {
          min-width: 150px;
        }
        .td-wide {
          min-width: 300px;
        }
        td {
          padding: 5px;
          font-size: 70%;
          vertical-align: top;
          min-width: 200px;
        }
        td span {
          font-size: 130% !important;
        }
        .td-odd {
          background-color: #efefef;
          
        }
        .td-even {
          background-color: #dedede;
        }
        .color-pending {
          color: #ffe505;
        }
        .color-pending-approval {
          color: #ffe505;
        }
        .color-not-started {
          color: #888888;
        }
        .color-not-complied {
          color: #C80036;
        }
        .color-partially-complied {
          color: #F79256;
        }
        .color-complied {
          color: #50cf01;
        }
        .color-complied-with-gaps {
          color: #ffe505;
        }
        .color-reported-non-compliance {
          color: #840B0F;
        }
        .color-scheduled {
          color: #888888;
        }
        .color-done {
          color: #50cf01;
        }
        .color-rejected {
          color: #C80036;
        }
        .color-approved {
          color: #50cf01;
        }
        .color-past-due-date {
          color: #ffe505;
        }
        .color-late-executed {
          color: #840B0F;
        }
        .color-late-approved {
          color: #EE2F36;
        }
        .color-late-reported {
          color: #Ef9C66;
        }
        .h-100 {
          height: 100vh;
        }
        .abs {
          position: absolute;
        }
        .watermark {
          background-image: url(https://flagggrc-images.s3.amazonaws.com/logo.png);
          background-position: center;
          background-repeat: no-repeat;
          opacity: 5%;
          width: 100%;
          height: 100vh;
          position: fixed;
        }
        .scroll-x {
          display: block;
          overflow-x: auto;
        }
      </style>
      <div class="d-flex justify-between m-20">
        <button part="button-icon" class="material-icons invisible">close</button>
        <h3 part="results-title" class="m-0">Reporting Summary</h3>
        <button id="button-detail-close" part="button-icon" class="material-icons">close</button>
      </div>
    
    `;
    html += this.htmlDataStats;
    html += '<div class="m-20"></div>';
    html += this.getFilteredStringSummary();
    // html += '<div class="m-20"></div>';
    // html += this.htmlDataSummary;
    (this._SfReportSummaryContainer as HTMLDivElement).innerHTML = html;
    (this._SfReportSummaryContainer as HTMLDivElement).style.display = 'block';

    (this._SfReportSummaryContainer as HTMLDivElement).querySelector('#button-detail-close')?.addEventListener('click', () => {

      (this._SfReportSummaryContainer as HTMLDivElement).innerHTML = '';
      (this._SfReportSummaryContainer as HTMLDivElement).style.display = 'none';

    });

    let summaryDocuments = (this._SfReportSummaryContainer as HTMLDivElement).querySelectorAll('.summary-report-doc') as NodeListOf<SfIUploader>;
    for (let summaryDocument of summaryDocuments) {
      summaryDocument.loadMode();
    }
  }

  csvToHtmlTable = (strCsv: string) => {
    const htmlRows = [];
    const lines = strCsv.trim().split(/\r?\n/);

    const parseCsvLine = (line: string): string[] => {
      const result = [];
      let current = '';
      let inQuotes = false;

      for (let i = 0; i < line.length; i++) {
        const char = line[i];
        const nextChar = line[i + 1];

        if (char === '"' && inQuotes && nextChar === '"') {
          current += '"'; // escaped quote
          i++; // skip next quote
        } else if (char === '"') {
          inQuotes = !inQuotes;
        } else if (char === ',' && !inQuotes) {
          result.push(current);
          current = '';
        } else {
          current += char;
        }
      }
      result.push(current);
      return result;
    };

    htmlRows.push('<br />' + parseCsvLine(lines[0])[0] + '<br /><br />');
    htmlRows.push('<table>');

    lines.forEach((line, index) => {
      const cells = parseCsvLine(line);
      const tag = index === 0 ? 'th' : 'td';
      htmlRows.push('<tr>');
      cells.forEach(cell => {
        htmlRows.push(`<${tag} class="${tag === 'td' ? 'text-center' : ''}">${cell}</${tag}>`);
      });
      htmlRows.push('</tr>');
    });

    htmlRows.push('</table>');
    return htmlRows.join('');
  };


  csvToHtmlTable1 = (strCsv: string) => {

    var html = '';

    //console.log('csvToHtmlTable', strCsv);

    var strArr = strCsv.split("\n");

    //console.log('csvToHtmlTable', strArr);

    html += '<br />' + strArr[0].split(',')[0] + '<br /><br />';

    html += '<table>';

    for (var i = 0; i < strArr.length; i++) {

      html += '<tr>';
      if (i === 0) {

        const strArrArr = strArr[i].split(',');
        for (var j = 0; j < strArrArr.length; j++) {
          html += ('<th>' + strArrArr[j] + '</th>');
        }

      } else {

        const strArrArr = strArr[i].split(',');
        for (var j = 0; j < strArrArr.length; j++) {
          html += ('<td class="text-center">' + strArrArr[j] + '</td>');
        }

      }
      html += '</tr>';

    }

    html += '</table>';

    //console.log('csvToHtmlTable', html);

    return html;


  }

  getFilteredString = () => {

    //console.log('selectedfilter', this.selectedFilter);

    var tempDiv = document.createElement('div');
    tempDiv.id = "div-filter-content";
    tempDiv.innerHTML = this.htmlDataCompliances;

    const newArrList: Array<HTMLTableRowElement> = [];

    //console.log('tempDiv', this.htmlDataCompliances);

    const rows = tempDiv.querySelectorAll('tr');
    for (var i = 0; i < rows.length; i++) {
      let cols = rows[i].querySelectorAll('td');
      if (cols.length === 0) {
        cols = rows[i].querySelectorAll('th');
      }
      if (i === 0) {
        newArrList.push(rows[i]);
      } else {

        if (cols.length > 0) {
          if (this.selectedFilters == null) {
            newArrList.push(rows[i]);
          } else {

            if (!this.selectedFilters.selected) {

              var found = false;

              for (var j = 0; j < this.selectedFilters.length; j++) {
                if (cols[cols.length - 1].innerHTML.toLowerCase().replace(/&amp;/g, '&').indexOf(this.selectedFilters[j].value.toLowerCase().replace(/&amp;/g, '&')) >= 0) {
                  found = true;
                }
              }

              if (!found) {
                newArrList.push(rows[i]);
              }

            } else {

              //console.log('selected filter', this.selectedFilter, cols[cols.length - 1].innerHTML.toLowerCase(), '*-*', this.selectedFilter.value.toLowerCase());

              if (cols[cols.length - 1].innerHTML.toLowerCase().replace(/&amp;/g, '&').indexOf(this.selectedFilters.value.toLowerCase().replace(/&amp;/g, '&')) >= 0) {
                newArrList.push(rows[i]);
              }
            }

          }
        }
      }
    }

    console.log('newarrlist', newArrList, this.selectedFilters);

    let filteredHTML = '';

    if (this.selectedFilters != null) {
      if (this.selectedFilters.selected) {
        filteredHTML += '<small>Filter (included parameters): ' + this.selectedFilters.value.charAt(0).toUpperCase() + this.selectedFilters.value.slice(1) + '</small>';
      } else {

        let params = "";
        for (var i = 0; i < this.selectedFilters.length; i++) {

          params += this.selectedFilters[i].value.charAt(0).toUpperCase() + this.selectedFilters[i].value.slice(1);
          if (i < (this.selectedFilters.length - 1)) {
            params += ',';
          }

        }

        filteredHTML += '<small>Filter (excluded parameters): ' + params + '</small>';
      }
    }

    //console.log('newArrList', newArrList);

    filteredHTML += '<br /><br /><div class="table-wrapper"><table>';
    for (var i = 0; i < newArrList.length; i++) {
      //console.log('htmlrender', (newArrList[i] as HTMLTableRowElement).outerHTML);
      filteredHTML += (newArrList[i] as HTMLTableRowElement).outerHTML;
    }
    filteredHTML += '</table></div>';
    // console.log('filteredHTML', filteredHTML);
    return filteredHTML;
  }

  getFilteredStringSummary = () => {

    console.log('selectedfilter', this.selectedFilters);

    var tempDiv = document.createElement('div');
    tempDiv.id = "div-filter-content";
    tempDiv.innerHTML = this.htmlDataSummary;

    const newArrList: Array<HTMLTableRowElement> = [];

    //console.log('tempDiv', this.htmlDataCompliances);

    const rows = tempDiv.querySelectorAll('tr');
    for (var i = 0; i < rows.length; i++) {
      let cols = rows[i].querySelectorAll('td');
      if (cols.length === 0) {
        cols = rows[i].querySelectorAll('th');
      }
      if (i === 0) {
        newArrList.push(rows[i]);
      } else {

        if (cols.length > 0) {
          if (this.selectedFilters == null) {
            newArrList.push(rows[i]);
          } else {

            if (!this.selectedFilters.selected) {

              var found = false;

              for (var j = 0; j < this.selectedFilters.length; j++) {
                if (cols[cols.length - 2].innerHTML.toLowerCase().replace(/&amp;/g, '&').indexOf(this.selectedFilters[j].value.toLowerCase().replace(/&amp;/g, '&')) >= 0) {
                  found = true;
                }
              }

              if (!found) {
                newArrList.push(rows[i]);
              }

            } else {

              console.log('selected filter', this.selectedFilters, cols[cols.length - 1].innerHTML.toLowerCase(), '*-*', this.selectedFilters.value.toLowerCase());

              if (cols[cols.length - 2].innerHTML.toLowerCase().replace(/&amp;/g, '&').indexOf(this.selectedFilters.value.toLowerCase().replace(/&amp;/g, '&')) >= 0) {
                newArrList.push(rows[i]);
              }
            }

          }
        }
      }
    }

    console.log('newarrlist', newArrList);

    let filteredHTML = '';

    if (this.selectedFilters != null) {
      if (this.selectedFilters.selected) {
        filteredHTML += '<small>Filter (included parameters): ' + this.selectedFilters.value.charAt(0).toUpperCase() + this.selectedFilters.value.slice(1) + '</small>';
      } else {

        let params = "";
        for (var i = 0; i < this.selectedFilters.length; i++) {

          params += this.selectedFilters[i].value.charAt(0).toUpperCase() + this.selectedFilters[i].value.slice(1);
          if (i < (this.selectedFilters.length - 1)) {
            params += ',';
          }

        }

        filteredHTML += '<small>Filter (excluded parameters): ' + params + '</small>';
      }
    }

    //console.log('newArrList', newArrList);

    filteredHTML += '<br /><br /><div class="table-wrapper"><table class="w-100">';
    for (var i = 0; i < newArrList.length; i++) {
      let tdClass = (i % 2 == 0) ? "td-even" : "td-odd";
      console.log('tdClass', tdClass, i)
      filteredHTML += (newArrList[i] as HTMLTableRowElement).outerHTML.replace(/td-odd/g, tdClass).replace(/td-even/g, tdClass);
    }
    filteredHTML += '</table></div>';
    return filteredHTML;
  }

  formatLabel = (str: string, maxwidth: number) => {
    const sections: any = [];
    var words = str.split(" ");
    var temp = "";

    words.forEach(function (item, index) {
      if (temp.length > 0) {
        var concat = temp + ' ' + item;

        if (concat.length > maxwidth) {
          sections.push(temp);
          temp = "";
        }
        else {
          if (index == (words.length - 1)) {
            sections.push(concat);
            return;
          }
          else {
            temp = concat;
            return;
          }
        }
      }

      if (index == (words.length - 1)) {
        sections.push(item);
        return;
      }

      if (item.length < maxwidth) {
        temp = item;
      }
      else {
        sections.push(item);
      }

    });

    return sections;
  }

  renderChart4 = (ctx: any, type: any, data: any, title: string, flagStats: boolean = false) => {

    if (this.chart4 != null) {
      (this.chart4 as Chart).destroy();
    }

    this.chart4 = new Chart(ctx, {
      type: type,
      data: data,
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        animation: {
          duration: 0,
          onComplete: () => {

            if (this.chart4 != null && this.chart4.ctx != null) {

              if (type == 'bar') {

                this.chart4.ctx.font = "bold 9pt 'Avenir'";
                this.chart4.ctx.fillStyle = '#333';
                this.chart4.ctx.textBaseline = "middle";
                this.chart4.ctx.textAlign = "center";
                console.log('chart 4 data', this.chart4.data.datasets);
                for (var i = 0; i < this.chart4.data.datasets.length; i++) {

                  const dataset = this.chart4.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      if ((this.chart4.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                        this.chart4.ctx.fillStyle = '#fff';
                      } else {
                        this.chart4.ctx.fillStyle = '#333';
                      }

                      let val = 0
                      if (i > 0) {
                        let tempI = 0
                        while (tempI < i) {
                          if (parseInt(this.chart4.data.datasets[tempI].data[j]) > 0) {
                            val = val == 0 ? 1 : 0;
                          }
                          tempI++;
                        }
                      }
                      if (j % 2 == val) {
                        this.chart4.ctx.fillText(dataset.data[j], this.chart4.getDatasetMeta(i).data[j].x - 5, this.chart4.getDatasetMeta(i).data[j].y - 15);
                      } else {
                        this.chart4.ctx.fillText(dataset.data[j], this.chart4.getDatasetMeta(i).data[j].x - 5, this.chart4.getDatasetMeta(i).data[j].y + 15);
                      }
                    }

                  }

                }

              } else {

                //console.log('onanimation complete', this.chart4, this.chart4.data);
                for (var i = 0; i < this.chart4.data.datasets.length; i++) {

                  const dataset = this.chart4.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      //console.log(this.chart4.getDatasetMeta(i));
                      //console.log(i + "," + j, this.chart4.getDatasetMeta(i).data[j]);
                      // var total = this.chart4.getDatasetMeta(i).total;
                      //console.log('total', total);
                      var mid_radius = this.chart4.getDatasetMeta(i).data[j].innerRadius + (this.chart4.getDatasetMeta(i).data[j].outerRadius - this.chart4.getDatasetMeta(i).data[j].innerRadius) / 2;
                      //console.log('mid_radius', mid_radius);
                      var start_angle = this.chart4.getDatasetMeta(i).data[j].startAngle;
                      //console.log('start_angle', start_angle);
                      var end_angle = this.chart4.getDatasetMeta(i).data[j].endAngle;
                      //console.log('end_angle', end_angle);
                      var mid_angle = start_angle + (end_angle - start_angle) / 2;
                      //console.log('mid_angle', mid_angle);

                      var x = mid_radius * Math.cos(mid_angle);
                      var y = mid_radius * Math.sin(mid_angle);

                      this.chart4.ctx.fillStyle = '#fff';
                      if (i == 3) { // Darker text color for lighter background
                        this.chart4.ctx.fillStyle = '#444';
                      }
                      // var percent = String(Math.round(dataset.data[j]/total*100)) + "%";
                      // var str = "";
                      // for(var k = 0; k <= dataset.data[j].length; k++) {
                      //   str += '█';
                      // }
                      //console.log('outputting bg', str);
                      this.chart4.ctx.fillStyle = '#333';
                      //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y);
                      //const match = /(?<value>\d+\.?\d*)/;
                      let fillText = '';
                      if ((this.chart4.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) {
                        this.chart4.ctx.font = "bold 20pt 'Avenir'";
                        fillText = dataset.data[j] + '✓';
                      } else {
                        this.chart4.ctx.font = "bold 15pt 'Avenir'";
                        fillText = dataset.data[j];
                      }
                      this.chart4.ctx.fillStyle = '#111';
                      this.chart4.ctx.textBaseline = "middle";
                      this.chart4.ctx.textAlign = "center";

                      //console.log('comparing labels', (this.chart4.data.labels[j] + "").toLowerCase().replace(/ /g, "-"), j, this.graphParam, this.chart4.getDatasetMeta(i).data[j]);
                      this.chart4.ctx.fillText(fillText, this.chart4.getDatasetMeta(i).data[j].x + x, this.chart4.getDatasetMeta(i).data[j].y + y);

                    }

                  }
                }

              }


            }
            if (this.chart4 != null && this.chart4.ctx != null) {
              this.chart4Base64 = (this.chart4 as Chart).toBase64Image()
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: false,
            },
            stacked: true,
          },
          y: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              font: {
                size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40,
              },
              callback: (val: any, _index: any) => {
                // Hide every 2nd tick label
                let value = data.labels[val];
                //console.log('callback', this.graphParam);
                if (this.graphParam.length > 0) {
                  // if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                  // } else {
                  //   value = "";
                  // }
                } else {
                  if (this.isSelectedLegend(val)) {
                    return "";
                  }
                }
                return value;
              }
            },
            stacked: true,
          }
        },
        barPercentage: 0.8,
        barThickness: 10,
        categoryPercentage: 0.5,
        plugins: {
          legend: {
            display: true,
            position: "bottom",
            align: "center",
            labels: {
              font: {
                size: 10,
              },
              boxWidth: 10,
              boxHeight: 10,
            },
            onClick: () => { }
          },
          title: {
            display: true,
            text: title,
            font: {
              size: 16,
            }
          },
          exportBackground: {
            color: '#ffffff'
          }
        },
        onClick: (_event: any = {}, array: any) => {

          // if(array == null) return;
          // if(array[0] == null) return;
          // const barIndex = array[0].index;
          // this.clickOnBar(false, 2, barIndex)
          // this.clickOnPie(true, barIndex)

          if (array == null) return;
          if (array[0] == null) return;
          const pieIndex = array[0].index;
          if (!flagStats) {
            this.clickOnPie(false, pieIndex)
          }
          if (this.chart2 != null && this.chart4 != null) {
            if (flagStats) {
              let selectedLabel = data.labels[array[0].index]
              if (Array.isArray(selectedLabel)) {
                selectedLabel = selectedLabel.join(' ')
              }
              let selectedFilter = data.datasets[array[0].datasetIndex].label.toLowerCase().replace(/ /g, '-')
              console.log('ClickedOnBar', selectedLabel, selectedFilter, this.statisticsMeta);
              for (let reporterStr of this.statisticsMeta.reporter) {
                let reporterName = reporterStr.split(';')[0]
                let reporterId = reporterStr.split(';')[1]
                if (reporterName == selectedLabel) {
                  this.renderStatisticsDetails('reporter', reporterId, reporterName, selectedFilter, true)
                  break;
                }
              }
            } else {
              this.clickOnBar(true, 2, array[0].index);
            }
          }

        },
      },

    });

    //console.log('canvas parent node', this.chart4.canvas.parentNode);
    this.chart4.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px';
    // this.chart4.canvas.parentNode.style.height = '100vh';

  }

  renderChart3 = (ctx: any, type: any, data: any, title: string, flagStats: boolean = false) => {

    if (this.chart3 != null) {
      (this.chart3 as Chart).destroy();
    }

    this.chart3 = new Chart(ctx, {
      type: type,
      data: data,
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        animation: {
          duration: 0,
          onComplete: () => {

            if (this.chart3 != null && this.chart3.ctx != null) {

              if (type == 'bar') {

                this.chart3.ctx.font = "bold 9pt 'Avenir'";
                this.chart3.ctx.fillStyle = '#333';
                this.chart3.ctx.textBaseline = "middle";
                this.chart3.ctx.textAlign = "center";

                for (var i = 0; i < this.chart3.data.datasets.length; i++) {

                  const dataset = this.chart3.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      if ((this.chart3.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                        this.chart3.ctx.fillStyle = '#fff';
                      } else {
                        this.chart3.ctx.fillStyle = '#333';
                      }

                      let val = 0
                      if (i > 0) {
                        let tempI = 0
                        while (tempI < i) {
                          if (parseInt(this.chart3.data.datasets[tempI].data[j]) > 0) {
                            val = val == 0 ? 1 : 0;
                          }
                          tempI++;
                        }
                      }

                      if (j % 2 == val) {
                        this.chart3.ctx.fillText(dataset.data[j], this.chart3.getDatasetMeta(i).data[j].x - 5, this.chart3.getDatasetMeta(i).data[j].y - 15);
                      } else {
                        this.chart3.ctx.fillText(dataset.data[j], this.chart3.getDatasetMeta(i).data[j].x - 5, this.chart3.getDatasetMeta(i).data[j].y + 15);
                      }
                    }

                  }

                }

              } else {

                //console.log('onanimation complete', this.chart3, this.chart3.data);
                for (var i = 0; i < this.chart3.data.datasets.length; i++) {

                  const dataset = this.chart3.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      //console.log(this.chart3.getDatasetMeta(i));
                      //console.log(i + "," + j, this.chart3.getDatasetMeta(i).data[j]);
                      // var total = this.chart3.getDatasetMeta(i).total;
                      //console.log('total', total);
                      var mid_radius = this.chart3.getDatasetMeta(i).data[j].innerRadius + (this.chart3.getDatasetMeta(i).data[j].outerRadius - this.chart3.getDatasetMeta(i).data[j].innerRadius) / 2;
                      //console.log('mid_radius', mid_radius);
                      var start_angle = this.chart3.getDatasetMeta(i).data[j].startAngle;
                      //console.log('start_angle', start_angle);
                      var end_angle = this.chart3.getDatasetMeta(i).data[j].endAngle;
                      //console.log('end_angle', end_angle);
                      var mid_angle = start_angle + (end_angle - start_angle) / 2;
                      //console.log('mid_angle', mid_angle);

                      var x = mid_radius * Math.cos(mid_angle);
                      var y = mid_radius * Math.sin(mid_angle);

                      this.chart3.ctx.fillStyle = '#fff';
                      if (i == 3) { // Darker text color for lighter background
                        this.chart3.ctx.fillStyle = '#444';
                      }
                      // var percent = String(Math.round(dataset.data[j]/total*100)) + "%";
                      // var str = "";
                      // for(var k = 0; k <= dataset.data[j].length; k++) {
                      //   str += '█';
                      // }
                      //console.log('outputting bg', str);
                      this.chart3.ctx.fillStyle = '#333';
                      //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y);
                      //const match = /(?<value>\d+\.?\d*)/;
                      let fillText = '';
                      if ((this.chart3.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) {
                        this.chart3.ctx.font = "bold 20pt 'Avenir'";
                        fillText = dataset.data[j] + '✓';
                      } else {
                        this.chart3.ctx.font = "bold 15pt 'Avenir'";
                        fillText = dataset.data[j];
                      }
                      this.chart3.ctx.fillStyle = '#111';
                      this.chart3.ctx.textBaseline = "middle";
                      this.chart3.ctx.textAlign = "center";

                      //console.log('comparing labels', (this.chart3.data.labels[j] + "").toLowerCase().replace(/ /g, "-"), j, this.graphParam, this.chart3.getDatasetMeta(i).data[j]);
                      this.chart3.ctx.fillText(fillText, this.chart3.getDatasetMeta(i).data[j].x + x, this.chart3.getDatasetMeta(i).data[j].y + y);

                    }

                  }
                }

              }


            }
            if (this.chart3 != null && this.chart3.ctx != null) {
              this.chart3Base64 = (this.chart3 as Chart).toBase64Image();
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: false,
            },
            stacked: true,
          },
          y: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              font: {
                size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40,
              },
              callback: (val: any, _index: any) => {
                // Hide every 2nd tick label
                let value = data.labels[val];
                //console.log('callback', this.graphParam);
                if (this.graphParam.length > 0) {
                  // if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                  // } else {
                  //   value = "";
                  // }
                } else {
                  if (this.isSelectedLegend(val)) {
                    return "";
                  }
                }
                return value;
              }
            },
            stacked: true,
          }
        },
        barPercentage: 0.8,
        barThickness: 10,
        categoryPercentage: 0.5,
        plugins: {
          legend: {
            display: true,
            position: "bottom",
            align: "center",
            labels: {
              font: {
                size: 10,
              },
              boxWidth: 10,
              boxHeight: 10,
            },
            onClick: () => { }
          },
          title: {
            display: true,
            text: title,
            font: {
              size: 16,
            }
          },
          exportBackground: {
            color: '#ffffff'
          }
        },
        onClick: (_event: any = {}, array: any) => {

          // if(array == null) return;
          // if(array[0] == null) return;
          // const barIndex = array[0].index;
          // this.clickOnBar(false, 2, barIndex)
          // this.clickOnPie(true, barIndex)

          if (array == null) return;
          if (array[0] == null) return;
          const pieIndex = array[0].index;
          if (!flagStats) {
            this.clickOnPie(false, pieIndex)
          }

          if (this.chart2 != null && this.chart3 != null) {
            if (flagStats) {
              let selectedLabel = data.labels[array[0].index]
              if (Array.isArray(selectedLabel)) {
                selectedLabel = selectedLabel.join(' ')
              }
              let selectedFilter = data.datasets[array[0].datasetIndex].label.toLowerCase().replace(/ /g, '-')
              console.log('ClickedOnBar2', selectedLabel, selectedFilter, this.statisticsMeta);
              for (let locationStr of this.statisticsMeta.location) {
                let locationName = locationStr.split(';')[0].replace(/\([^)]*\)/g, "")
                let locationId = locationStr.split(';')[1]
                if (locationName == selectedLabel) {
                  this.renderStatisticsDetails('location', locationId, locationName, selectedFilter, true)
                  break;
                }
              }
            } else {
              //console.log('pie bar trigger 2', this.graphParam, array[0].index);
              this.clickOnBar(true, 2, array[0].index);
            }
          }

        },
      },

    });

    //console.log('canvas parent node', this.chart3.canvas.parentNode);
    this.chart3.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px';
    // this.chart3.canvas.parentNode.style.height = '100vh';

  }

  renderChart2 = (ctx: any, type: any, data: any, title: string, flagStats: boolean = false) => {

    if (this.chart2 != null) {
      (this.chart2 as Chart).destroy();
    }
    console.log('chart2 context', ctx);
    this.chart2 = new Chart(ctx, {
      type: type,
      data: data,
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        animation: {
          duration: 0,
          onComplete: () => {

            if (this.chart2 != null && this.chart2.ctx != null) {

              if (type == 'bar') {

                this.chart2.ctx.font = "bold 9pt 'Avenir'";
                this.chart2.ctx.fillStyle = '#333';
                this.chart2.ctx.textBaseline = "middle";
                this.chart2.ctx.textAlign = "left";
                // let count = 0
                // let arrPos = [[],[]]
                for (var i = 0; i < this.chart2.data.datasets.length; i++) {

                  const dataset = this.chart2.data.datasets[i];

                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      if ((this.chart2.data.labels[j].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                        this.chart2.ctx.fillStyle = '#fff';
                      } else {
                        this.chart2.ctx.fillStyle = '#333';
                      }

                      let val = 0
                      if (i > 0) {
                        let tempI = 0
                        while (tempI < i) {
                          if (parseInt(this.chart2.data.datasets[tempI].data[j]) > 0) {
                            val = val == 0 ? 1 : 0;
                          }
                          tempI++;
                        }
                      }

                      if (j % 2 == val) {
                        this.chart2.ctx.fillText(dataset.data[j], this.chart2.getDatasetMeta(i).data[j].x - 5, this.chart2.getDatasetMeta(i).data[j].y - 15);
                      } else {
                        this.chart2.ctx.fillText(dataset.data[j], this.chart2.getDatasetMeta(i).data[j].x - 5, this.chart2.getDatasetMeta(i).data[j].y + 15);
                      }

                    }

                  }
                  // count ++

                }

              } else {

                for (var i = 0; i < this.chart2.data.datasets.length; i++) {

                  const dataset = this.chart2.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      var mid_radius = this.chart2.getDatasetMeta(i).data[j].innerRadius + (this.chart2.getDatasetMeta(i).data[j].outerRadius - this.chart2.getDatasetMeta(i).data[j].innerRadius) / 2;
                      var start_angle = this.chart2.getDatasetMeta(i).data[j].startAngle;
                      var end_angle = this.chart2.getDatasetMeta(i).data[j].endAngle;
                      var mid_angle = start_angle + (end_angle - start_angle) / 2;

                      var x = mid_radius * Math.cos(mid_angle);
                      var y = mid_radius * Math.sin(mid_angle);

                      this.chart2.ctx.fillStyle = '#fff';
                      if (i == 3) { // Darker text color for lighter background
                        this.chart2.ctx.fillStyle = '#444';
                      }
                      // var percent = String(Math.round(dataset.data[j]/total*100)) + "%";
                      // var str;
                      // str = "";
                      // for(var k = 0; k <= dataset.data[j].length; k++) {
                      //   str += '█';
                      // }
                      this.chart2.ctx.fillStyle = '#333';
                      //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y);
                      //const match = /(?<value>\d+\.?\d*)/;
                      let fillText = '';
                      if ((this.chart2.data.labels[j] + "").toLowerCase().replace(/ /g, "-") == this.graphParam) {
                        this.chart2.ctx.font = "bold 20pt 'Avenir'";
                        fillText = dataset.data[j] + '✓';
                      } else {
                        this.chart2.ctx.font = "bold 15pt 'Avenir'";
                        fillText = dataset.data[j];
                      }
                      this.chart2.ctx.fillStyle = '#111';
                      this.chart2.ctx.textBaseline = "middle";
                      this.chart2.ctx.textAlign = "center";
                      this.chart2.ctx.fillText(fillText, this.chart2.getDatasetMeta(i).data[j].x + x, this.chart2.getDatasetMeta(i).data[j].y + y);

                    }

                  }
                }

              }

            }
            if (this.chart2 != null && this.chart2.ctx != null) {
              this.chart2Base64 = (this.chart2 as Chart).toBase64Image();
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: false,
            },
            stacked: true,
          },
          y: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: true,
              autoSkip: false,
              font: {
                size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40,
              },
              callback: (val: any, _index: any) => {
                // Hide every 2nd tick label
                let value = data.labels[val];
                console.log('callbackTick', this.graphParam, value);
                if (this.graphParam.length > 0) {
                  // if ((data.labels[val].join(" ") + "").toLowerCase().trim() == this.graphParam) {
                  // } else {
                  //   value = "";
                  // }
                } else {
                  if (this.isSelectedLegend(val)) {
                    return "";
                  }
                }
                return value;
              }
            },
            stacked: true,
            offset: true,
          }
        },
        // barPercentage: 0.8,
        barThickness: 10,
        // categoryPercentage: 0.5,
        plugins: {

          legend: {
            display: true,
            position: "bottom",
            align: "center",
            labels: {
              font: {
                size: 10,
              },
              boxWidth: 10,
              boxHeight: 10,
            },
            onClick: () => { }
          },
          title: {
            display: true,
            text: title,
            font: {
              size: 16,
            }
          },
          exportBackground: {
            color: '#ffffff'
          }
        },
        onClick: (_event: any = {}, array: any) => {

          // if(array == null) return;
          // if(array[0] == null) return;
          // const barIndex = array[0].index;
          // this.clickOnBar(false, 2, barIndex)
          // this.clickOnPie(true, barIndex)

          if (array == null) return;
          if (array[0] == null) return;
          const pieIndex = array[0].index;
          // const tempGraphParam = this.graphParam
          //console.log('pie bar trigger 0', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2));
          if (!flagStats) {
            this.clickOnPie(false, pieIndex)
          }
          //console.log('pie bar trigger 1', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2));
          if (this.chart2 != null && this.chart3 != null) {
            if (flagStats) {
              let selectedLabel = data.labels[array[0].index]
              if (Array.isArray(selectedLabel)) {
                selectedLabel = selectedLabel.join(' ')
              }
              let selectedFilter = data.datasets[array[0].datasetIndex].label.toLowerCase().replace(/ /g, '-')
              console.log('ClickedOnBar2', selectedLabel, selectedFilter, this.statisticsMeta);
              for (let functionStr of this.statisticsMeta.function) {
                let functionName = functionStr.split(';')[0].replace(/\([^)]*\)/g, "")
                let functionId = functionStr.split(';')[1]
                if (functionName == selectedLabel) {
                  this.renderStatisticsDetails('function', functionId, functionName, selectedFilter, true)
                  break;
                }
              }
            } else {
              //console.log('pie bar trigger 2', this.graphParam, array[0].index);
              this.clickOnBar(true, 2, array[0].index);
            }
          }

        },
      },

    });

    //console.log('canvas parent node', this.chart2.canvas.parentNode);
    this.chart2.canvas.parentNode.style.height = (parseInt(data.labels.length) * 90 + 40) + 'px';
    // this.chart2.canvas.parentNode.style.height = '100vh';
    console.log('this.chart2 rendered', (this.chart2 as Chart));
  }

  renderChart = (ctx: any, type: any, data: any, title: string | string[], flagFullWidth: boolean = true, flagInModal: boolean = false, flagStats: boolean = false) => {

    //console.log('rendering chart', this.chart);

    if (this.chart != null) {
      //console.log('destroying chart', this.chart);
      (this.chart as Chart).destroy();
      this.chart = null;
    }

    this.chart = new Chart(ctx, {
      type: type,
      data: data,
      options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,
        cutout: '95%',
        animation: {
          duration: 0,
          onComplete: () => {

            if (this.chart != null) {

              if (type == 'bar') {

                // this.chart.ctx.font = "bold 10pt Courier";
                this.chart.ctx.font = "bold 9pt 'Avenir'";
                this.chart.ctx.fillStyle = '#333';
                this.chart.ctx.textBaseline = "middle";
                this.chart.ctx.textAlign = "center";

                for (var i = 0; i < this.chart.data.datasets.length; i++) {

                  const dataset = this.chart.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {
                      //console.log('points', this.chart.getDatasetMeta(i).data[j]);
                      this.chart.ctx.fillText(dataset.data[j], this.chart.getDatasetMeta(i).data[j].x + 15, this.chart.getDatasetMeta(i).data[j].y);
                    }

                  }

                }

              } else {

                //console.log('onanimation complete', this.chart, this.chart.data, this.graphParam);
                //console.log('onanimation complete', this.graphParam);

                var rendered = false;

                for (var i = 0; i < this.chart.data.datasets.length; i++) {

                  const dataset = this.chart.data.datasets[i];
                  for (var j = 0; j < dataset.data.length; j++) {

                    if (parseInt(dataset.data[j]) > 0) {

                      rendered = true;
                      //console.log(this.chart.getDatasetMeta(i));
                      //console.log(i + "," + j, this.chart.getDatasetMeta(i).data[j]);
                      // var total = this.chart.getDatasetMeta(i).total;
                      //console.log('total', total);
                      var mid_radius = (this.chart.getDatasetMeta(i).data[j].outerRadius - 25);
                      if (j % 2 == 0) {
                        mid_radius = (this.chart.getDatasetMeta(i).data[j].outerRadius + 10);
                      }
                      // var mid_radius = this.chart.getDatasetMeta(i).data[j].innerRadius + ((this.chart.getDatasetMeta(i).data[j].outerRadius - this.chart.getDatasetMeta(i).data[j].innerRadius) * 2) / 3;
                      //console.log('mid_radius', mid_radius);
                      var start_angle = this.chart.getDatasetMeta(i).data[j].startAngle;
                      //console.log('start_angle', start_angle);
                      var end_angle = this.chart.getDatasetMeta(i).data[j].endAngle;
                      //console.log('end_angle', end_angle);
                      var mid_angle = start_angle + (end_angle - start_angle) / 2;
                      //console.log('mid_angle', mid_angle);

                      var x = mid_radius * Math.cos(mid_angle);
                      var y = mid_radius * Math.sin(mid_angle);

                      this.chart.ctx.fillStyle = '#fff';
                      if (i == 3) { // Darker text color for lighter background
                        this.chart.ctx.fillStyle = '#444';
                      }
                      // var percent = String(Math.round(dataset.data[j]/total*100)) + "%";
                      // var str = "";
                      // for(var k = 0; k <= dataset.data[j].length; k++) {
                      //   str += '█';
                      // }
                      //console.log('outputting bg', str);
                      this.chart.ctx.fillStyle = '#333';
                      //this.chart.ctx.fillText(str, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y);
                      //const match = /(?<value>\d+\.?\d*)/;
                      let fillText = '';
                      let replaceText = ' ';
                      if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
                        replaceText = '-';
                      }
                      this.chart.ctx.fillStyle = '#111';
                      if ((this.chart.data.labels[j] + "").toLowerCase().replace(/ /g, replaceText) == this.graphParam) {
                        // this.chart.ctx.font = "bold 20pt 'Source Sans Pro'";
                        this.chart.ctx.font = "bold 20pt 'Avenir'";
                        if (this.isSelectedLegend(j)) {
                          fillText = '';
                        } else {
                          this.chart.ctx.fillStyle = '#111';
                          fillText = dataset.data[j] + '✓';
                        }

                      } else {
                        // this.chart.ctx.font = "bold 8pt 'Source Sans Pro'";
                        this.chart.ctx.font = "bold 9pt 'Avenir'";
                        if (this.isSelectedLegend(j)) {
                          fillText = '';
                        } else {
                          this.chart.ctx.fillStyle = '#333';
                          // this.chart.ctx.fillStyle = '#fff';
                          fillText = dataset.data[j];

                        }

                      }

                      this.chart.ctx.textBaseline = "middle";
                      this.chart.ctx.textAlign = "center";

                      this.chart.ctx.fillText(fillText, this.chart.getDatasetMeta(i).data[j].x + x, this.chart.getDatasetMeta(i).data[j].y + y);

                    }

                  }
                }

                if (!rendered) {
                  const { chartArea: { left, top, right, bottom }, ctx } = this.chart;
                  const centerX = (left + right) / 2;
                  const centerY = (top + bottom) / 2;
                  ctx.font = "15pt Arial";
                  ctx.fillStyle = '#666';
                  ctx.textAlign = 'center';
                  ctx.textBaseline = 'middle';
                  ctx.fillText('No data to display', centerX, centerY);
                }

              }

            }
            if (this.chart != null) {
              this.chartBase64 = (this.chart as Chart).toBase64Image();
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: false,
            },
            stacked: true,
          },
          y: {
            grid: {
              display: false,
              drawBorder: false
            },
            ticks: {
              display: type == 'bar' ? true : false,
              font: {
                size: window.innerWidth > window.innerHeight ? window.innerWidth / 170 : window.innerWidth / 40,
              }
            },
            stacked: true,
          }
        },
        barPercentage: 0.8,
        barThickness: 10,
        categoryPercentage: 0.5,
        plugins: {
          legend: {
            display: type !== "bar",
            position: "bottom",
            align: "center",
            labels: {
              font: {
                size: 10,
              },
              boxWidth: 10,
              boxHeight: 10,
              generateLabels: (chart: any) => chart.data.labels.map((l: any, i: any) => ({
                datasetIndex: i,
                index: i,
                text: l,
                fillStyle: chart.data.datasets[0].backgroundColor[i],
                strokeStyle: chart.data.datasets[0].backgroundColor[i],
                hidden: chart.getDatasetMeta(0).data[i].hidden
              }))
            },
            onClick: (_evt: any, legendItem: any, _legend: any) => {
              if (this.graphParam.length > 0) {
                this.clearSelectedGraphParam();
              }
              //
              //console.log('index clicked', legendItem.index, this.chart.legend.legendItems[legendItem.index]);
              if (flagStats) {
                this.processClickOnLegendStats(legendItem.index, legendItem)
              } else {
                this.processClickOnLegend(legendItem.index, legendItem);
              }
            }
          },
          title: {
            display: true,
            text: title,
            font: {
              size: Array.isArray(title) ? 14 : 16,
              lineHeight: 1.5
            },
            padding: { bottom: 20 }
          },
          exportBackground: {
            color: '#ffffff'
          }
        },
        onClick: (_event: any, array: any) => {
          console.log('chartclick', array[0], data.labels[array[0].index]);
          if (array == null) return;
          if (array[0] == null) return;
          const pieIndex = array[0].index;
          // const tempGraphParam = this.graphParam
          //console.log('pie bar trigger 0', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2));
          console.log('graphParam', this.graphParam, data.labels[array[0].index].toLowerCase().replace(/ /g, "-"))
          if (flagStats && this.graphParam != data.labels[array[0].index].toLowerCase().replace(/ /g, "-") && data.labels[array[0].index].toLowerCase().replace(/ /g, "-") != '') {
            console.log('filterStatus', data.labels[array[0].index].toLowerCase().replace(/ /g, "-"))
            this.renderStatisticsDetails('all', '', '', data.labels[array[0].index].toLowerCase().replace(/ /g, "-"));
          }
          if (flagStats) {
            this.clickOnPieStats(false, pieIndex);
          } else {
            this.clickOnPie(false, pieIndex)
          }
          //console.log('pie bar trigger 1', this.graphParam, array[0].index, JSON.stringify(this.barCharDataSet2));
          if (this.chart2 != null && this.chart3 != null && this.chart4 != null) {
            //console.log('pie bar trigger 2', this.graphParam, array[0].index);
            if (flagStats) {
              this.clickOnBarStats(true, 2, data.labels[array[0].index]);
            } else {
              this.clickOnBar(true, 2, array[0].index);
            }
          }

        }
      },
    });

    console.log('chartData', data);

    let chartHeight = '480px'
    if (flagFullWidth && flagInModal) {
      chartHeight = '100vh'
    }
    this.chart.canvas.parentNode.style.height = (type === 'bar') ? ((parseInt(data.labels.length) * 90 + 40) + 'px') : chartHeight;
    // if (type !== 'bar' && flagFullWidth) {
    //   this.chart.canvas.parentNode.style.width = '100vh'
    // }
    this.chart.canvas.parentNode.style.width = chartHeight

    // this.chart.canvas.parentNode.style.height = '100vh'
  }

  copy = (aObject: any) => {
    // Prevent undefined objects
    // if (!aObject) return aObject;

    let bObject: any = Array.isArray(aObject) ? [] : {};

    let value;
    for (const key in aObject) {

      // Prevent self-references to parent object
      // if (Object.is(aObject[key], aObject)) continue;

      value = aObject[key];

      bObject[key] = (typeof value === "object") ? this.copy(value) : value;
    }

    return bObject;
  }

  processGraphHide = (clickedValue: string, hide: boolean) => {
    //console.log('processGraphHide', clickedValue, hide, this.selectedFilter);

    let eventContainer = null;

    if (this.getCurrentTab() == this.TAB_STREAM) {
      eventContainer = (this._SfStreamContainer as HTMLDivElement);
    }

    if (this.getCurrentTab() == this.TAB_UPCOMING) {
      eventContainer = (this._SfUpcomingContainer as HTMLDivElement);
    }

    if (this.getCurrentTab() == this.TAB_THIS) {
      eventContainer = (this._SfThisContainer as HTMLDivElement);
    }

    if (this.getCurrentTab() == this.TAB_PAST) {
      eventContainer = (this._SfPastContainer as HTMLDivElement);
    }

    if (this.getCurrentTab() == this.TAB_CUSTOM) {
      eventContainer = (this._SfCustomContainer as HTMLDivElement);
    }

    const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf<HTMLElement>;
    const eventTitles = eventContainer!.querySelectorAll('.stream-events-event-title') as NodeListOf<HTMLElement>;
    const eventSubTitles = eventContainer!.querySelectorAll('.stream-events-event-subtitle') as NodeListOf<HTMLElement>;
    const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf<HTMLTableElement>;
    const graphparamnames1 = eventContainer!.querySelectorAll('.graphparamname1') as NodeListOf<HTMLTableCellElement>;
    const graphparamnames2 = eventContainer!.querySelectorAll('.graphparamname2') as NodeListOf<HTMLTableCellElement>;
    const graphparamnames3 = eventContainer!.querySelectorAll('.graphparamname3') as NodeListOf<HTMLTableCellElement>;
    const eventUserLabelsContainers = eventContainer!.querySelectorAll('.event-user-labels-container') as NodeListOf<HTMLDivElement>;
    const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement;
    const streamEventFilters = eventContainer!.querySelector('#stream-event-filter') as HTMLDivElement;
    const buttonListReporting = eventContainer!.querySelector('.button-list-reporting') as HTMLButtonElement;
    if (hide) {
      //this.graphParam = clickedValue;
      streamEventSummary.style.display = 'none';
      //console.log('selectedfilter', this.selectedFilter);
      if (this.selectedFilters == null) {
        this.selectedFilters = [];
      }
      this.selectedFilters.push({
        selected: false,
        value: clickedValue
      });

      var filterString = "";
      for (var j = 0; j < this.selectedFilters.length; j++) {
        filterString += this.selectedFilters[j].value;
        if (j < (this.selectedFilters.length - 1)) {
          filterString += ',';
        }
      }

      (streamEventFilters as HTMLDivElement).style.display = 'block';
      (streamEventFilters as HTMLDivElement).innerHTML = '<div part="badge-dashboard" class="mr-10 mb-10 no-shrink d-flex justify-between align-center"><div><span>Filtered by</span>&nbsp;&nbsp;<span id="graph-total" part="badge-filter-name">excluding ' + filterString + '</span></div><button id="button-filter-cancel" part="button-icon"><span class="material-symbols-outlined">close</span></button></div>';
      console.log('processGraphHide called');
      (streamEventFilters as HTMLDivElement).querySelector('#button-filter-cancel')?.addEventListener('click', () => {
        this.clearSelectedLegend();
        this.clearSelectedGraphParam();
      });

    } else {

      streamEventSummary.style.display = 'flex';
      this.selectedFilters = null;
      (streamEventFilters as HTMLDivElement).style.display = 'none';
      (streamEventFilters as HTMLDivElement).innerHTML = '';

    }

    //console.log('selectedfilter', this.selectedFilter);

    for (var i = 0; i < divs.length; i++) {

      if (!hide) {
        if (tables[i] != null) {
          (tables[i] as HTMLDivElement).style.display = 'block';
          (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'flex';
          //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block';
          (graphparamnames1[i] as HTMLDivElement).style.display = 'block';
          if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'block';
          if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'block';
          if (eventSubTitles[i] != null) {
            (eventSubTitles[i] as HTMLDivElement).style.display = 'flex';
          }
          buttonListReporting.style.display = "block";
        }
        (eventTitles[i] as HTMLDivElement).style.display = 'flex';
      } else {

        var found = false;

        if (this.selectedFilters != null) {
          for (var j = 0; j < this.selectedFilters.length; j++) {
            // if((graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&amp;', '&').indexOf(this.selectedFilter[j].value) >= 0) {
            if ((graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&amp;', '&').replace(/-/g, ' ') == this.selectedFilters[j].value.toLowerCase().replace('&amp;', '&').replace(/-/g, ' ')) {

              found = true;
              break;
            }
          }
        }

        if (found) {
          if (tables[i] != null) {
            (tables[i] as HTMLDivElement).style.display = 'none';
            (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'none';
            //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none';
            (graphparamnames1[i] as HTMLDivElement).style.display = 'none';
            if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'none';
            if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'none';
            if (eventSubTitles[i] != null) {
              (eventSubTitles[i] as HTMLDivElement).style.display = 'none';
            }
            buttonListReporting.style.display = 'none';
          }
          (eventTitles[i] as HTMLDivElement).style.display = 'none';
        }
      }

      let listReportingContainers = eventContainer!.querySelectorAll('.list-reporting-container') as NodeListOf<HTMLDivElement>
      for (let tempReportingContainer of listReportingContainers) {
        tempReportingContainer.style.display = 'none';
        tempReportingContainer.innerHTML = '';
      }
      let buttonListReportings = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
      for (let buttonListReporting of buttonListReportings) {
        buttonListReporting.setAttribute('part', 'button-list-reporting')
      }
      let streamEventTitles = eventContainer!.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
      for (let streamEventTitle of streamEventTitles) {
        streamEventTitle.removeAttribute('part')
      }
      // var found = false;

      // if(this.selectedFilter != null) {
      //   for(var j = 0; j < this.selectedFilter.length; j++) {
      //     if((graphparamnames[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&amp;', '&').indexOf(this.selectedFilter[j].value) >= 0) {
      //       found = true;
      //       break;
      //     }
      //   }
      // }


      // if(found) {
      //   if(hide) {
      //     (tables[i] as HTMLDivElement).style.display = 'none';
      //     //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none';
      //     (graphparamnames[i] as HTMLDivElement).style.display = 'none';
      //     (eventTitles[i] as HTMLDivElement).style.display = 'none';  
      //   } else {
      //     (tables[i] as HTMLDivElement).style.display = 'block';
      //     //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block';
      //     (graphparamnames[i] as HTMLDivElement).style.display = 'block';
      //     (eventTitles[i] as HTMLDivElement).style.display = 'flex';

      //   }
      // } 

    }

  }

  processGraphFilter = (clickedValue: string, detailsListContainer?: HTMLDivElement, flagStats: boolean = false) => {

    if (flagStats) {
      return;
    }
    let eventContainer = detailsListContainer;
    if (eventContainer == null) {
      console.log('processGraphFilter called', clickedValue, detailsListContainer);
      if (this.getCurrentTab() == this.TAB_STREAM) {
        eventContainer = (this._SfStreamContainer as HTMLDivElement);
      }

      // if(this.getCurrentTab() == this.TAB_UPCOMING) {
      //   eventContainer = (this._SfUpcomingContainer as HTMLDivElement);
      // }

      if (this.getCurrentTab() == this.TAB_THIS) {
        eventContainer = (this._SfThisContainer as HTMLDivElement);
      }

      // if(this.getCurrentTab() == this.TAB_PAST) {
      //   eventContainer = (this._SfPastContainer as HTMLDivElement);
      // }

      if (this.getCurrentTab() == this.TAB_CUSTOM) {
        eventContainer = (this._SfCustomContainer as HTMLDivElement);
      }

      if (this.getCurrentTab() == this.TAB_FIND) {
        eventContainer = (this._SfFindContainer as HTMLDivElement);
      }
    }
    if (eventContainer == null) {
      console.log('processGraphFilter called 1', eventContainer)
      return;
    }
    this.graphFilter = clickedValue
    this.selectedItemIds = [];

    const buttonSelect = eventContainer!.querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;

    // for(let checkSelect of buttonSelect){
    //   checkSelect.checked = false
    // }

    const divs = eventContainer!.querySelectorAll('.stream-events-container') as NodeListOf<HTMLElement>;
    const eventTitles = eventContainer!.querySelectorAll('.stream-events-event-title') as NodeListOf<HTMLElement>;
    const eventSubTitles = eventContainer!.querySelectorAll('.stream-events-event-subtitle') as NodeListOf<HTMLElement>;
    const tables = eventContainer!.querySelectorAll('.stream-events-container-table') as NodeListOf<HTMLTableElement>;
    const graphparamnames1 = eventContainer!.querySelectorAll('.graphparamname1') as NodeListOf<HTMLTableCellElement>;
    const graphparamnames2 = eventContainer!.querySelectorAll('.graphparamname2') as NodeListOf<HTMLTableCellElement>;
    const graphparamnames3 = eventContainer!.querySelectorAll('.graphparamname3') as NodeListOf<HTMLTableCellElement>;
    const eventUserLabelsContainers = eventContainer!.querySelectorAll('.event-user-labels-container') as NodeListOf<HTMLDivElement>;
    const streamEventSummary = eventContainer!.querySelector('#stream-event-summary') as HTMLDivElement;
    const streamEventFilters = eventContainer!.querySelector('#stream-event-filter') as HTMLDivElement;
    const buttonListReporting = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>;

    if (streamEventSummary == null) {
      return;
    }
    console.log('recentlyReported', this.recentlyReported);
    console.log('graphParam', this.graphParam, clickedValue)
    if (this.graphParam == clickedValue) {

      this.graphParam = "";
      streamEventSummary.style.display = 'flex';
      this.selectedFilters = null;
      (streamEventFilters as HTMLDivElement).style.display = 'none';
      (streamEventFilters as HTMLDivElement).innerHTML = '';

    } else {

      this.graphParam = clickedValue;
      streamEventSummary.style.display = 'none';
      this.selectedFilters = {
        selected: true,
        value: clickedValue
      };
      console.log('setting selected filter', this.selectedFilters);
      (streamEventFilters as HTMLDivElement).style.display = 'block';
      (streamEventFilters as HTMLDivElement).innerHTML = '<div part="badge-dashboard" class="d-flex align-center justify-between mr-10 mb-10 no-shrink"><div><span>Filtered by</span>&nbsp;&nbsp;<span id="graph-total" part="badge-filter-name">' + clickedValue + '</span></div>' + (detailsListContainer == null ? '<button id="button-filter-cancel" part="button-icon"><span class="material-symbols-outlined">close</span></button>' : '') + '</div>';
      (streamEventFilters as HTMLDivElement).querySelector('#button-filter-cancel')?.addEventListener('click', () => {
        this.graphFilter = "";
        this.clearSelectedGraphParam();
      });
      setTimeout(() => {
        this.recentlyReported = {}
      }, 10000);
    }


    for (var i = 0; i < divs.length; i++) {

      // console.log('processGraphFilter', graphparamnames1[i], (graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&amp;', '&').replace(/-/g, ' '), this.graphParam.toLowerCase().replace('&amp;', '&').replace(/-/g, ' '));
      if (graphparamnames1[i] == null) {
        continue;
      }
      let graphparamname1Arr = (graphparamnames1[i] as HTMLDivElement).innerHTML.toLowerCase().replace('&amp;', '&').replace(/-/g, ' ').split(' • ');
      let filterFound = false;
      for (let tempFilterStr of graphparamname1Arr) {
        // console.log('graphparamname1Arr', tempFilterStr, this.graphParam.toLowerCase().replace('&amp;', '&').replace(/-/g, ' '), tempFilterStr == this.graphParam.toLowerCase().replace('&amp;', '&').replace(/-/g, ' '));
        if (tempFilterStr == this.graphParam.toLowerCase().replace('&amp;', '&').replace(/-/g, ' ') || this.graphParam.toLowerCase().replace('&amp;', '&').replace(/-/g, ' ') == "") {
          filterFound = true;
          break;
        }
      }
      if (buttonSelect[i] != null) {
        buttonSelect[i].checked = false
        let selectid = buttonSelect[i].id
        let selectidArr = selectid.split('-')
        let selectMmdd = selectidArr[2] + '/' + selectidArr[3]
        let selectEntityid = selectidArr[7].replace(/_/g, '-')
        let selectLocationid = selectidArr[8].replace(/_/g, '-')
        let selectEventid = selectidArr[9].replace(/_/g, '-')
        if (this.recentlyReported[selectMmdd] != null) {
          for (let recentlyReportedEvent of this.recentlyReported[selectMmdd]) {
            if (recentlyReportedEvent.id == selectEventid && recentlyReportedEvent.locationid == selectLocationid && recentlyReportedEvent.entityid == selectEntityid) {
              filterFound = true;
              break;
            }
          }
        }
      }

      if (filterFound) {
        if (tables[i] != null) {
          (tables[i] as HTMLDivElement).style.display = 'block';
          (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'flex';
          //(hiddenFilternames[i] as HTMLDivElement).style.display = 'block';
          (graphparamnames1[i] as HTMLDivElement).style.display = 'block';
          if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'block';
          if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'block';
          if (eventSubTitles[i] != null) {
            (eventSubTitles[i] as HTMLDivElement).style.display = 'flex';
          }
          if (buttonListReporting[i] != null && buttonListReporting[i].id.indexOf('-reportedlocations') < 0) {
            buttonListReporting[i].style.display = 'block';
          }
        }
        if (buttonSelect[i] != null && buttonSelect[i].id.indexOf('-bulk') < 0 && buttonSelect[i].id.indexOf('-reportformat') < 0 && buttonSelect[i].id.indexOf('-reportedlocations') < 0) buttonSelect[i].style.display = "flex"
        if (eventTitles[i] != null) (eventTitles[i]).style.display = 'flex';
        divs[i].style.display = 'block'
      } else {
        if (tables[i] != null) {
          (tables[i] as HTMLDivElement).style.display = 'none';
          (eventUserLabelsContainers[i] as HTMLDivElement).style.display = 'none';
          //(hiddenFilternames[i] as HTMLDivElement).style.display = 'none';
          (graphparamnames1[i] as HTMLDivElement).style.display = 'none';
          if (graphparamnames2 != null && graphparamnames2[i] != null) (graphparamnames2[i] as HTMLDivElement).style.display = 'none';
          if (graphparamnames3 != null && graphparamnames3[i] != null) (graphparamnames3[i] as HTMLDivElement).style.display = 'none';
          if (eventSubTitles[i] != null) {
            (eventSubTitles[i] as HTMLDivElement).style.display = 'none';
          }
          if (buttonListReporting[i] != null) {
            buttonListReporting[i].style.display = 'none';
          }
        }
        // console.log('eventTitle', divs[i]);
        if (buttonSelect[i] != null) buttonSelect[i].style.display = "none"
        if (eventTitles[i] != null) (eventTitles[i]).style.display = 'none';
        if (divs[i] != null) divs[i].style.display = 'none'
      }

    }
    let listReportingContainers = eventContainer!.querySelectorAll('.list-reporting-container') as NodeListOf<HTMLDivElement>
    for (let tempReportingContainer of listReportingContainers) {
      tempReportingContainer.style.display = 'none';
      tempReportingContainer.innerHTML = '';
    }
    let buttonListReportings = eventContainer!.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
    for (let buttonListReporting of buttonListReportings) {
      buttonListReporting.setAttribute('part', 'button-list-reporting')
    }
    let streamEventTitles = eventContainer!.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
    for (let streamEventTitle of streamEventTitles) {
      streamEventTitle.removeAttribute('part')
    }
  }

  processClickOnLegend = (index: number, legendItem: any) => {

    legendItem.hidden = true;
    const ci = this.chart;
    if (this.chart.legend.chart.data.datasets != null) {
      this.chart.legend.chart.data.datasets[0].data.forEach((_d: any, i: any) => {
        if (index === i) {

          let opHide = true;

          //console.log('dataset-found before before', this.isSelectedLegend(i), legendItem, this.chartSelectedLegend);

          if (!this.isSelectedLegend(i)) {

            //this.clearSelectedLegend();

            opHide = true;
            this.chart.legend.chart.getDatasetMeta(0).data[index].hidden = true;
            this.chartSelectedLegend.push(index);
            ci.update();

          } else {

            opHide = false;

            for (var j = 0; j < this.chartSelectedLegend.length; j++) {
              this.chart.legend.chart.getDatasetMeta(0).data[this.chartSelectedLegend[j]].hidden = false;
            }
            this.removeFromSelectedLegend(index)
            ci.update();

          }

          this.clickOnLegend(this.isSelectedLegend(i), legendItem.text);

          if (this.chart2 != null && this.chart3 != null) {

            if (opHide) {

              // if(this.barCharDataSet2Arr.length > 0) {
              //   this.chart2.data.datasets = this.barCharDataSet2Arr.pop();
              // }

              // if(this.barCharDataSet3Arr.length > 0) {
              //   this.chart3.data.datasets = this.barCharDataSet3Arr.pop();
              // }

              // this.barCharDataSet2Arr.push({index: index, value: this.copy(this.chart2.data.datasets)});
              // this.barCharDataSet3Arr.push({index: index, value: this.copy(this.chart3.data.datasets)});

              this.barCharDataSet2Arr.push(this.copy(this.chart2.data.datasets));
              this.barCharDataSet3Arr.push(this.copy(this.chart3.data.datasets));

              for (var k = 0; k < this.chart2.data.datasets.length; k++) {
                const dataset = this.chart2.data.datasets[k];
                for (var j = 0; j < dataset.data.length; j++) {
                  if (j === index) {
                    dataset.data[j] = 0;
                  } else {
                  }
                }
              }

              for (var k = 0; k < this.chart3.data.datasets.length; k++) {
                const dataset = this.chart3.data.datasets[k];
                for (var j = 0; j < dataset.data.length; j++) {
                  if (j === index) {
                    dataset.data[j] = 0;
                  } else {
                  }
                }
              }

              //console.log('dataset-found before', this.barCharDataSet3Arr);

            } else {

              do {
                this.chart2.data.datasets = this.barCharDataSet2Arr.pop();
                this.chart3.data.datasets = this.barCharDataSet3Arr.pop();
              } while (this.barCharDataSet2Arr.length > 0);

              this.chartSelectedLegend = [];

            }

            this.chart2.update();
            this.chart3.update();

          }

          ////console.log('modified datasets', this.chart2.data.datasets);

          //console.log('dataset-found after', this.chartSelectedLegend);

        }
      })

    }

  }
  processClickOnLegendStats = (index: number, legendItem: any) => {

    legendItem.hidden = true;
    const ci = this.chart;
    if (this.chart.legend.chart.data.datasets != null) {
      this.chart.legend.chart.data.datasets[0].data.forEach((_d: any, i: any) => {
        if (index === i) {

          let opHide = true;

          //console.log('dataset-found before before', this.isSelectedLegend(i), legendItem, this.chartSelectedLegend);

          if (!this.isSelectedLegend(i)) {

            //this.clearSelectedLegend();

            opHide = true;
            this.chart.legend.chart.getDatasetMeta(0).data[index].hidden = true;
            this.chartSelectedLegend.push(index);
            ci.update();

          } else {

            opHide = false;

            for (var j = 0; j < this.chartSelectedLegend.length; j++) {
              this.chart.legend.chart.getDatasetMeta(0).data[this.chartSelectedLegend[j]].hidden = false;
            }
            this.removeFromSelectedLegend(index)
            ci.update();

          }

          this.clickOnLegend(this.isSelectedLegend(i), legendItem.text);

          if (this.chart2 != null && this.chart3 != null) {

            if (opHide) {

              // if(this.barCharDataSet2Arr.length > 0) {
              //   this.chart2.data.datasets = this.barCharDataSet2Arr.pop();
              // }

              // if(this.barCharDataSet3Arr.length > 0) {
              //   this.chart3.data.datasets = this.barCharDataSet3Arr.pop();
              // }

              // this.barCharDataSet2Arr.push({index: index, value: this.copy(this.chart2.data.datasets)});
              // this.barCharDataSet3Arr.push({index: index, value: this.copy(this.chart3.data.datasets)});

              this.barCharDataSet2Arr.push(this.copy(this.chart2.data.datasets));
              this.barCharDataSet3Arr.push(this.copy(this.chart3.data.datasets));
              this.barCharDataSet4Arr.push(this.copy(this.chart4.data.datasets));
              console.log('processingLegendClick', this.chart2.data.datasets, index, legendItem)
              for (var k = 0; k < this.chart2.data.datasets.length; k++) {
                const dataset = this.chart2.data.datasets[k];
                if (dataset.label.toLowerCase() == legendItem.text.toLowerCase()) {
                  for (var j = 0; j < dataset.data.length; j++) {
                    // if (j === index) {
                    dataset.data[j] = 0;
                    // } else {
                    // }
                  }
                }
              }

              for (var k = 0; k < this.chart3.data.datasets.length; k++) {
                const dataset = this.chart3.data.datasets[k];
                if (dataset.label.toLowerCase() == legendItem.text.toLowerCase()) {
                  for (var j = 0; j < dataset.data.length; j++) {
                    // if (j === index) {
                    dataset.data[j] = 0;
                    // } else {
                    // }
                  }
                }
              }

              for (var k = 0; k < this.chart4.data.datasets.length; k++) {
                const dataset = this.chart4.data.datasets[k];
                if (dataset.label.toLowerCase() == legendItem.text.toLowerCase()) {
                  for (var j = 0; j < dataset.data.length; j++) {
                    // if (j === index) {
                    dataset.data[j] = 0;
                    // } else {
                    // }
                  }
                }
              }

              //console.log('dataset-found before', this.barCharDataSet3Arr);

            } else {

              do {
                this.chart2.data.datasets = this.barCharDataSet2Arr.pop();
                this.chart3.data.datasets = this.barCharDataSet3Arr.pop();
                this.chart4.data.datasets = this.barCharDataSet4Arr.pop();
              } while (this.barCharDataSet2Arr.length > 0);

              this.chartSelectedLegend = [];

            }

            this.chart2.update();
            this.chart3.update();
            this.chart4.update();

          }

          ////console.log('modified datasets', this.chart2.data.datasets);

          //console.log('dataset-found after', this.chartSelectedLegend);

        }
      })

    }

  }

  clickOnLegend = (hide: boolean, label: string) => {
    //console.log(hide, label);
    let labelClicked = '';

    if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS || this.flowGraph == this.FLOW_GRAPH_COMPLIANCE) {
      labelClicked = (label).toLowerCase().replace(/ /g, "-").replace('status-', '');
    } else {
      labelClicked = (label).toLowerCase();
    }

    this.processGraphHide(labelClicked, hide);
  }

  clickOnPie = (callingFromBar: boolean, pieIndex: number) => {

    //console.log('pie bar trigger 1 0', JSON.stringify(this.barCharDataSet2));
    //console.log('pieIndex', pieIndex);

    if (this.barCharDataSet2Arr.length > 0) {
      this.clearSelectedLegend();
    }

    //console.log('pie bar trigger 1 1', JSON.stringify(this.barCharDataSet2));

    let labelClicked = '';

    if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
      labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase().replace(/ /g, "-").replace('status-', '');
    } else {
      labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase();
    }

    console.log('pieIndex', labelClicked);

    if (!callingFromBar) {
      console.log('pieIndex', labelClicked);
      console.log('calling processGraphFilter 2')
      this.processGraphFilter(labelClicked);
    }

  }
  clickOnPieStats = (callingFromBar: boolean, pieIndex: number) => {

    //console.log('pie bar trigger 1 0', JSON.stringify(this.barCharDataSet2));
    //console.log('pieIndex', pieIndex);

    if (this.barCharDataSet2Arr.length > 0) {
      this.clearSelectedLegend();
    }

    //console.log('pie bar trigger 1 1', JSON.stringify(this.barCharDataSet2));

    console.log('this.chart', this.chart)
    let labelClicked = '';

    if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
      labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase().replace(/ /g, "-").replace('status-', '');
    } else {
      labelClicked = (this.chart.data.labels[pieIndex] + "").toLowerCase();
    }

    console.log('pieIndex', labelClicked);

    if (!callingFromBar) {
      if (this.graphParam != labelClicked) {
        this.graphParam = labelClicked;
      } else {
        this.graphParam = ""
      }
      // console.log('pieIndex', labelClicked);
      // console.log('calling processGraphFilter 2')
      // this.processGraphFilter(labelClicked);
    }

  }

  clickOnBar = (callingFromPie: boolean, graphNumber: number, barIndex: number) => {

    let labelClicked = '';

    if (graphNumber === 2 || graphNumber === 3 || graphNumber === 4) {
      if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
        labelClicked = (this.chart2.data.labels[barIndex].join(" ") + "").toLowerCase().replace(/ /g, "-").replace('status-', '');
      } else {
        labelClicked = (this.chart2.data.labels[barIndex].join(" ") + "").toLowerCase();
      }
    }

    if (!callingFromPie) {
      console.log('calling processGraphFilter 3')
      this.processGraphFilter(labelClicked);
    }

    //console.log('clickonbar trigger', this.graphParam, '><', this.barCharDataSet2);

    if (this.graphParam.length > 0) {

      if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) {
        this.chart2.data.datasets = this.barCharDataSet2.pop();
        this.chart3.data.datasets = this.barCharDataSet3.pop();
        this.chart4.data.datasets = this.barCharDataSet4.pop();
      }

      this.barCharDataSet2.push(this.copy(this.chart2.data.datasets));
      for (var i = 0; i < this.chart2.data.datasets.length; i++) {
        const dataset = this.chart2.data.datasets[i];
        for (var j = 0; j < dataset.data.length; j++) {
          if (j === barIndex) {

          } else {
            dataset.data[j] = 0;
          }
        }
      }

      this.barCharDataSet3.push(this.copy(this.chart3.data.datasets));
      for (var i = 0; i < this.chart3.data.datasets.length; i++) {
        const dataset = this.chart3.data.datasets[i];
        for (var j = 0; j < dataset.data.length; j++) {
          if (j === barIndex) {

          } else {
            dataset.data[j] = 0;
          }
        }
      }

      this.barCharDataSet4.push(this.copy(this.chart4.data.datasets));
      for (var i = 0; i < this.chart4.data.datasets.length; i++) {
        const dataset = this.chart4.data.datasets[i];
        for (var j = 0; j < dataset.data.length; j++) {
          if (j === barIndex) {

          } else {
            dataset.data[j] = 0;
          }
        }
      }

      //console.log('clickonbar trigger latest values', this.chart2.data.datasets);
      //console.log('clickonbar trigger in storage', this.barCharDataSet2);

    } else {
      this.chart2.data.datasets = this.barCharDataSet2.pop();
      this.chart3.data.datasets = this.barCharDataSet3.pop();
      this.chart4.data.datasets = this.barCharDataSet4.pop();
    }

    //console.log(this.chart2.data);
    this.chart2.update();
    this.chart3.update();
    this.chart4.update();

  }

  clickOnBarStats = (callingFromPie: boolean, graphNumber: number, labelText: string) => {

    let labelClicked = '';

    if (graphNumber === 2 || graphNumber === 3 || graphNumber === 4) {
      if (this.flowGraph == this.FLOW_GRAPH_COMPLETENESS || this.flowGraph == this.FLOW_GRAPH_TIMELINESS) {
        labelClicked = (labelText + "").toLowerCase().replace(/ /g, "-").replace('status-', '');
      } else {
        labelClicked = (labelText + "").toLowerCase();
      }
    }

    if (!callingFromPie) {
      console.log('calling processGraphFilter 3')
      this.processGraphFilter(labelClicked);
    }

    // console.log('clickonbar trigger', this.graphParam, '><', this.barCharDataSet2);

    if (this.graphParam.length > 0) {

      if (this.barCharDataSet2.length > 0 && this.barCharDataSet3.length > 0 && this.barCharDataSet4.length > 0) {
        this.chart2.data.datasets = this.barCharDataSet2.pop();
        this.chart3.data.datasets = this.barCharDataSet3.pop();
        this.chart4.data.datasets = this.barCharDataSet4.pop();
      }

      this.barCharDataSet2.push(this.copy(this.chart2.data.datasets));
      let tempDatasets = []
      for (var i = 0; i < this.chart2.data.datasets.length; i++) {
        const dataset = this.chart2.data.datasets[i];
        if (dataset.label.toLowerCase() != labelText.toLowerCase()) {
          // for (var j = 0; j < dataset.data.length; j++) {
          //   // if (j === barIndex) {

          //   // } else {
          //   dataset.data[j] = 0;
          //   // }
          // }
        } else {
          tempDatasets.push(dataset);
        }
      }
      this.chart2.data.datasets = tempDatasets;

      this.barCharDataSet3.push(this.copy(this.chart3.data.datasets));
      tempDatasets = []
      for (var i = 0; i < this.chart3.data.datasets.length; i++) {
        const dataset = this.chart3.data.datasets[i];
        if (dataset.label.toLowerCase() != labelText.toLowerCase()) {
          // for (var j = 0; j < dataset.data.length; j++) {
          //   // if (j === barIndex) {

          //   // } else {
          //   dataset.data[j] = 0;
          //   // }
          // }
        } else {
          tempDatasets.push(dataset);
        }
      }
      this.chart3.data.datasets = tempDatasets;

      this.barCharDataSet4.push(this.copy(this.chart4.data.datasets));
      tempDatasets = []
      for (var i = 0; i < this.chart4.data.datasets.length; i++) {
        const dataset = this.chart4.data.datasets[i];
        if (dataset.label.toLowerCase() != labelText.toLowerCase()) {
          // for (var j = 0; j < dataset.data.length; j++) {
          //   // if (j === barIndex) {

          //   // } else {
          //   dataset.data[j] = 0;
          //   // }
          // }
        } else {
          tempDatasets.push(dataset);
        }
      }
      this.chart4.data.datasets = tempDatasets;

      //console.log('clickonbar trigger latest values', this.chart2.data.datasets);
      //console.log('clickonbar trigger in storage', this.barCharDataSet2);

    } else {
      console.log('this.chart2.data before', this.chart2.data);
      this.chart2.data.datasets = this.barCharDataSet2.pop();
      this.chart3.data.datasets = this.barCharDataSet3.pop();
      this.chart4.data.datasets = this.barCharDataSet4.pop();
    }

    console.log('this.chart2.data', this.chart2.data);
    this.chart2.update();
    this.chart3.update();
    this.chart4.update();

  }

  getCurrentTab = () => {
    if (this.mode == "next") {
      return;
    }
    if ((this._SfCalendarContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_YEAR;
    }

    if ((this._SfStreamContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_STREAM;
    }

    if ((this._SfUpcomingContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_UPCOMING;
    }

    if ((this._SfThisContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_THIS;
    }

    if ((this._SfPastContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_PAST;
    }

    if ((this._SfCustomContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_CUSTOM;
    }

    if ((this._SfFindContainer as HTMLDivElement).style.display == 'flex') {
      return this.TAB_FIND;
    }

    return "";

  }

  renderTabs = (selectedTab: string) => {

    this.selectedTab = selectedTab;

    this.clearAllCalendars();

    this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;

    var html = '';

    html += '<button class="tab-button mb-10" id="calendar-tab-month" part="' + (selectedTab == this.TAB_STREAM ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Month</button>';
    html += '<button class="tab-button mb-10" id="calendar-tab-custom" part="' + (selectedTab == this.TAB_CUSTOM ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">' + (this.myRole == this.TAB_VIEWER ? "Statistics" : "Range") + '</button>';
    if (this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0) {
      html += '<button class="tab-button mb-10" id="calendar-tab-register" part="' + (selectedTab == this.TAB_REGISTERS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Registers</button>';
      html += '<button class="tab-button tab-button-secondary mb-10 ' + (selectedTab == this.TAB_FIND ? '' : 'hide') + '" id="calendar-tab-find" part="' + (selectedTab == this.TAB_FIND ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Search</button>';
      html += '<button class="tab-button tab-button-secondary mb-10 ' + (selectedTab == this.TAB_THIS ? '' : 'hide') + '" id="calendar-tab-this" part="' + (selectedTab == this.TAB_THIS ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Current</button>';
      html += '<button class="tab-button tab-button-secondary mb-10 ' + (selectedTab == this.TAB_YEAR ? '' : 'hide') + '" id="calendar-tab-year" part="' + (selectedTab == this.TAB_YEAR ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Overview</button>';
      html += '<button class="tab-button tab-button-secondary mb-10 ' + (selectedTab == this.TAB_ADHOC ? '' : 'hide') + '" id="calendar-tab-adhoc" part="' + (selectedTab == this.TAB_ADHOC ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Adhoc</button>';
      html += '<button class="tab-button mb-10" id="calendar-tab-next" part="calendar-tab-button-not-selected"><span class="material-symbols-outlined">arrow_forward_ios</span></button>';
    }


    // html += '<button class="tab-button mb-10" id="calendar-tab-upcoming" part="'+(selectedTab == this.TAB_UPCOMING ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected')+'">Upcoming</button>';
    // html += '<button class="tab-button mb-10" id="calendar-tab-past" part="'+(selectedTab == this.TAB_PAST ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected')+'">Past</button>';

    (this._SfTabContainer as HTMLDivElement).innerHTML = html;
    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-next')?.addEventListener('click', async (e: any) => {

      const buttons = (this._SfTabContainer as HTMLDivElement).querySelectorAll('.tab-button-secondary') as NodeListOf<HTMLButtonElement>;
      buttons.forEach(button => {
        button.style.display = 'block';
      });

      const button = (e.currentTarget as HTMLButtonElement);
      button.style.display = 'none';

    });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-year')?.addEventListener('click', async () => {

      //console.log('calclicked', this.mode);

      if (this.mode == "consumer") {
        this.renderTabs(this.TAB_YEAR);
        this.enableCalendar();
        await this.fetchAndYearlyRenderUserCalendar_2();
        //this.renderCalendar();
        // this.loadMode();

      } else {
        this.enableCalendar();
        this.renderTabs(this.TAB_YEAR);
      }
    });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month')?.addEventListener('click', async () => {
      this.enableStream();
      this.renderTabs(this.TAB_STREAM);

      const currMonth = ("0" + (new Date().getMonth() + 1)).slice(-2);

      //console.log('currMonth', currMonth);

      let idx = 0;
      for (var i = 0; i < 12; i++) {
        //console.log('currMonth compare', currMonth, (parseInt(this.calendarStartMM) + i)%12);
        if ((parseInt(currMonth) === 12 && (parseInt(this.calendarStartMM) + i) % 12 === 0) || parseInt(currMonth) === (parseInt(this.calendarStartMM) + i) % 12) {
          idx = i;
          break;
        }
      }
      this.currentColumnIndex = idx + "";
      const dateResult = this.calculateStartAndEndDateOfStream(idx);
      const monthResult = this.calculateMonthFromIndex(idx);
      if (dateResult != null) {
        await this.renderWithFeatures(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
        // await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate,"","yes",("0" + monthResult).slice(-2));
      }
      this.renderStream(idx, true, false);
    });

    // (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-upcoming')?.addEventListener('click', async () => {
    //   this.enableUpcoming();
    //   this.renderTabs(this.TAB_UPCOMING);
    //   const dateResult = this.calculateStartAndEndDateOfUpcoming(1);
    //   //console.log('dateresult', dateResult)
    //   this.currentColumnIndex =  1 + ""
    //   await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
    //   this.renderUpcoming();
    // });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-this')?.addEventListener('click', async () => {
      this.enableThis();
      this.renderTabs(this.TAB_THIS);
      const dateResult = this.calculateStartAndEndDateOfThis(0);
      let idx = 0;
      const currMonth = ("0" + (new Date().getMonth() + 1)).slice(-2);
      for (var i = 0; i < 12; i++) {
        //console.log('currMonth compare', currMonth, (parseInt(this.calendarStartMM) + i)%12);
        if ((parseInt(currMonth) === 12 && (parseInt(this.calendarStartMM) + i) % 12 === 0) || parseInt(currMonth) === (parseInt(this.calendarStartMM) + i) % 12) {
          idx = i;
          break;
        }
      }
      const monthResult = this.calculateMonthFromIndex(idx);
      //console.log('dateresult', dateResult)
      this.currentColumnIndex = 1 + ""
      await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate, "", "yes", ("0" + monthResult).slice(-2));
      this.renderThis(0, true, false);
    });

    // (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-past')?.addEventListener('click', async () => {
    //   this.enablePast();
    //   this.renderTabs(this.TAB_PAST);
    //   const dateResult = this.calculateStartAndEndDateOfPast(1);
    //   //console.log('dateresult', dateResult)
    //   this.currentColumnIndex =  1 + ""
    //   await this.fetchAndYearlyRenderUserCalendar_2(dateResult.startDate, dateResult.endDate);
    //   this.renderPast();
    // });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom')?.addEventListener('click', () => {
      this.enableCustom();
      this.renderTabs(this.TAB_CUSTOM);
      console.log('stats clicked');
      if (this.myRole == this.TAB_VIEWER) {
        this.renderCustomViewer()
      } else {
        this.renderCustom();
      }
    });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-find')?.addEventListener('click', () => {
      this.enableFind();
      this.renderTabs(this.TAB_FIND);
      this.renderFind();
    });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-adhoc')?.addEventListener('click', () => {
      this.enableAdhoc();
      this.renderTabs(this.TAB_ADHOC);
      this.renderAdhoc();
    });

    (this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-register')?.addEventListener('click', () => {
      this.enableRegisters();
      this.renderTabs(this.TAB_REGISTERS);
      this.renderRegister();
    });

  }

  renderMappingTabs = (selectedTab: string) => {

    var html = '';

    html += '<button class="tab-button" id="mapping-tab-reporter" part="' + (selectedTab == this.TAB_REPORTER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Reporter</button>';
    html += '<button class="tab-button" id="mapping-tab-approver" part="' + (selectedTab == this.TAB_APPROVER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Approver</button>';

    (this._SfMappingTabContainer as HTMLDivElement).innerHTML = html;

    if (this.myRole == this.TAB_REPORTER) {
      //console.log('sync mapping reporter');
      (this._SfButtonBackSyncMapping as HTMLButtonElement).style.visibility = 'visible';
    } else {
      //console.log('sync mapping approver');
      (this._SfButtonBackSyncMapping as HTMLButtonElement).style.visibility = 'hidden';
    }

    (this._SfMappingTabContainer as HTMLDivElement).querySelector('#mapping-tab-reporter')?.addEventListener('click', () => {
      this.myRole = this.TAB_REPORTER;
      this.fetchEventMap();
      this.renderMappingTabs(this.TAB_REPORTER)
    });

    (this._SfMappingTabContainer as HTMLDivElement).querySelector('#mapping-tab-approver')?.addEventListener('click', () => {
      this.myRole = this.TAB_APPROVER;
      this.fetchEventMap();
      this.renderMappingTabs(this.TAB_APPROVER)
    });

  }

  renderExpandEvent = (events: any, index: any) => {

    var html = '';

    for (var k = 0; k < Object.keys(events[index]).length; k++) {
      if (!this.getEventPreviewFields().includes(Object.keys(events[index])[k])) {

        html += '<td part="td-body">';
        if (events[index][Object.keys(events[index])[k]].indexOf("[") >= 0) {
          html += this.getEventTexts(Object.keys(events[index])[k], JSON.parse(events[index][Object.keys(events[index])[k]]), events[index]);
        } else {
          html += '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + events[index][Object.keys(events[index])[k]].replace(/"/g, "") + '" minLength="20"></sf-i-elastic-text>';
        }
        html += '</td>';

      }
    }

    //console.log((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-'+index)!.innerHTML);

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-' + index)!.insertAdjacentHTML('beforeend', html);

    html = '';
    for (var k = 0; k < Object.keys(events[index]).length; k++) {
      if (!this.getEventPreviewFields().includes(Object.keys(events[index])[k])) {
        html += '<th part="td-head" class="bg-left">';
        html += Object.keys(events[index])[k];
        html += '</th>';
      }
    }

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-head-' + index)!.insertAdjacentHTML('beforeend', html);

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#th-expand-' + index) as HTMLElement).style.display = 'none';
    ((this._SfMappingContainer as HTMLDivElement).querySelector('#td-expand-' + index) as HTMLElement).style.display = 'none';

  }

  renderMapping = (unmappedEvents: any) => {

    this.mappedValuesDueDates = {};
    this.mappedValuesTags = {};
    this.mappedValuesUsers = {};

    //console.log('rendering mapping1', unmappedEvents, this.mappedValuesDueDates, this.mappedValuesUsers, this.mappedValuesTags)


    var html = '';

    html += '<div class="d-flex align-center mt-20">';
    html += '<div id="row-unmapped-graph" class="d-flex flex-grow"><div class="div-graph-complete"></div><div class="div-graph-pending"></div></div>';
    html += '<div id="row-unmapped-summary" part="filter-title" class="ml-10">Completed 0</div>';
    html += '</div>';

    html += '<table part="stream-event-selected" id="row-unmapped-table-multi-entry" class="hide fixed-bottom justify-center">';
    html += '<tr>';
    html += '</tr>';
    html += '<tr>';
    html += '<th part="td-head" class="col-date">';
    html += 'Duedate';
    html += '</th>';
    html += '<th part="td-head" class="col-tags">';
    html += 'Tags';
    html += '</th>';
    html += '<th part="td-head">';
    html += 'Users';
    html += '</th>';
    html += '<th class="d-flex">';
    html += '<button id="row-unmapped-table-multi-entry-cancel" part="button-icon-small" class="material-icons">close</button>';
    html += '</th>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="col-date">';
    html += '<input part="input" type="text" id="row-unmapped-input-multi-entry-date" />';
    html += '</td>';
    html += '<td part="td-head" class="col-tags">';
    html += '<sf-i-form id="row-unmapped-input-multi-entry-tags" name="Tags" label="Select Tags" apiId="' + this.apiIdTags + '" mode="multiselect-dropdown" searchPhrase="' + (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0] + '" selectProjection="name" mandatory></sf-i-form>';
    //html += '<input part="input" type="text" id="row-unmapped-input-multi-entry-tags"  />';
    html += '</td>';
    html += '<td part="td-head">';
    html += '<sf-i-form id="row-unmapped-input-multi-entry-users" name="Users" label="Select Users" apiId="' + this.apiIdUsers + '" mode="multiselect-dropdown" searchPhrase="' + (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0] + '" selectProjection="name" mandatory></sf-i-form>';
    //html += '<input part="input" type="text" id="row-unmapped-input-multi-entry-users"  />';
    html += '</td>';
    html += '<td>';
    html += '</td>';
    html += '</tr>';
    html += '</table>';

    html += '<div class="d-flex align-center mt-20 mb-20">';
    html += '<div class="mr-10" part="filter-title">Filter</div>';
    html += '<div class="pr-10 pt-5 pb-5" part="filter-title"><label><input name="row-unmapped-filter" id="row-unmapped-filter-all" type="radio"/>All</label></div>'
    html += '<div class="pr-10 pt-5 pb-5" part="filter-title"><label><input name="row-unmapped-filter" id="row-unmapped-filter-mapped" type="radio"/>Mapped</label></div>'
    html += '<div class="pr-10 pt-5 pb-5" part="filter-title"><label><input name="row-unmapped-filter" id="row-unmapped-filter-unmapped" type="radio"/>Un-mapped</label></div>'
    html += '</div>'

    html += '<div class="container-mapping-event">';

    for (var i = 0; i < unmappedEvents.length; i++) {

      // var moveOn = false;

      // if(filter != "all") {
      //   if(filter == "mapped") {
      //     if(this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") {
      //       moveOn = true;
      //     }
      //   }
      //   if(filter == "unmapped") {
      //     if(this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") {
      //       moveOn = true;
      //     }
      //   }
      // }

      // if(moveOn) {
      //   continue;
      // }

      //console.log(unmappedEvents[i]);
      html += '<table id="row-unmapped-table' + i + '">';
      html += '<thead>';
      html += '<tr id="row-unmapped-head-' + i + '">';
      html += '<th part="td-head" class="left-sticky bg-left">';
      html += 'Select';
      html += '</th>';
      html += '<th part="td-head" class="bg-left ' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? 'color-done' : 'color-pending') + '">';
      html += 'Status';
      html += '</th>';
      html += '<th part="td-head" class="bg-left col-date-head-' + i + '">';
      html += 'Duedate';
      html += '</th>';
      html += '<th part="td-head" class="bg-left col-tags-head-' + i + '">';
      html += 'Tags';
      html += '</th>';
      html += '<th part="td-head" class="bg-left">';
      html += 'Users';
      html += '</th>';
      for (var k = 0; k < Object.keys(unmappedEvents[i]).length; k++) {
        if (this.getEventPreviewFields().includes(Object.keys(unmappedEvents[i])[k])) {
          html += '<th part="td-head" class="bg-left">';
          html += Object.keys(unmappedEvents[i])[k];
          html += '</th>';
        }
      }
      html += '<th id="th-expand-' + i + '" part="td-head">';
      html += '</th>';
      html += '</tr>';
      html += '</thead>';
      html += '<tbody>';
      html += '<tr id="row-unmapped-' + i + '">';
      html += '<td part="td-body" class="left-sticky">';
      html += '<input type="checkbox" class="input-checkbox" id="row-unmapped-select-' + i + '"/>'
      html += '</td>';
      html += '<td part="td-body" class="" id="row-unmapped-status-' + i + '">';
      html += '<span class="material-icons ' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? 'color-done' : 'color-pending') + '">' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? 'check_circle' : 'pending') + '</span>';
      html += '</td>';
      html += '<td part="td-body" class="col-date-' + i + '">';
      html += '<div class="d-flex align-center">';
      html += '<input part="input" type="text" id="row-unmapped-override-date-input-' + i + '" class="hide input-dates" value="' + (this.mappedValuesDueDates[i] != null ? this.mappedValuesDueDates[i] : '') + '"/>';
      html += '<div id="row-unmapped-override-date-div-' + i + '" class="div-dates">' + ((this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : '') + '</div>';
      html += '</div>';
      html += '</td>';
      html += '<td part="td-body" class="col-tags-' + i + '">';
      html += '<sf-i-form id="row-unmapped-input-tags-' + i + '" class="hide input-tags" name="Tags" label="Select Tags" apiId="' + this.apiIdTags + '" mode="multiselect-dropdown" searchPhrase="' + (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0] + '" selectProjection="name" mandatory></sf-i-form>';
      //html += '<input part="input" type="text" id="row-unmapped-input-tags-'+i+'" class="hide input-tags" value="'+((this.mappedValuesTags[i] != null && this.mappedValuesTags[i] != "") ? this.mappedValuesTags[i] : '')+'"/>';
      html += '<div id="row-unmapped-div-tags-' + i + '" class="div-tags">' + ((this.mappedValuesTags[i] != null && this.mappedValuesTags[i] != "") ? this.mappedValuesTags[i] : '') + '</div>';
      html += '</td>';
      html += '<td part="td-body" class="">';
      html += '<sf-i-form id="row-unmapped-input-users-' + i + '" class="hide input-users" name="Users" label="Select Users" apiId="' + this.apiIdUsers + '" mode="multiselect-dropdown" searchPhrase="' + (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0] + '" selectProjection="name" mandatory></sf-i-form>';
      //html += '<input part="input" type="text" id="row-unmapped-input-users-'+i+'" class="hide input-users" value="'+((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? this.mappedValuesUsers[i] : '')+'"/>';
      html += '<div id="row-unmapped-div-users-' + i + '" class="div-users">' + ((this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") ? this.mappedValuesUsers[i] : '') + '</div>';
      html += '</td>';
      for (var k = 0; k < Object.keys(unmappedEvents[i]).length; k++) {
        if (this.getEventPreviewFields().includes(Object.keys(unmappedEvents[i])[k])) {

          html += '<td part="td-body">';
          if (unmappedEvents[i][Object.keys(unmappedEvents[i])[k]].indexOf("[") >= 0) {
            html += this.getEventTexts(Object.keys(unmappedEvents[i])[k], JSON.parse(unmappedEvents[i][Object.keys(unmappedEvents[i])[k]]), unmappedEvents[i]);
          } else {
            html += ' <sf-i-elastic-text exportparts="highlight,highlight-count" text="' + unmappedEvents[i][Object.keys(unmappedEvents[i])[k]].replace(/"/g, "") + '" minLength="20"></sf-i-elastic-text>';
          }
          html += '</td>';

        }
      }
      html += '<td id="td-expand-' + i + '" part="td-body">';
      html += '<button id="button-unmapped-expand-' + i + '" part="button-icon-small" class="material-icons">chevron_right</button>'
      html += '</td>';
      html += '</tr>';
      html += '</tbody>';
      html += '</table>';
    }

    html += '</div>';

    html += '<button id="button-back-add-mapping" part="button" class="invisible mb-20 mt-20">Save</button>';

    (this._SfMappingContainer as HTMLDivElement).innerHTML = html;


    for (var i = 0; i < unmappedEvents.length; i++) {

      // var moveOn = false;

      // if(filter != "all") {
      //   if(filter == "mapped") {
      //     if(this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") {
      //       moveOn = true;
      //     }
      //   }
      //   if(filter == "unmapped") {
      //     if(this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") {
      //       moveOn = true;
      //     }
      //   }
      // }

      // if(moveOn) {
      //   continue;
      // }

      (this._SfMappingContainer as HTMLDivElement).querySelector('#button-unmapped-expand-' + i)?.addEventListener('click', (ev: any) => {

        const clickIndex = ev.target.id.split("-")[3];
        //console.log('clickindex', clickIndex)
        this.renderExpandEvent(unmappedEvents, clickIndex);

      });

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-select-' + i) as HTMLInputElement).addEventListener('change', (ev: any) => {

        const clickIndex = ev.target.id.split("-")[3];
        //console.log('clickcheckbox', clickIndex)
        if (((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-select-' + clickIndex) as HTMLInputElement).checked) {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement).style.display = 'block';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLInputElement).style.display = 'none';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as HTMLInputElement).style.display = 'block';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLInputElement).style.display = 'none';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as HTMLInputElement).style.display = 'block';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLInputElement).style.display = 'none';
        } else {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement).style.display = 'none';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLInputElement).style.display = 'block';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as HTMLInputElement).style.display = 'none';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLInputElement).style.display = 'block';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as HTMLInputElement).style.display = 'none';
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLInputElement).style.display = 'block';
        }
        if (this.checkAndShowBulk()) {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'flex';
        } else {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'none';
        }

      });

      (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + i)?.addEventListener('keyup', (ev: any) => {

        const clickIndex = ev.target.id.split("-")[5];
        const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + clickIndex) as HTMLDivElement);
        const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + clickIndex) as HTMLInputElement);
        div.innerHTML = input.value;
        this.mappedValuesDueDates[clickIndex] = input.value;

      });

      (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + i)?.addEventListener('valueChanged', (ev: any) => {

        const clickIndex = ev.target.id.split("-")[4];
        const form = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + clickIndex) as SfIForm);
        const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + clickIndex) as HTMLDivElement);
        div.innerHTML = '';
        var html = '';
        for (var i = 0; i < form.selectedValues().length; i++) {
          html += form.selectedValues()[i];
          if (i < (form.selectedValues().length - 1)) {
            html += ",";
          }
        }
        div.innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
        this.mappedValuesTags[clickIndex] = form.selectedValues();

        // const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-'+clickIndex) as HTMLDivElement);
        // const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-'+clickIndex) as HTMLInputElement);
        // div.innerHTML = input.value;

      });

      (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + i)?.addEventListener('valueChanged', (ev: any) => {

        const clickIndex = ev.target.id.split("-")[4];
        const form = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + clickIndex) as SfIForm);
        //console.log('valuechanged called', form.selectedValues());
        const div = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + clickIndex) as HTMLDivElement);
        div.innerHTML = '';
        var html = '';
        for (var i = 0; i < form.selectedValues().length; i++) {
          html += form.selectedValues()[i];
          if (i < (form.selectedValues().length - 1)) {
            html += ",";
          }
        }
        div.innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
        this.mappedValuesUsers[clickIndex] = form.selectedValues();
        this.updateMappingStatus(form.selectedValues(), clickIndex);
        this.calculateAndShowSummary();

      });

    }

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-users')?.addEventListener('valueChanged', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-users') as SfIForm);
      //console.log('valuechanged users', input.selectedValues());
      this.updateInAllSelections("users", input.selectedValues());

    });

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-date')?.addEventListener('keyup', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-date') as HTMLInputElement);
      this.updateInAllSelections("duedate", input.value)

    });

    (this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-tags')?.addEventListener('valueChanged', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-multi-entry-tags') as SfIForm);
      this.updateInAllSelections("tags", input.selectedValues());

    });

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement).addEventListener('change', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement);
      if (input.checked) {
        this.showAllEvents();
      }

    });

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement).addEventListener('change', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement);
      if (input.checked) {
        this.showMappedEvents();
      }

    });

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement).addEventListener('change', () => {

      const input = ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement);
      if (input.checked) {
        this.showUnmappedEvents();
      }

    });

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry-cancel') as HTMLInputElement).addEventListener('click', () => {

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table-multi-entry') as HTMLElement).style.display = 'none';
      this.clearAllMappingSelections();

    });

    ((this._SfMappingContainer as HTMLDivElement).querySelector('#button-back-add-mapping') as HTMLButtonElement)!.addEventListener('click', async () => {
      this.uploadMapping();
    });
  }

  applyFilter = (filter: string = "all") => {

    for (var i = 0; i < this.unmappedEvents.length; i++) {

      if (filter == "mapped") {


        if (this.mappedValuesUsers[i] != null && this.mappedValuesUsers[i] != "") {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block';
        } else {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'none';
        }

      }

      if (filter == "unmapped") {

        if (this.mappedValuesUsers[i] == null || this.mappedValuesUsers[i] == "") {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block';
        } else {
          ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'none';
        }

      }

      if (filter == "all") {

        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-table' + i) as HTMLElement).style.display = 'block';

      }

      if (this.myRole == this.TAB_APPROVER) {
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf<HTMLElement>)[0].style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf<HTMLElement>)[1].style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-' + i) as HTMLElement).style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-head-' + i) as HTMLElement).style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf<HTMLElement>)[0].style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf<HTMLElement>)[1].style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-' + i) as HTMLElement).style.display = 'none';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-head-' + i) as HTMLElement).style.display = 'none';
      } else {
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf<HTMLElement>)[0].style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-date') as NodeListOf<HTMLElement>)[1].style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-' + i) as HTMLElement).style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-date-head-' + i) as HTMLElement).style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf<HTMLElement>)[0].style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelectorAll('.col-tags') as NodeListOf<HTMLElement>)[1].style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-' + i) as HTMLElement).style.display = 'table-cell';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('.col-tags-head-' + i) as HTMLElement).style.display = 'table-cell';
      }


    }

    if (filter == "all") {

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-all') as HTMLInputElement).checked = true;

    }


    if (filter == "mapped") {

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-mapped') as HTMLInputElement).checked = true;

    }

    if (filter == "unmapped") {

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-filter-unmapped') as HTMLInputElement).checked = true;

    }

  }

  getIndexFromId = (id: string) => {

    for (var i = 0; i < this.unmappedEvents.length; i++) {

      if (this.unmappedEvents[i].id == id) {
        return i;
      }

    }

    return -1;
  }

  prepopulateMapping = (mappings: any) => {

    //console.log('mappings5', mappings, this.mappedValuesUsers);

    if (mappings == null) {
      return;
    }

    for (var i = 0; i < Object.keys(mappings.duedates).length; i++) {
      const eventId = Object.keys(mappings.duedates)[i];
      const index = this.getIndexFromId(eventId);
      if (index >= 0) {
        this.mappedValuesDueDates[index] = mappings.duedates[eventId];
      }
    }

    for (var i = 0; i < Object.keys(mappings.tags).length; i++) {
      const eventId = Object.keys(mappings.tags)[i];
      const index = this.getIndexFromId(eventId);
      if (index >= 0) {
        this.mappedValuesTags[index] = mappings.tags[eventId];
      }
    }

    for (var i = 0; i < Object.keys(mappings.users).length; i++) {
      const eventId = Object.keys(mappings.users)[i];
      const index = this.getIndexFromId(eventId);
      //console.log('mapping users', index);
      if (index >= 0) {
        this.mappedValuesUsers[index] = mappings.users[eventId];
      }
    }

    //console.log(this.mappedValuesDueDates);
    //console.log(this.mappedValuesTags);
    //console.log(this.mappedValuesUsers);

    for (var i = 0; i < this.unmappedEvents.length; i++) {

      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-div-' + i) as HTMLDivElement)!.innerHTML = (this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : "";
      ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-override-date-input-' + i) as HTMLInputElement)!.value = (this.mappedValuesDueDates[i] != null && this.mappedValuesDueDates[i] != "") ? this.mappedValuesDueDates[i] : "";

      if (this.mappedValuesTags[i] != null) {
        var html = '';
        for (var j = 0; j < this.mappedValuesTags[i].length; j++) {
          html += this.mappedValuesTags[i][j];
          if (j < (this.mappedValuesTags[i].length - 1)) {
            html += ',';
          }
        }
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-tags-' + i) as HTMLDivElement)!.innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-' + i) as SfIForm)!.preselectedValues = JSON.stringify(this.mappedValuesTags[i]);
        //((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-tags-'+i) as SfIForm)!.populatePreselected();
      }


      if (this.mappedValuesUsers[i] != null) {
        html = '';
        for (var j = 0; j < this.mappedValuesUsers[i].length; j++) {
          html += this.mappedValuesUsers[i][j];
          if (j < (this.mappedValuesUsers[i].length - 1)) {
            html += ',';
          }
        }
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-div-users-' + i) as HTMLDivElement)!.innerHTML = '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + html + '" minLength="20"></sf-i-elastic-text>';
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-' + i) as SfIForm)!.preselectedValues = JSON.stringify(this.mappedValuesUsers[i]);
        //((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-input-users-'+i) as SfIForm)!.populatePreselected();
      }

      if (this.mappedValuesUsers[i] != null) {
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + i) as HTMLDivElement).innerHTML = '<span class="material-icons color-done">check_circle</span>';
      } else {
        ((this._SfMappingContainer as HTMLDivElement).querySelector('#row-unmapped-status-' + i) as HTMLDivElement).innerHTML = '<span class="material-icons color-pending">pending</span>';
      }


    }

    this.calculateAndShowSummary();

  }

  clearAllMappingSelections = () => {

    const inputArr = (this._SfMappingContainer as HTMLDivElement).querySelectorAll('.input-checkbox') as NodeListOf<HTMLInputElement>;
    for (var i = 0; i < inputArr.length; i++) {

      if (inputArr[i].checked) {
        inputArr[i].checked = false;
        inputArr[i].dispatchEvent(new Event('change'));
      }

    }

  }

  clearAllCalendars = () => {

    //(this._SfCalendarContainer as HTMLDivElement).innerHTML = "";
    (this._SfStreamContainer as HTMLDivElement).innerHTML = "";
    (this._SfUpcomingContainer as HTMLDivElement).innerHTML = "";
    (this._SfThisContainer as HTMLDivElement).innerHTML = "";
    (this._SfPastContainer as HTMLDivElement).innerHTML = "";
    (this._SfCustomContainer as HTMLDivElement).innerHTML = "";
    (this._SfAdhocContainer as HTMLDivElement).innerHTML = "";
    (this._SfRegisterContainer as HTMLDivElement).innerHTML = "";

  }

  transformMappingsForUpload = (mapping: any) => {

    const duedates = mapping.duedates;
    const tags = mapping.tags;
    const users = mapping.users;

    const transformedDuedates: any = {};
    const transformedTags: any = {};
    const transformedUsers: any = {};

    //console.log('unmappedevents[i] duedates',duedates);

    for (var i = 0; i < Object.keys(duedates).length; i++) {

      //console.log('unmappedevents[i]',i,this.unmappedEvents[i]);

      const index = Object.keys(duedates)[i];
      const eventId = this.unmappedEvents[i].id;
      transformedDuedates[eventId] = duedates[index];

    }

    for (var i = 0; i < Object.keys(tags).length; i++) {

      const index = Object.keys(tags)[i];
      const eventId = this.unmappedEvents[i].id;
      transformedTags[eventId] = tags[index];

    }

    for (var i = 0; i < Object.keys(users).length; i++) {

      const index = Object.keys(users)[i];
      const eventId = this.unmappedEvents[i].id;
      transformedUsers[eventId] = users[index];

    }

    return {
      duedates: transformedDuedates,
      tags: transformedTags,
      users: transformedUsers
    }

  }

  uploadTriggersMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'triggers', statuteids);
  }

  uploadInternalControlsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'internalcontrols', statuteids);
  }

  uploadReportedLocationsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'reportedlocations', statuteids);
  }

  uploadAlertSchedulesMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'alertschedules', statuteids);
  }

  uploadActivationsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'activations', statuteids);
  }

  uploadInvalidationsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'invalidations', statuteids);
  }

  uploadDuedatesMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'duedates', statuteids);

  }

  uploadExtensionsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'extensions', statuteids);

  }

  uploadApproversMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'approvers', statuteids);

  }

  uploadFunctionHeadsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'functionheads', statuteids);
  }

  uploadMakerCheckersMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'makercheckers', statuteids);
  }

  uploadDocsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'docs', statuteids);

  }

  uploadAuditorsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'auditors', statuteids);

  }

  uploadViewersMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'viewers', statuteids);

  }

  uploadReportersMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'reporters', statuteids);
  }

  uploadTagsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'tags', statuteids);
  }

  uploadFunctionsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'functions', statuteids);
  }

  uploadLocationsMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'locations', statuteids);
  }

  uploadEntitiesMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'entities', statuteids);
  }

  uploadCountriesMapping = async (data: any, statuteids: string[]) => {
    await this.uploadOnboardingMapping(data, 'countries', statuteids);
  }

  uploadMappedGovUsers = async (data: any) => {

    console.log('uploading..', data);

    let url = "https://" + this.apiId + "/updatemappedgovusers";

    let body: any = {
      "projectid": this.projectId,
      "presigned": true
    }
    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      let jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "key": jsonRespose.key
      }
      console.log('body', body);
      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse gov users', jsonRespose);
      return jsonRespose;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadMappedGovLocations = async (data: any) => {

    console.log('uploading..', data);

    let url = "https://" + this.apiId + "/updatemappedgovlocations";

    let body: any = {
      "projectid": this.projectId,
      "presigned": true
    }
    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      let jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "key": jsonRespose.key
      }
      console.log('body', body);
      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse gov locations', jsonRespose);
      return jsonRespose;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadMappedSuspense = async (data: any, year: string) => {

    //console.log('uploading..', data);

    let url = "https://" + this.apiId + "/updatemappedsuspense";

    // const body = {
    //   "projectid": this.projectId,
    //   "data": JSON.stringify(data),
    //   "year": year
    // }
    let body: any = {
      "projectid": this.projectId,
      "presigned": true,
      "year": year
    }
    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      let jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "key": jsonRespose.key,
        "year": year
      }
      console.log('body', body);
      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse suspense', jsonRespose);
      return jsonRespose;
    }
    // let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    // let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    // this._SfLoader.innerHTML = '';
    // if (xhr.status == 200) {

    //   const jsonRespose = JSON.parse(xhr.responseText);
    //   console.log('jsonResponse suspense', jsonRespose);
    //   return jsonRespose;
    // } 
    else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadOnboardingMapping = async (data: any, onboardingstep: string, statuteids: string[]) => {

    //console.log('uploading..', data);

    let url = "https://" + this.apiId + "/updatemappedonboarding1";

    // const body = { 
    //   "projectid": this.projectId, 
    //   "data": JSON.stringify(data),
    //   "onboardingstep": onboardingstep,
    // }

    let body: any = {
      "projectid": this.projectId,
      "presigned": true,
      "onboardingstep": onboardingstep,
      "statuteids": statuteids
    }

    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "key": jsonRespose.key,
        "onboardingstep": onboardingstep,
        "statuteids": statuteids
      }
      console.log('body', body);
      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadToPresignedUrl = async (data: any, url: string) => {
    const xhr: any = (await this.prepareXhrPresigned(data, url, this._SfLoader)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

    }
  }

  uploadCompliancesMapping = async (data: any, mappedstatutes: Array<any>) => {

    console.log('uploading..', data, mappedstatutes);
    let url = "https://" + this.apiId + "/updatemappedcompliances1";
    let statuteids = []
    for (let statuteObj of mappedstatutes) {
      statuteids.push(statuteObj.id);
    }
    let body: any = {
      "projectid": this.projectId,
      "presigned": true,
    }

    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "statuteids": statuteids,
        "key": jsonRespose.key
      }
      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadStatutesMapping = async (data: any) => {

    // console.log('uploading..', data);
    let url = "https://" + this.apiId + "/updatemappedstatutes1";

    // var searchstring = '';

    // for (var i = 0; i < data.mappings.length; i++) {

    //   // const dataItem = JSON.parse(data.mappings[i].data);
    //   const dataId = data.mappings[i].id;
    //   // console.log(dataItem[3])
    //   if (data.mappings[i].selected == true) {
    //     searchstring += dataId;
    //     // if (i < (data.mappings.length - 1)) {
    //       searchstring += '|';
    //     // }
    //   }

    // }
    // if(searchstring.length > 0){
    //   searchstring = searchstring.slice(0, -1);
    // }
    // const bodyUpload = { 
    //   "projectid": this.projectId, 
    //   // "data": JSON.stringify(data),
    //   "compliancessearchstring": searchstring
    // }

    // console.log("upload body", bodyUpload)
    // return;

    let body: any = {
      "projectid": this.projectId,
      "presigned": true,
    }

    let authorization: any = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      await this.uploadToPresignedUrl(data, jsonRespose.signedUrl)

      body = {
        "projectid": this.projectId,
        "key": jsonRespose.key,
      }

      authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      xhr = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadUnTriggerEvent = async (untrigger: any) => {

    let url = "https://" + this.apiId + "/untriggerevent1";

    const body = untrigger;

    console.log('uploading...', body);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Your trigger has been retracted successfully. The changes will reflect in your calendar shortly.");
      setTimeout(() => {
        this.clearMessages();
      }, 3000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 2000);
    }

  }

  uploadTriggerMyEvent = async (complianceid: string, message: string, countryname: string, entityname: string, locationname: string, statute: string, subcategory: string, suspenseVal: any = {}) => {

    let url = "https://" + this.apiId + "/triggermyevent";

    const body = {
      "projectid": this.projectId,
      "complianceid": complianceid,
      "message": message,
      "userid": this.userProfileId,
      "username": this.userName,
      "countryname": countryname,
      "entityname": entityname,
      "locationname": locationname,
      "statute": statute,
      "subcategory": subcategory,
      "suspenseval": suspenseVal
    }

    console.log('uploading...', body);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Feedback sent successfully!");
      setTimeout(() => {
        this.clearMessages();
      }, 5000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 3000);
    }

  }

  uploadAdHocCheckTime = async (showSuccess: boolean = true) => {

    let url = "https://" + this.apiIdDashboard + "/updateadhocchecktime";

    const body = {
      "projectid": this.projectId,
      "userid": this.userProfileId
    }

    console.log('uploading...', body);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse sync', jsonRespose);
      if (showSuccess) {
        this.setSuccess("AdHoc Questions reviewed for this month.");
        setTimeout(() => {
          this.clearMessages();
        }, 3000);
      }
      Util.putUserAdhocCheckTime(jsonRespose.adhocCheckTime)
      this.loadMode();
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 10000);
    }

  }

  uploadTriggerEvent = async (triggeredCompliances: any) => {

    let url = "https://" + this.apiId + "/triggerevent2";

    const body = {
      "projectid": this.projectId,
      "triggers": triggeredCompliances
    }

    console.log('uploading...', body);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Your trigger request is registered successfully. The associated compliances will be available in your calendar shortly.");
      setTimeout(() => {
        this.clearMessages();
      }, 3000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 10000);
    }

  }

  uploadAudit = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, approved: any, module: string = "compliance") => {
    let url = "https://" + this.apiId + "/uploadaudit1";

    const body = {
      "mmddyyyy": mmddyyyy,
      "projectid": this.projectId,
      "type": "audit",
      "eventid": eventid,
      "comments": comments,
      "approved": approved,
      "entityid": entityId,
      "locationid": locationId,
      "userid": this.userProfileId,
      "username": this.userName,
      "module": module
    }
    let retValue = true;
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Audit report uploaded successfully!");
      setTimeout(() => {
        this.clearMessages()
        // this.showChosenMapping();
        // this.fetchEventMap();
        // if(this.myRole == this.TAB_REPORTER) {
        //   this.renderMappingTabs(this.TAB_REPORTER);
        // } else {
        //   this.renderMappingTabs(this.TAB_APPROVER);
        // }
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      retValue = false;
    }
    return retValue;
  }
  uploadAuditsBulk = async (bulkBody: any) => {
    let url = "https://" + this.apiId + "/uploadauditsbulk2";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete.");
      setTimeout(() => {
        this.clearMessages()
      }, 10000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }
  }

  uploadReview = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, approved: any, module: string = "compliance") => {
    let url = "https://" + this.apiId + "/uploadreview1";
    if (module == "rcmresource" && this.apiId2 != null) {
      url = "https://" + this.apiId2 + "/uploadreview1";
    }
    const body = {
      "mmddyyyy": mmddyyyy,
      "projectid": this.projectId,
      "type": "review",
      "eventid": eventid,
      "comments": comments,
      "approved": approved,
      "entityid": entityId,
      "locationid": locationId,
      "userid": this.userProfileId,
      "username": this.userName,
      "module": module
    }
    let retValue = true;
    console.log('uploading review', body);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Report uploaded successfully!");
      setTimeout(() => {
        this.clearMessages()
        // this.showChosenMapping();
        // this.fetchEventMap();
        // if(this.myRole == this.TAB_REPORTER) {
        //   this.renderMappingTabs(this.TAB_REPORTER);
        // } else {
        //   this.renderMappingTabs(this.TAB_APPROVER);
        // }
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
      retValue = false;
    }
    return retValue;
  }
  uploadReportsReviewsBulk = async (bulkBody: any) => {
    let url = "https://" + this.apiId + "/uploadreportsreviewsbulk2";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete.");
      setTimeout(() => {
        this.clearMessages()
      }, 10000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
    }
  }
  uploadReviewsBulk = async (bulkBody: any) => {
    let url = "https://" + this.apiId + "/uploadreviewsbulk2";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete.");
      setTimeout(() => {
        this.clearMessages()
      }, 10000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
    }
  }

  uploadReport = async (entityId: string, locationId: string, mmddyyyy: string, eventid: string, comments: string, doc: string, docs: any, event: any, reportformatvalues: string = "", reportformatschema: string = "", module: string = "compliance", percentage: string = "100", makercheckers: any, reportedlocations: string = "") => {
    let url = "https://" + this.apiId + "/uploadreport";
    if (module == "rcmresource" && this.apiId2 != null) {
      url = "https://" + this.apiId2 + "/uploadreport";
    }
    let yearStr = this.getFinancialYear(mmddyyyy)
    let body = {
      "mmddyyyy": mmddyyyy,
      "projectid": this.projectId,
      "type": "report",
      "eventid": eventid,
      "comments": comments,
      "dateofcompletion": doc,
      "percentage": percentage,
      "entityid": entityId,
      "locationid": locationId,
      "event": event == null ? null : JSON.stringify(event),
      "docs": JSON.stringify(docs),
      "username": this.userName,
      "reportformatvalues": reportformatvalues,
      "reportformatschema": reportformatschema,
      "userid": this.userProfileId,
      "userrole": this.myRole,
      "year": yearStr,
      "module": module,
      "makercheckers": makercheckers,
      "reportedlocations": reportedlocations
    }

    console.log('reportingbody', body);
    let retValue = true;
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Report uploaded successfully!");
      setTimeout(() => {
        this.clearMessages()
        // this.showChosenMapping();
        // this.fetchEventMap();
        // if(this.myRole == this.TAB_REPORTER) {
        //   this.renderMappingTabs(this.TAB_REPORTER);
        // } else {
        //   this.renderMappingTabs(this.TAB_APPROVER);
        // }
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      console.log()
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
      retValue = false;
    }
    return retValue;
  }

  uploadReportsBulk = async (bulkBody: any, showSuccess: boolean = true) => {
    let url = "https://" + this.apiId + "/uploadreportsbulk2"

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(bulkBody, url, this._SfLoader, authorization)) as any;
    if (showSuccess) {
      this._SfLoader.innerHTML = '';
    }
    if (xhr.status == 200) {
      if (showSuccess) {
        this.setSuccess("Bulk upload initiated. Processing will occur in the background, and you'll receive an email notification once it's complete.");
        setTimeout(() => {
          this.clearMessages()
        }, 10000);
      }

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
    }
  }

  sendSuggestions = async (eventid: string, eventdelta: any) => {
    let url = "https://" + this.apiIdRCMResources + "/sendsuggestions";

    const body = {
      "projectid": this.projectId,
      "objectid": eventid,
      "objectdelta": JSON.stringify(eventdelta),
    }
    let retValue = true;
    console.log('uploading suggestion', body);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Suggestion sent successfully!");
      setTimeout(() => {
        this.clearMessages()
        // this.showChosenMapping();
        // this.fetchEventMap();
        // if(this.myRole == this.TAB_REPORTER) {
        //   this.renderMappingTabs(this.TAB_REPORTER);
        // } else {
        //   this.renderMappingTabs(this.TAB_APPROVER);
        // }
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 3000);
      retValue = false;
    }
    return retValue;
  }

  exportRegister = async () => {

    let url = "https://" + this.apiId + "/scheduleregisterexportjob";

    const body = {
      "projectid": this.projectId,
      "userid": this.userProfileId,
      "role": this.myRole,
      "admin": (this.showRegisterExport && this.showRegisterExport == "true")
    }

    console.log('exporting Register...', body);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Register export started successfully! You will get an email with your register landscape.");
      setTimeout(() => {
        this.clearMessages();
      }, 5000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages()
      }, 3000);
    }
  }


  uploadMapping = async () => {

    let url = "https://" + this.apiId + "/mapevents";

    const mapping = this.transformMappingsForUpload({
      duedates: this.mappedValuesDueDates,
      tags: this.mappedValuesTags,
      users: this.mappedValuesUsers
    });

    const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "role": this.myRole, "mapping": JSON.stringify(mapping) }
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      this.setSuccess("Mapping uploaded successfully!");
      setTimeout(() => {
        this.clearMessages()
        this.showChosenMapping();
        this.fetchEventMap();
        if (this.myRole == this.TAB_REPORTER) {
          this.renderMappingTabs(this.TAB_REPORTER);
        } else {
          this.renderMappingTabs(this.TAB_APPROVER);
        }
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }

  }

  uploadEvents = async () => {

    let url = "https://" + this.apiId + "/synccalendar";

    const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "compliance": JSON.stringify(this.events) }
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);
      // this.loadMode();
      this.showChosenMapping();
      this.fetchEventMap();
      this.renderMappingTabs(this.TAB_REPORTER);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }
  }

  uploadReprogramTrigger = async (eventid: string, timestamp: string) => {

    let url = "https://" + this.apiId + "/reprogramtrigger";

    const body = { "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "eventid": eventid, "timestamp": timestamp + "" }
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse sync', jsonRespose);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }
  }

  processEvent = (value: any) => {

    //console.log('processing due date', value);
    //console.log('processing due date', value.duedate.replace(/['"]+/g, ''));
    //console.log('processing due date', this.mappings);

    var duedate = value.duedate;

    if (this.mappings != null && this.mappings.duedates != null && this.mappings.duedates[value.id] != null && this.mappings.duedates[value.id] != "") {
      duedate = this.mappings.duedates[value.id];
    }

    const duedateArr = duedate.replace(/['"]+/g, '').split(",") as Array<string>;

    const startMonth = parseInt(this.calendarStartMM);

    for (var i = 0; i < duedateArr.length; i++) {

      const dateArr = duedateArr[i].split("/");
      //console.log('datearr', dateArr);

      if (dateArr[2] == "*") {
        if (dateArr[1] == "*") {

          var j = startMonth;

          while (true) {

            //console.log('processing event',dateArr[2],dateArr[1],j);

            const mmdd = ("0" + j).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2);

            if (this.events == null) {
              this.events = {};
            }
            if (this.events[mmdd] == null) {
              this.events[mmdd] = [];
            }
            (this.events[mmdd] as Array<any>).push(value);

            if (startMonth !== 12) {

              if (j === (startMonth - 1)) {
                break;
              }
            }

            j++;

            if (j === 13) {
              j = 0;
            }

          }

        } else {

          const mmdd = ("0" + (parseInt(dateArr[1]))).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2);

          if (this.events == null) {
            this.events = {};
          }
          if (this.events[mmdd] == null) {
            this.events[mmdd] = [];
          }
          (this.events[mmdd] as Array<any>).push(value);

        }
      } else {

        if ((new Date().getFullYear() + "") == dateArr[2]) {

          const mmdd = ("0" + (parseInt(dateArr[1]))).slice(-2) + "/" + ("0" + dateArr[0]).slice(-2);

          if (this.events == null) {
            this.events = {};
          }
          if (this.events[mmdd] == null) {
            this.events[mmdd] = [];
          }
          (this.events[mmdd] as Array<any>).push(value);

        }


      }

    }

    //console.log('calendar processed', this.calendar);
    //console.log('event processed', this.events);

  }

  renderChosenProject = (events: any = null) => {

    if (events == null) {

      var html = '';

      html += '<div class="lb"></div>';
      html += '<div class="d-flex justify-between align-center">';
      html += '<div class="muted">Calender doesn\'t exist! &nbsp; &nbsp;</div>';
      html += '<button id="button-generate-chosen-project" part="button">Generate</button>';
      html += '</div>';
      html += '<div class="rb"></div>';

      (this._SfContainerChosenProject as HTMLDivElement).innerHTML = html;

      (((this._SfContainerChosenProject as HTMLDivElement) as HTMLDivElement).querySelector('#button-generate-chosen-project') as HTMLButtonElement).addEventListener('click', async () => {
        await this.fetchList();
      });

    } else {

    }

  }

  fetchRcmLockedCompliances = async (lockedCompliances: Array<string>) => {

    let url = "https://" + this.apiId + "/getrcmlockedcompliances";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ data: lockedCompliances }, url, this._SfLoader, authorization)) as any;

    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('lockedcompliances', jsonRespose);

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchCancelOnboardingJob = async (onboardingStep: string) => {
    let url = "https://" + this.apiId + "/cancelonboardingjob";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingStep }, url, this._SfLoader, authorization)) as any;

    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('fetchCancelnboardingJob', jsonRespose);

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }
  }

  fetchGetStoredMapping = async (flow: string) => {
    let url = "https://" + this.apiId + "/getstoredmapping";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "flow": flow }, url, this._SfLoader, authorization)) as any;

    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('fetchGetStoredMapping', jsonRespose);

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }
  }

  fetchUpdateUsermap = async (usermap: any) => {

    let url = "https://" + this.apiIdUsers + "/updatefield";

    this.setSuccess('Updating usermaps, please wait...')

    //console.log('updating usermap', usermap);
    const arrUserIds = Object.keys(usermap);
    for (var i = 0; i < arrUserIds.length; i++) {

      const userId = arrUserIds[i];
      const map = usermap[userId];
      const strMap = JSON.stringify(map).replace(/"/g, '_QUOTES_');
      const body = { id: userId, field: "usermap", value: "\"" + strMap + "\"" };
      //console.log('updating', userId, body, url)
      let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      let xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      if (xhr.status == 200) {

      }

    }

    setTimeout(() => {
      this.clearMessages();
    }, 1000);

  }

  fetchUpdateRcmLock = async (complianceId: string) => {

    let url = "https://" + this.apiId + "/updatercmlock";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "complianceid": complianceId, "locked": true }, url, this._SfLoader, authorization)) as any;

    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('fetchUpdateRcmLock', jsonRespose);

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchDetailProject = async (projectId: string) => {

    let url = "https://" + this.apiIdProjects + "/detail";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "id": projectId }, url, this._SfLoader, authorization)) as any;

    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('searchprojects', jsonRespose);

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchDeleteReview = async (eventId: string, mmddyyyy: string, entityId: string, locationId: string) => {

    let url = "https://" + this.apiId + "/deletereview";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "entityid": entityId, "locationid": locationId, "mmddyyyy": mmddyyyy, "eventid": eventId, }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }


  fetchStatuteDefinitionDetails = async (statuteName: string) => {

    const statuteDetails = await this.fetchSearchStatutes(statuteName);
    console.log('statuteDetails', statuteDetails);

    statuteDetails.values.forEach(async (statute: any) => {
      const nameIndex = (JSON.parse(statute.fields.cols[0]) as Array<string>).indexOf('name');
      const statuteNameFound = JSON.parse(statute.fields.data[0])[nameIndex];
      if (statuteNameFound == statuteName) {
        if (statute.fields.cols[0].indexOf('definitions') >= 0) {
          const definitionsIndex = (JSON.parse(statute.fields.cols[0]) as Array<string>).indexOf('definitions');
          const definitionsFound = JSON.parse(statute.fields.data[0])[definitionsIndex];
          if (definitionsFound.length > 0) {
            console.log(JSON.parse(statute.fields.data[0])[definitionsIndex]);
            const definitionsName = JSON.parse(statute.fields.data[0])[definitionsIndex][0].trim();
            console.log('statute', statute, JSON.parse(statute.fields.cols[0]), nameIndex, statuteNameFound, definitionsFound, definitionsName);
            const definitionDetails = await this.fetchSearchDefinitions(definitionsName);
            definitionDetails.values.forEach(async (definition: any) => {
              const definitionNameIndex = (JSON.parse(definition.fields.cols[0]) as Array<string>).indexOf('name');
              const definitionNameFound = JSON.parse(definition.fields.data[0])[definitionNameIndex];
              if (definitionNameFound == definitionsName) {
                const attachmentIndex = (JSON.parse(definition.fields.cols[0]) as Array<string>).indexOf('attachment');
                const attachmentKey = JSON.parse(definition.fields.data[0])[attachmentIndex][0]
                console.log('definition', definition, attachmentKey);
                (this._SfDetailContainer as HTMLDivElement).querySelector('#container-definition')!.innerHTML = '<div class="m-20"><div part="detail-head"><strong>Definitions</strong></div><button part="button" id="button-show-definition" class="mt-5">View</button></div>';

                ((this._SfDetailContainer as HTMLDivElement).querySelector('#button-show-definition') as HTMLButtonElement)!.addEventListener('click', (_e: any) => {
                  (this._SfDetailContainer as HTMLDivElement).querySelector('#container-definition')!.innerHTML = `<div  class="m-20"><div part="detail-head" class="mb-10"><strong>Definitions</strong></div><sf-i-uploader class="gone" id="sf-i-definitions" max="10" apiid="${this.apiIdUpload}" apiidregion="${this.apiRegionUpload}" allowedextensions="[&quot;jpg&quot;,&quot;png&quot;,&quot;pdf&quot;]" extract="no" mandatory="" mode="view" maximize="yes"></sf-i-uploader></div>`;
                  ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).classList.remove('gone');
                  ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).prepopulatedInputArr = JSON.stringify([attachmentKey]);
                  ((this._SfDetailContainer as HTMLDivElement).querySelector('#sf-i-definitions') as SfIUploader).loadMode();
                });

              }
            });
          }
        }
      }
    });

  }

  fetchSearchDefinitions = async (searchString: string, cursor: string = "") => {

    let url = "https://" + this.apiIdDefinitions + "/listlarge";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('searchstatutes', jsonRespose);

      let newCursor = jsonRespose.cursor;
      let i = 0;

      while (true) {

        url = "https://" + this.apiIdDefinitions + "/listlarge";
        authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
        xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any;
        this._SfLoader.innerHTML = '';
        if (xhr.status == 200) {
          const jsonRespose1 = JSON.parse(xhr.responseText);
          //console.log('found', jsonRespose1.values);
          jsonRespose.values.push(...jsonRespose1.values);
          if (newCursor == jsonRespose1.cursor) {
            break;
          }
          newCursor = jsonRespose1.cursor;
          //console.log('newcursor', i, jsonRespose1.cursor);
          i += jsonRespose1.values.length;
        } else {
          break;
        }
      }


      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchReportFormat = async (reportingContainer: HTMLDivElement, searchName: string, reportformatschema: string = "", reportformatvalues: string = "") => {
    let jsonContentIndex: number;
    let jsonContentFound: string = "";
    if (reportformatschema == "") {
      let reportformats = await this.fetchSearchReportformats(searchName);
      if (reportformats.values == null || reportformats.values.length == 0) {
        return;
      }
      for (let format of reportformats.values) {
        let data = JSON.parse(format.fields.data[0])
        let cols = JSON.parse(format.fields.cols[0])
        if (data[cols.indexOf('name')] == searchName) {
          jsonContentIndex = (JSON.parse(format.fields.cols[0]) as Array<string>).indexOf('jsoncontent');
          jsonContentFound = JSON.parse(format.fields.data[0])[jsonContentIndex];
          break;
        }
      }
    } else {
      jsonContentFound = reportformatschema
    }
    console.log('format found', JSON.parse(jsonContentFound));
    if (jsonContentFound == "") {
      console.log('format not found');
      return;
    }
    if (reportingContainer.querySelector('#report-format-container') != null) {
      reportingContainer.querySelector('#report-format-container')!.innerHTML = `<slot name="reporting"></slot>`;
      console.log('innerhtml', reportingContainer.querySelector('#report-format-container')!.innerHTML);
      (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).name = searchName;
      (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).mode = reportformatvalues != "" ? "edit" : "new";
      (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).flow = "reporting";
      (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).configjson = jsonContentFound;
      if (reportformatvalues != "") {
        (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).prepopulateValJson = reportformatvalues
      }
      (this._SfReporting[0].querySelector('#reporting-format') as SfIReporting).loadMode();
    } else {
      console.log('report format container not found');
    }
  }

  fetchSearchReportformats = async (searchString: string, cursor: string = "") => {

    let url = "https://" + this.apiidReportformats + "/listlarge";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('searchstatutes', jsonRespose);

      let newCursor = jsonRespose.cursor;
      let i = 0;

      while (true) {

        url = "https://" + this.apiidReportformats + "/listlarge";
        authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
        xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any;
        this._SfLoader.innerHTML = '';
        if (xhr.status == 200) {
          const jsonRespose1 = JSON.parse(xhr.responseText);
          //console.log('found', jsonRespose1.values);
          jsonRespose.values.push(...jsonRespose1.values);
          if (newCursor == jsonRespose1.cursor) {
            break;
          }
          newCursor = jsonRespose1.cursor;
          //console.log('newcursor', i, jsonRespose1.cursor);
          i += jsonRespose1.values.length;
        } else {
          break;
        }
      }


      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }


  fetchSearchStatutes = async (searchString: string, cursor: string = "") => {
    console.log('cursor', cursor);
    let url = "https://" + this.apiIdStatutes + "/listlarge";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('searchstatutes', { "searchstring": searchString, "cursor": cursor }, jsonRespose);

      let newCursor = jsonRespose.cursor;
      let i = 0;

      while (true) {

        url = "https://" + this.apiIdStatutes + "/listlarge";
        authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
        xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((i) * 100 / jsonRespose.found) + "") + "%")) as any;
        this._SfLoader.innerHTML = '';
        if (xhr.status == 200) {
          const jsonRespose1 = JSON.parse(xhr.responseText);
          //console.log('found', jsonRespose1.values);
          jsonRespose.values.push(...jsonRespose1.values);
          if (newCursor == jsonRespose1.cursor) {
            break;
          }
          newCursor = jsonRespose1.cursor;
          //console.log('newcursor', i, jsonRespose1.cursor);
          i += jsonRespose1.values.length;
        } else {
          break;
        }
      }


      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchSearchCompliances = async (searchString: string, cursor: string = "", count: number, length: number) => {

    let url = "https://" + this.apiIdCompliances + "/listlarge";
    let authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    let xhr: any = (await this.prepareXhr({ "searchstring": searchString, "cursor": cursor }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      // //console.log(jsonRespose);

      let newCursor = jsonRespose.cursor;
      ////console.log('newcursor', newCursor);

      while (true) {

        url = "https://" + this.apiIdCompliances + "/listlarge";
        authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
        xhr = (await this.prepareXhr({ "searchstring": searchString, "cursor": newCursor }, url, this._SfLoader, authorization, "" + parseInt(((count) * 100 / length) + "") + "%")) as any;

        this._SfLoader.innerHTML = '';
        if (xhr.status == 200) {
          const jsonRespose1 = JSON.parse(xhr.responseText);
          // //console.log('newcursor response', jsonRespose1);
          jsonRespose.values.push(...jsonRespose1.values);
          if (newCursor == jsonRespose1.cursor) {
            break;
          }
          newCursor = jsonRespose1.cursor;
          ////console.log('newcursor', i, jsonRespose1.cursor);
        } else {
          break;
        }

      }

      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchMappedProjects = async () => {

    let url = "https://" + this.apiId + "/getmappedprojects";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "complianceid": this.rcmSelectedCompliance.id }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchOnboardingStatus = async () => {

    let url = "https://" + this.apiId + "/getonboardingstatus";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchGetSignOff = async () => {

    let url = "https://" + this.apiId + "/getsignoff";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchUpdateSignOff = async (signoffText: string, signature: string) => {

    let url = "https://" + this.apiId + "/updatesignoff";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "signofftext": signoffText, "signature": signature, "username": this.userName }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchMappedCompliances = async (statuteids = []) => {

    let url = "https://" + this.apiId + "/getmappedcompliances1";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "statuteids": statuteids }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      var jsResponse = JSON.parse(xhr.responseText);
      let resultPresigned: any = null;
      resultPresigned = {};
      resultPresigned.data = {};
      resultPresigned.data.mappings = await this.fetchPresignedUrl(jsResponse.signedUrlGet);
      console.log(resultPresigned);
      await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete)
      return resultPresigned;

      // const jsonRespose = JSON.parse(xhr.responseText);
      // return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

    // let jsonResponse : any = null;
    // let lastEvaluatedKey : any = 0;

    // do {

    //   //console.log(lastEvaluatedKey);

    //   let url = "https://"+this.apiId+"/getmappedcompliances";
    //   const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    //   const xhr : any = (await this.prepareXhr({"projectid": this.projectId, "lastevaluatedkey": lastEvaluatedKey}, url, this._SfLoader, authorization)) as any;
    //   this._SfLoader.innerHTML = '';
    //   if(xhr.status == 200) {

    //     const jsResponse = JSON.parse(xhr.responseText);
    //     //console.log(jsResponse);

    //     if(jsResponse == null) return;

    //     if(lastEvaluatedKey === 0) {
    //         jsonResponse = {};
    //         jsonResponse.data = {}
    //         jsonResponse.data = jsResponse.data;
    //     } else {
    //       jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings);
    //     }

    //     if(jsResponse.lastEvaluatedKey < 0) break;

    //     lastEvaluatedKey = jsResponse.lastEvaluatedKey;

    //   } else {

    //     const jsonRespose = JSON.parse(xhr.responseText);
    //     this.setError(jsonRespose.error);
    //     break;

    //   }

    // } while(true);

    // return jsonResponse;

  }

  fetchMappedSerializedExtensions = async () => {

    return (await this.fetchSerializedMapping("extensions"));

  }

  fetchMappedSerializedAlertSchedules = async () => {

    return (await this.fetchSerializedMapping("alertschedules"));

  }

  fetchMappedSerializedTriggers = async () => {

    return (await this.fetchSerializedMapping("triggers"));

  }

  fetchMappedSerializedDuedates = async () => {

    return (await this.fetchSerializedMapping("duedates"));

  }

  fetchMappedSerializedApprovers = async () => {

    return (await this.fetchSerializedMapping("approvers"));

  }

  fetchMappedSerializedFunctionheads = async () => {

    return (await this.fetchSerializedMapping("functionheads"));

  }

  fetchMappedSerializedMakerCheckers = async () => {

    return (await this.fetchSerializedMapping("makercheckers"));

  }

  fetchMappedSerializedDocs = async () => {

    return (await this.fetchSerializedMapping("docs"));

  }

  fetchMappedSerializedAuditors = async () => {

    return (await this.fetchSerializedMapping("auditors"));

  }

  fetchMappedSerializedViewers = async () => {

    return (await this.fetchSerializedMapping("viewers"));

  }

  fetchMappedSerializedReporters = async () => {

    return (await this.fetchSerializedMapping("reporters"));

  }

  fetchMappedSerializedTags = async () => {

    return (await this.fetchSerializedMapping("tags"));

  }

  fetchMappedSerializedLocations = async () => {

    return (await this.fetchSerializedMapping("locations"));

  }

  fetchMappedSerializedFunctions = async () => {

    return (await this.fetchSerializedMapping("functions"));

  }

  fetchMappedSerializedEntities = async () => {

    return (await this.fetchSerializedMapping("entities"));

  }

  fetchPresignedUrl = async (url: string) => {
    const xhr: any = (await this.prepareXhrPresignedGet(url, this._SfLoader, 'Downloading')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      const jsResponse = JSON.parse(xhr.responseText);
      console.log('jsResponse', jsResponse);
      return jsResponse;
    }
  }

  fetchPresignedUrlDelete = async (url: string) => {
    const xhr: any = (await this.prepareXhrPresignedDelete(url, this._SfLoader)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      const jsResponse = JSON.parse(xhr.responseText);
      console.log('jsResponse', jsResponse);
      return jsResponse;
    }
  }

  fetchSerializedMapping = async (onboardingstep: string) => {

    const url = "https://" + this.apiId + "/getmappedserializedonboarding";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      var jsResponse = JSON.parse(xhr.responseText);
      let resultPresigned: any = null;
      resultPresigned = {};
      resultPresigned.data = {};
      resultPresigned.data.mappings = await this.fetchPresignedUrl(jsResponse.signedUrlGet);
      console.log(resultPresigned);
      await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete)
      return resultPresigned;

      // if(jsResponse != null && jsResponse.lastEvaluatedKey == null) {

      //   jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings);

      //   break;
      // } else {

      //   if(jsonResponse == null) {

      //     jsonResponse = {};
      //     jsonResponse.data = {}
      //     jsonResponse.data = jsResponse.data;

      //   } else {

      //     jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings);

      //   }
      //   lastEvaluatedKey = jsResponse.lastEvaluatedKey;
      // }

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchSerializedPartByPart = async (url: string) => {

    let jsonResponse: any = null;
    let lastEvaluatedKey: any = null;

    do {

      //console.log(lastEvaluatedKey);

      const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "lastevaluatedkey": lastEvaluatedKey }, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      if (xhr.status == 200) {

        const jsResponse = JSON.parse(xhr.responseText);
        //console.log(jsResponse);
        if (jsResponse != null && jsResponse.lastEvaluatedKey == null) {

          jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings);

          break;
        } else {

          if (jsonResponse == null) {

            jsonResponse = {};
            jsonResponse.data = {}
            jsonResponse.data = jsResponse.data;

          } else {

            jsonResponse.data.mappings.mappings.push(...jsResponse.data.mappings.mappings);

          }
          lastEvaluatedKey = jsResponse.lastEvaluatedKey;
        }

      } else {
        if (xhr.status == 401) {
          let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
          this.dispatchEvent(changeEvent);
        }
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);

      }

    } while (true);

    //console.log(jsonResponse);
    return jsonResponse;

  }

  fetchMappedSerializedCountries = async () => {

    // return (await this.fetchSerializedPartByPart("https://"+this.apiId+"/getmappedserializedcountries"));
    return (await this.fetchSerializedMapping("countries"));

  }

  fetchMappedTriggers = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('triggers', statuteids));

  }

  fetchMappedInternalControls = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('internalcontrols', statuteids));

  }

  fetchMappedReportedLocations = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('reportedlocations', statuteids));

  }

  fetchMappedAlertSchedules = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('alertschedules', statuteids));

  }

  fetchMappedActivations = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('activations', statuteids));

  }

  fetchMappedInvalidations = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('invalidations', statuteids));

  }

  fetchMappedExtensions = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('extensions', statuteids));

  }

  fetchMappedDuedates = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('duedates', statuteids));

  }

  fetchMappedReporters = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('reporters', statuteids));

  }

  fetchMappedApprovers = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('approvers', statuteids));

  }

  fetchMappedFunctionHeads = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('functionheads', statuteids));

  }

  fetchMappedMakerCheckers = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('makercheckers', statuteids));

  }

  fetchMappedDocs = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('docs', statuteids));

  }

  fetchMappedAuditors = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('auditors', statuteids));

  }

  fetchMappedViewers = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('viewers', statuteids));

  }

  fetchMappedTags = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('tags', statuteids));

  }

  fetchMappedLocations = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('locations', statuteids));

  }

  fetchMappedFunctions = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('functions', statuteids));
  }

  fetchMappedEntities = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('entities', statuteids));
  }

  fetchMappedCountries = async (statuteids = []) => {

    return (await this.fetchMappedOnboarding('countries', statuteids));

  }

  fetchMappedOnboarding = async (onboardingstep: string, statuteids: string[]) => {

    const url = "https://" + this.apiId + "/getmappedonboarding1";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep, "statuteids": statuteids }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      var jsResponse = JSON.parse(xhr.responseText);
      let resultPresigned: any = null;
      resultPresigned = {};
      resultPresigned.data = {};
      let tempObj = await this.fetchPresignedUrl(jsResponse.signedUrlGet)
      let tempArr = [];
      for (let statuteid of statuteids) {
        for (let foundObjId of Object.keys(tempObj[statuteid] ?? [])) {
          let tempPushObj = tempObj[statuteid][foundObjId];
          tempPushObj.id = foundObjId.split(';')[foundObjId.split(';').length - 1];
          tempPushObj.statuteid = statuteid;
          tempArr.push(tempPushObj);
        }
      }
      // resultPresigned.data.mappings = (tempObj.mappings != null) ? tempObj : { mappings: [] };
      resultPresigned.data.mappings = tempArr;
      console.log('resultPresigned onboarding1', tempObj);
      console.log('resultPresigned onboarding', resultPresigned);
      // await this.fetchPresignedUrlDelete(jsResponse.signedUrlDelete)
      return resultPresigned;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchLocaltions = async () => {

    let cursor = "";
    let arrList: any = [];
    do {
      const url = "https://" + this.apiIdTags + "/listlarge";
      const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      const xhr: any = (await this.prepareXhr({ "searchstring": this.projectName + "&Location", "cursor": cursor }, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';
      if (xhr.status == 200) {

        var jsResponse = JSON.parse(xhr.responseText);
        console.log('response', jsResponse)
        arrList = [...arrList, ...jsResponse.values]
        if (jsResponse.cursor == cursor) {
          break;
        }
        cursor = jsResponse.cursor
      } else {
        if (xhr.status == 401) {
          let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
          this.dispatchEvent(changeEvent);
        }
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
        break;
      }
    } while (cursor != "" && cursor != null)
    return arrList
  }

  fetchMappingCount = async (onboardingstep: string) => {

    const url = "https://" + this.apiId + "/getmappedonboardingcount";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "onboardingstep": onboardingstep }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      var jsResponse = JSON.parse(xhr.responseText);
      return jsResponse;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }

  }

  fetchUpdatedCompliances = async (nextBackwardToken: string = "") => {

    let url = "https://" + this.apiIdCompliances + "/logs";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "nextBackwardToken": nextBackwardToken }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchMappedStatutes = async () => {

    let url = "https://" + this.apiId + "/getmappedstatutes1";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchMappedStatutesList = async () => {

    let url = "https://" + this.apiId + "/getmappedstatuteslist";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose.data;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchCreateRcmJob = async (complianceid: string, data: any, triggerDate: string, triggerMessage: string, projects: any) => {

    data.trigger = {};
    data.trigger.date = triggerDate;
    data.trigger.message = triggerMessage;
    data.projects = [];
    data.projects.push(...projects)

    let url = "https://" + this.apiId + "/creatercmjob";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "complianceid": complianceid, "data": data }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchRcmNotifications = async (projectid: string) => {

    let url = "https://" + this.apiId + "/getrcmnotifications";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": projectid }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchRcmJobs = async (complianceid: string) => {

    let url = "https://" + this.apiId + "/getrcmjobs";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "complianceid": complianceid }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }


  fetchCalendarJobs = async () => {

    let url = "https://" + this.apiId + "/getcalendarjobs";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchExternalMapping = async () => {

    let url = "https://" + this.apiId + "/getexternalmapping";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  deleteFromSuspense = async (suspenseKey: any, year: string) => {
    let url = "https://" + this.apiId + "/deletefromsuspense";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "eventid": suspenseKey.split(';')[2], "entityid": suspenseKey.split(';')[0], "locationid": suspenseKey.split(';')[1], "year": year };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('jsonResponse', jsonResponse);
      return jsonResponse;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  markReviewed = async (suspenseKey: any, year: string, review: boolean) => {
    let url = "https://" + this.apiId + "/markreviewed";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "eventid": suspenseKey.split(';')[2], "entityid": suspenseKey.split(';')[0], "locationid": suspenseKey.split(';')[1], "year": year, "mark": review };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('jsonResponse', jsonResponse);
      return jsonResponse;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  fetchMappedGovUsersList = async () => {

    let url = "https://" + this.apiId + "/getmappedgovuserslist";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));

    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      return retData ?? {};

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchMappedGovLocationsList = async () => {

    let url = "https://" + this.apiId + "/getmappedgovlocationslist";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));

    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      return retData ?? {};

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchSuspenseList = async (year: string = "") => {

    let url = "https://" + this.apiId + "/getsuspenselist";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    if (year == "") {
      year = this.getCurrentYearGeneric();
    }
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "year": year }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      let retData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      console.log('retData', retData);
      return retData ?? {};

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);

    }

  }

  fetchDetail = async (value: any) => {

    const body: any = this.getApiBodyList();
    body.id = value;
    //console.log('detail', value, body);
    let url = "https://" + this.apiIdDetail + "/" + this.apiMethodDetail;

    //console.log('fetch events detail url', url);
    //console.log('fetch events detail body', body);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log('jsonResponse fetch events detail', jsonRespose.data.value.duedate);
      this.processEvent(jsonRespose.data.value)

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
    }

  }

  fetchGetMappedCalendar = async (year: string) => {

    // let url = "https://"+this.apiId+"/getmappedcalendar";
    // let url = "https://3mefupehxkw4pwsq3oyk7lf2pq0pisdx.lambda-url.us-east-1.on.aws/schedulegetcalendarjob";
    let url = "https://" + this.apiId + "/schedulegetcalendarjob";
    const body: any = { "projectid": this.projectId, "year": year };
    if (this.contractStartDate != "") {
      body.contractstartdate = this.contractStartDate;
    }
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      return jsonRespose;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      return jsonRespose;

    }

  }

  sleepFunction = async (ms: number) => {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  renderAppropriateStream = (startDate: string, endDate: string, showGraph: boolean = false, showBackgroundButton: boolean = false) => {
    if (startDate == "" && endDate == "") this.renderCalendar(); // yearly

    if (this.selectedTab == this.TAB_STREAM) {
      this.renderStream(parseInt(this.currentColumnIndex), showGraph, showBackgroundButton);
    }
    // if(this.selectedTab == this.TAB_UPCOMING) {
    //   this.renderUpcoming(parseInt(this.currentColumnIndex), false);
    // }
    if (this.selectedTab == this.TAB_THIS) {
      this.renderThis(parseInt(this.currentColumnIndex), showGraph, showBackgroundButton);
    }
    if (this.selectedTab == this.TAB_CUSTOM) {
      this.processDateSelection((this._SfCustomContainer as HTMLDivElement), false, showBackgroundButton)
    }
    // if(this.selectedTab == this.TAB_PAST) {
    //   this.renderPast(parseInt(this.currentColumnIndex), false);
    // }
  }

  fetchRegisters = async (searchString: string = "", meta: string = "", selectedCountry: string = "", selectedStatute: string = "") => {

    let path = "";

    path = "getallfunctionevents1";

    let url = "https://" + this.apiId + "/" + path;

    let locationId = "";
    let entityId = "";

    if (this.locationId != null && this.locationId.length > 2) {
      locationId = this.locationId;
    }

    if (this.entityId != null && this.entityId.length > 2) {
      entityId = this.entityId;
    }

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "searchstring": searchString, "locationid": locationId, "entityid": entityId, meta: meta, country: selectedCountry, statute: selectedStatute };

    //console.log('urlbody', url, urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      const registers = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      this.registerFilters = {};
      // this.renderAppropriateStream(startDate, endDate);
      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      return registers;

    } else if (xhr.status == 401) {
      let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
      this.dispatchEvent(changeEvent);
    }

  }

  markUnderstoodBulk = async (complianceids: any, userid: string, review: number) => {
    let url = "https://" + this.apiId + "/markunderstoodbulk";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "eventids": complianceids, "userid": userid, "mark": review };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('jsonResponse', jsonResponse);
      return jsonResponse;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  markUnderstood = async (complianceid: any, userid: string, review: number) => {
    let url = "https://" + this.apiId + "/markunderstood";

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "eventid": complianceid, "userid": userid, "mark": review };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('jsonResponse', jsonResponse);
      this.setSuccess('Review saved')
      setTimeout(() => {
        this.clearMessages()
      }, 3000)
      return jsonResponse;
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  renderWithFeatures = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => {
    this.selectedFeatures = Util.getFeatures();
    for (let feature of this.selectedFeatures) {
      if (this.getFeatures().indexOf(feature) < 0) {
        this.selectedFeatures = ['compliances']
        break;
      }
    }
    this.events = []
    console.log('rendering and fetching', startDate, endDate, searchString, list, month)
    if (this.selectedFeatures.indexOf('compliances') >= 0) {
      this.fetchAndYearlyRenderUserCalendar_2(startDate, endDate, searchString, list, month, year)
    } else if (this.selectedFeatures.indexOf('notices') >= 0) {
      this.fetchAndRenderNotices(startDate, endDate, searchString, list, month, year);
    } else if (this.selectedFeatures.indexOf('contracts') >= 0) {
      this.fetchAndRenderContracts(startDate, endDate, searchString, list, month, year);
    } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
      this.fetchAndRenderLicenses(startDate, endDate, searchString, list, month, year);
    } else if (this.selectedFeatures.indexOf('rcmresources') >= 0) {
      this.fetchAndRenderRCMResources(startDate, endDate, searchString, list, month, year);
    }
  }
  fetchAndYearlyRenderUserCalendar_2 = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY, flagReporting: boolean = false) => {

    let path = "", view = "";
    this.sdate = startDate;
    this.edate = endDate;
    this.suspenseCount = this.suspenseFlag ? this.suspenseCount : 0;
    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    path = "getallcountryevents6";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }


    let url = "https://" + this.apiId + "/" + path;

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month, "suspense": this.suspenseFlag, "contractstartdate": this.contractStartDate, flagreporting: flagReporting };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }
    if (this.showReportedLocations) {
      urlBody["reportedlocations"] = "yes";
    }

    //console.log('urlbody', urlBody);
    this.getallcountryevetsParams = JSON.stringify(urlBody);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      if (JSON.stringify(urlBody) == this.getallcountryevetsParams) {
        let tempEvents = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
        for (let mmdd of Object.keys(tempEvents)) {
          tempEvents[mmdd] = tempEvents[mmdd].sort((a: any, b: any) => {
            return a.obligationtitle.localeCompare(b.obligationtitle);
          });
        }
        this.events = tempEvents;
      }
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      if (JSON.stringify(urlBody) == this.getallcountryevetsParams) {
        this.lastupdated = Util.getDateTimeStrings(new Date().getTime())
        this.suspenseCount = this.suspenseFlag ? this.suspenseCount : (jsonRespose.suspensecount ?? 0);
        console.log('rendering appropriate string', list, this.selectedTab);
        this.renderAppropriateStream(startDate, endDate, true);
        this.fetchBulkReportingData();
      }
      // if(this.selectedFeatures.indexOf('notices') >= 0){
      //   this.fetchAndRenderNotices(startDate, endDate);
      // }
      // this.events = {}
      // this.events = {...JSON.parse(JSON.stringify(jsonRespose.data.events))};

      // let lastEvaluatedKey = jsonRespose.lastEvaluatedKey;

      // //console.log('lastevaluatedkey0', lastEvaluatedKey);

      // var recallCount = 0;

      // do {

      //   if(recallCount > 3) break;

      //   if(lastEvaluatedKey != null) {

      //     let urlBody2 : any = {"projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": lastEvaluatedKey, "sdate": sDate, "edate": eDate, "view": view, "year": this.calendarStartYYYY}

      //     if(searchString.length > 0) {
      //       urlBody2["searchstring"] = searchString;
      //     }

      //     const xhr2 : any = (await this.prepareXhr(urlBody2, url, this._SfLoader, authorization)) as any;
      //     this._SfLoader.innerHTML = '';

      //     if(xhr2.status == 200) {

      //       const jsonRespose2 = JSON.parse(xhr2.responseText);

      //       for(var i = 0; i < Object.keys(JSON.parse(JSON.stringify(jsonRespose2.data.events))).length; i++) {

      //         const key = Object.keys(JSON.parse(JSON.stringify(jsonRespose2.data.events)))[i];
      //         this.events[key].push(...JSON.parse(JSON.stringify(jsonRespose2.data.events))[key]);

      //       }

      //       //console.log('consolidated', this.events)

      //       //console.log(jsonRespose2);

      //       this.renderAppropriateStream(startDate, endDate);

      //       lastEvaluatedKey = jsonRespose2.lastEvaluatedKey;
      //       //console.log('lastevaluatedkey1', lastEvaluatedKey);

      //     } else {
      //       //console.log('calendar fetching error breaking');
      //       break;
      //     }

      //   } else {
      //     //console.log('calendar fetching breaking');
      //     break;
      //   }

      // } while(1)



    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }
  fetchOnlyYearlyUserCalendar = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY, userprofileid: string = this.userProfileId, userrole: string = this.myRole, entityid = this.entityId, countryid = this.countryId, locationid = this.locationId, tagid = this.tagId, functionid = this.functionId) => {

    let path = "", view = "";
    this.suspenseCount = 0;
    if (tagid != null && tagid != "") {
      view = "tag";
    } else if (countryid != null && countryid != "") {
      view = "tag";
    } else if (locationid != null && locationid != "") {
      view = "tag";
    } else {
      view = "entity";
    }

    path = "getallcountryevents6";

    let url = "https://" + this.apiId + "/" + path;
    let temptagid = tagid;
    if (temptagid == "" && locationid != "") {
      temptagid = locationid
    } else if (temptagid == "" && (userprofileid != this.userProfileId || userrole != this.myRole)) {
      temptagid = "allevents"
    }
    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": userprofileid, "role": userrole, "entityid": entityid, "countryid": countryid, "functionid": functionid, "locationid": "", "tagid": temptagid, "adhoc": "false", "exclusivestartkey": 0, "sdate": startDate, "edate": endDate, "view": view, "year": year, "list": list, "month": month, "viewerrole": this.myRole, "viewerid": this.userProfileId, "contractstartdate": this.contractStartDate };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }
    if (this.showReportedLocations) {
      urlBody["reportedlocations"] = "yes";
    }

    console.log('fetchOnlyYearlyUserCalendar', `TagId:${this.tagId}, CountryId:${this.countryId}, LocationId:${this.locationId}, EntityId:${this.entityId}, FunctionId:${this.functionId}, View:${view}, urlBody:`, urlBody);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      // if (JSON.stringify(urlBody) == this.getallcountryevetsParams) {
      this.events = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      // }
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchAndRenderNotices = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => {

    let path = "", view = "";
    this.sdate = startDate;
    this.edate = endDate;
    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    path = "getallcountrynotices";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }


    let url = "https://" + this.apiIdNotices + "/" + path;

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      let notices = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      this.lastupdated = Util.getDateTimeStrings(new Date().getTime())
      let tempEvents = this.events
      for (let mmddyyyy of Object.keys(notices)) {
        tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...notices[mmddyyyy]]
      }
      this.events = tempEvents;
      this.renderAppropriateStream(this.sdate, this.edate, true);
      console.log('notices', notices, tempEvents);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchAndRenderContracts = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => {

    let path = "", view = "";
    this.sdate = startDate;
    this.edate = endDate;
    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    path = "getallcountryobjects";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }


    let url = "https://" + this.apiIdAgreements + "/" + path;

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      let contracts = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      this.lastupdated = Util.getDateTimeStrings(new Date().getTime())
      // let tempEvents = this.events
      // for (let mmddyyyy of Object.keys(contracts)) {
      //   tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...contracts[mmddyyyy]]
      // }
      // this.events = tempEvents;
      this.events = contracts;
      this.renderAppropriateStream(this.sdate, this.edate, true);
      console.log('contracts', contracts);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }
  fetchAndRenderLicenses = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => {

    let path = "", view = "";
    this.sdate = startDate;
    this.edate = endDate;
    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    path = "getallcountryobjects";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }


    let url = "https://" + this.apiIdLicenses + "/" + path;

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      let licenses = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      this.lastupdated = Util.getDateTimeStrings(new Date().getTime())
      // let tempEvents = this.events
      // for (let mmddyyyy of Object.keys(licenses)) {
      //   tempEvents[mmddyyyy] = [...(tempEvents[mmddyyyy] ?? []), ...licenses[mmddyyyy]]
      // }
      // this.events = tempEvents;
      this.events = licenses;
      this.renderAppropriateStream(this.sdate, this.edate, true);
      console.log('licenses', licenses);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchAndRenderRCMResources = async (startDate: string = "", endDate: string = "", searchString: string = "", list: string = "yes", month: string = "00", year: string = this.calendarStartYYYY) => {

    let path = "", view = "";
    this.sdate = startDate;
    this.edate = endDate;
    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    path = "getallcountryobjects";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }


    let url = "https://" + this.apiIdRCMResources + "/" + path;

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": view, "year": year, "list": list, "month": month };

    if (searchString.length > 0) {
      urlBody["searchstring"] = searchString;
    }

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose', jsonRespose);
      let rcmresources = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      this.lastupdated = Util.getDateTimeStrings(new Date().getTime())
      this.events = rcmresources;
      this.renderAppropriateStream(this.sdate, this.edate, true);
      console.log('rcmresources', rcmresources);
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchStatistics = async (startDate: string = "", endDate: string = "", filtercriteria: string, filterid: string, subfiltercriteria: string, subfilterid: string) => {

    let path = "";
    this.sdate = startDate;
    this.edate = endDate;


    path = "getstatistics";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }

    let url = ""
    if (this.selectedFeatures.indexOf('compliances') >= 0) {
      url = "https://" + this.apiId + "/" + path;
    } else if (this.selectedFeatures.indexOf('notices') >= 0) {
      url = "https://" + this.apiIdNotices + "/" + path;
    } else if (this.selectedFeatures.indexOf('contracts') >= 0) {
      url = "https://" + this.apiIdAgreements + "/" + path;
    } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
      url = "https://" + this.apiIdLicenses + "/" + path;
    } else if (this.selectedFeatures.indexOf('rcmresource') >= 0) {
      url = "https://" + this.apiIdRCMResources + "/" + path;
    }

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userid": this.userProfileId, "role": this.myRole, "sdate": sDate, "edate": eDate, "filtercriteria": filtercriteria, "subfiltercriteria": subfiltercriteria, "subfilterid": subfilterid };

    if (filtercriteria == 'function') {
      urlBody["functionid"] = filterid;
      urlBody["locationid"] = '';
      urlBody["filteruserrole"] = '';
      urlBody["filteruserid"] = '';
    } else if (filtercriteria == 'location') {
      urlBody["functionid"] = '';
      urlBody["locationid"] = filterid;
      urlBody["filteruserrole"] = '';
      urlBody["filteruserid"] = '';
    } else {
      urlBody["functionid"] = '';
      urlBody["locationid"] = '';
      urlBody["filteruserrole"] = filtercriteria;
      urlBody["filteruserid"] = filterid;
    }

    console.log('urlbody', urlBody);
    this.getallcountryevetsParams = JSON.stringify(urlBody);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200 && this.getallcountryevetsParams == JSON.stringify(urlBody)) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose Statistics', jsonRespose);
      this.statistics = jsonRespose.data
      this.lastupdated = Util.getDateTimeStrings(new Date(jsonRespose.lastupdated).getTime())
      console.log('statistics date', this.lastupdated);
      this.statisticsFiltersData = jsonRespose.filtersdata ?? {}
      if (jsonRespose.meta != null)
        this.statisticsMeta = jsonRespose.meta
      return jsonRespose.meta

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status != 200) {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }
    }

  }

  fetchStatisticsEvents = async (startDate: string = "", endDate: string = "", filtercriteria: string, filterid?: string) => {

    let path = "";
    this.sdate = startDate;
    this.edate = endDate;


    path = "getstatisticsevents";

    let sDate = "";
    let eDate = "";

    //console.log('currenttab', this.getCurrentTab());

    if (this.getCurrentTab() == this.TAB_YEAR) {
      sDate = "03/31/" + this.calendarStartYYYY;
      eDate = "04/01/" + (parseInt(this.calendarStartYYYY) + 1);
    } else {
      sDate = startDate;
      eDate = endDate;
    }

    let url = ""
    if (this.selectedFeatures.indexOf('compliances') >= 0) {
      url = "https://" + this.apiId + "/" + path;
    } else if (this.selectedFeatures.indexOf('notices') >= 0) {
      url = "https://" + this.apiIdNotices + "/" + path;
    } else if (this.selectedFeatures.indexOf('contracts') >= 0) {
      url = "https://" + this.apiIdAgreements + "/" + path;
    } else if (this.selectedFeatures.indexOf('licenses') >= 0) {
      url = "https://" + this.apiIdLicenses + "/" + path;
    } else if (this.selectedFeatures.indexOf('rcmresource') >= 0) {
      url = "https://" + this.apiIdRCMResources + "/" + path;
    }

    //console.log('fetch calendar url', url);
    let urlBody: any = { "projectid": this.projectId, "userid": this.userProfileId, "role": this.myRole, "sdate": sDate, "edate": eDate, "filtercriteria": filtercriteria, "filterid": filterid };

    console.log('urlbody', urlBody);
    this.getallcountryevetsParams = JSON.stringify(urlBody);
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200 && this.getallcountryevetsParams == JSON.stringify(urlBody)) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('jsonRespose Statistics', jsonRespose);
      this.lastupdated = Util.getDateTimeStrings(new Date(jsonRespose.lastupdated).getTime())
      console.log('statistics date', this.lastupdated);
      this.events = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      // }
      this.suspenseCount = jsonRespose.suspensecount ?? 0;
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status != 200) {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }
    }

  }

  fetchBulkReportingData = async () => {
    let path = "getbulkreportjobs"
    let urlBody: any = { "projectid": this.projectId }
    let url = "https://" + this.apiId + "/" + path;
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('bulk reports jsonResponse', jsonResponse);
      let flagBulk = false;
      if (jsonResponse.result == true) {
        for (let sortid of Object.keys(jsonResponse.data)) {
          let sortidArr = sortid.split(';')
          let mmddyyyy = sortidArr[0]
          let entityid = sortidArr[1]
          let locationid = sortidArr[2]
          let eventid = sortidArr[3]
          let mmdd = mmddyyyy.split('/')[0] + '/' + mmddyyyy.split('/')[1]
          if (this.mode == "next") {
            console.log('mmdd', mmdd, Object.keys(this.nextEvents[this.nextTabRole]));
            if (this.nextEvents[this.nextTabRole][mmdd] != null) {
              for (let i = 0; i < this.nextEvents[this.nextTabRole][mmdd].length; i++) {
                if (this.nextEvents[this.nextTabRole][mmdd][i].entityid == entityid && this.nextEvents[this.nextTabRole][mmdd][i].locationid == locationid && this.nextEvents[this.nextTabRole][mmdd][i].id == eventid) {
                  this.nextEvents[this.nextTabRole][mmdd][i].isbulk = true;
                  flagBulk = true
                  break
                }
              }
            }
          } else {
            console.log('mmdd', mmdd, Object.keys(this.events));
            if (this.events[mmdd] != null) {
              for (let i = 0; i < this.events[mmdd].length; i++) {
                if (this.events[mmdd][i].entityid == entityid && this.events[mmdd][i].locationid == locationid && this.events[mmdd][i].id == eventid) {
                  this.events[mmdd][i].isbulk = true;
                  flagBulk = true
                  break
                }
              }
            }
          }
        }
        // All Bulk for testing
        // for(let mmdd of Object.keys(this.events)){
        //   for (let i = 0 ; i < this.events[mmdd].length; i ++){
        //     this.events[mmdd][i].isbulk = true;
        //     flagBulk = true
        //   }
        // }
        if (flagBulk) {
          // backgroundProcessButton.classList.remove('hide');
          // backgroundProcessButton.style.display = 'flex'
          // console.log('backgroundprocessbutton', backgroundProcessButton);
          // backgroundProcessButton.addEventListener('click',() => {
          //   console.log('bulk-progress clicked')
          //   let bulkLoader = (this._SfIEventsC as HTMLDivElement).querySelector('.bulk-loader') as HTMLDivElement
          //   bulkLoader.scrollIntoView();
          // })
          if (this.mode == "next") {
            this.renderNextEvents(this.nextEvents, this.nextPage, this.nextTabRole)
          } else {
            this.renderAppropriateStream(this.sdate, this.edate, true, true)
          }
        } else {
          // backgroundProcessButton.classList.add('hide')
          // backgroundProcessButton.style.display = 'none'
        }
      }
    } else if (xhr.status == 401) {
      let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
      this.dispatchEvent(changeEvent);
    }
  }

  fetchUserCalendar = async () => {

    let url = "https://" + this.apiId + "/getuserevents";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      this.showChosenProject();
      //console.log(jsonRespose);
      this.events = (jsonRespose.data.events)

      if (this.events != null) {
        this.renderTabs(this.TAB_YEAR);
        this.renderCalendar();
      }
      // this.renderChosenProject(events);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchCalendar = async () => {

    //this.apiBodyList = '{"id": "' +(this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0]+ '"}'

    let url = "https://3mefupehxkw4pwsq3oyk7lf2pq0pisdx.lambda-url.us-east-1.on.aws/schedulegetcalendarjob";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0] }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      this.showChosenProject();
      (this._SfTitleChosenProject as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true);
      this.events = JSON.parse(jsonRespose.data.value.events)
      // //console.log(events);
      if (this.events != null) {
        this.renderTabs(this.TAB_YEAR);
        this.renderCalendar();
      }
      // this.renderChosenProject(events);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {

        this.showChosenProject();
        (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
        this.renderChosenProject();

      } else {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  fetchReprogramAdhoc = async () => {

    let url = "https://" + this.apiId + "/reprogramtrigger";
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": this.mode == "admin" ? (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0] : this.projectId }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      // const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      this.fetchList();
      setTimeout(() => {
        this.clearMessages();
      }, 3000);

    }
  }

  fetchAdhoc = async () => {

    let path = "getallmyevents", view = "";

    if (this.tagId != null && this.tagId != "") {
      view = "tag";
    } else if (this.countryId != null && this.countryId != "") {
      view = "country";
    } else if (this.locationId != null && this.locationId != "") {
      view = "location";
    } else {
      view = "entity";
    }

    let url = "https://" + this.apiId + "/" + path;
    let urlBody = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": this.entityId, "countryid": this.countryId, "functionid": this.functionId, "locationid": this.locationId, "tagid": this.tagId, "adhoc": "true", "year": this.calendarStartYYYY, "view": view };

    //console.log('urlbody', urlBody);

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log(jsonRespose);
      let responseData = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      return responseData;

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      this.fetchList();
      setTimeout(() => {
        this.clearMessages();
      }, 3000);

    }
  }

  fetchEventMap = async () => {

    let url = "https://" + this.apiId + "/getunmappedevents";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr({ "projectid": (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0], "role": this.myRole }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      //console.log(jsonRespose);
      this.unmappedEvents = jsonRespose.data.unmappedEvents;
      this.mappings = jsonRespose.data.mappings;
      //console.log('mappings-1', 'fetcheventmap', this.mappings)
      //console.log('mappings0', 'fetcheventmap', this.mappedValuesUsers)
      this.renderMapping(this.unmappedEvents)
      //console.log('mappings1', 'fetcheventmap', this.mappedValuesUsers)
      this.prepopulateMapping(this.mappings);
      //console.log('mappings2', 'fetcheventmap', this.mappedValuesUsers)
      this.applyFilter();
      if (jsonRespose.data.mappings != null && this.myRole != this.TAB_APPROVER) {
        (this._SfButtonBackCalendarMapping as HTMLButtonElement).style.visibility = 'visible';
      } else {
        (this._SfButtonBackCalendarMapping as HTMLButtonElement).style.visibility = 'hidden';
      }

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      this.fetchList();
      setTimeout(() => {
        this.clearMessages();
      }, 3000);

    }

  }

  fetchList = async () => {

    //console.log('calendar fetching list', this.apiIdList);

    const body: any = this.getApiBodyList();

    if (this.apiIdList != null) {

      body.id = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0];

      let url = "https://" + this.apiIdList + "/" + this.apiMethodList;

      //console.log('fetch events url', url);

      const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
      const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
      this._SfLoader.innerHTML = '';

      //console.log('fetch events body', body);

      if (xhr.status == 200) {

        const jsonRespose = JSON.parse(xhr.responseText);

        //console.log('list response', JSON.stringify(jsonRespose));

        const fieldArr = JSON.parse(jsonRespose.data.value[this.apiResponseFieldList]) as Array<string>;
        this.events = null;
        for (var i = 0; i < fieldArr.length; i++) {

          //console.log('events', fieldArr[i]);
          await this.fetchDetail(fieldArr[i])

        }

        //console.log('all events processed');
        await this.uploadEvents();
        await this.fetchReprogramAdhoc();
        //await this.fetchAdhoc(true);

      } else {
        if (xhr.status == 401) {
          let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
          this.dispatchEvent(changeEvent);
        }
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  initCalendar = async () => {

    var newDate = null;
    var newMonth = null;
    var newYear = null;
    var startDate = new Date(this.calendarStartMM + '/' + this.calendarStartDD + '/' + this.calendarStartYYYY);

    //console.log('startDate', startDate);

    do {

      this.calendar.push(startDate);
      startDate.setDate(startDate.getDate() + 1);

      newDate = ("0" + startDate.getDate()).slice(-2);
      newMonth = ("0" + startDate.getMonth()).slice(-2);
      newYear = (startDate.getFullYear());

    } while (!(newDate == this.calendarStartDD && newMonth == (("0" + ((parseInt(this.calendarStartMM) - 1) + "")).slice(-2)) && newYear === (parseInt(this.calendarStartYYYY) + 1)));

    //console.log(this.calendar);

  }

  initInputs = () => {

    this.calendarStartDD = ("0" + this.calendarStartDD).slice(-2);
    this.calendarStartMM = ("0" + this.calendarStartMM).slice(-2);

  }

  showChooseProject = () => {

    var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf<HTMLElement>;
    var index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'flex'
    }

    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }

    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }
  }

  showChosenProject = () => {

    var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf<HTMLElement>;
    var index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }

    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'flex'
    }


    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }

  }

  showChosenMapping = () => {

    var elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.choose-project') as NodeListOf<HTMLElement>;
    var index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }

    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-project') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'none'
    }


    elems = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.chosen-mapping') as NodeListOf<HTMLElement>;
    index = 0, length = elems.length;
    for (; index < length; index++) {
      elems[index].style.display = 'flex'
    }

  }

  formatIndianNumber = (num: number) => {
    if (num === null || num === undefined || isNaN(num)) return '';
    num = Number(num);

    if (num >= 10000000) {
      // 1 Crore = 10,000,000
      return (num / 10000000).toFixed(num % 10000000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' Cr';
    } else if (num >= 100000) {
      // 1 Lakh = 100,000
      return (num / 100000).toFixed(num % 100000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' Lac';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(num % 1000 === 0 ? 0 : 2).replace(/\.00$/, '') + ' K';
    } else {
      return num.toString();
    }
  }


  truncate = (str: string, n: number, useWordBoundary: boolean, ellipsis: boolean = true) => {
    if (str.length <= n) { return str; }
    const subString = str.slice(0, n - 1); // the original check
    return (useWordBoundary
      ? subString.slice(0, subString.lastIndexOf(" "))
      : subString) + (ellipsis ? "&hellip;" : "...");
  };

  initListenersAdmin = () => {

    var old_element = null;
    var new_element = null;

    old_element = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    this._SfProject[0].querySelector('#sf-i-project').addEventListener('valueChanged', async () => {
      (this._SfTitleChosenMapping as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true);
      this.showChosenMapping();
      this.fetchEventMap();
      this.renderMappingTabs(this.TAB_REPORTER);
    });

    old_element = (this._SfButtonBackChosenProject as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonBackChosenProject as HTMLButtonElement).addEventListener('click', async () => {
      this.loadMode();
    });

    old_element = (this._SfButtonSyncChosenProject as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonSyncChosenProject as HTMLButtonElement).addEventListener('click', async () => {
      this.fetchList();
    });

    old_element = (this._SfButtonBackChosenMapping as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonBackChosenMapping as HTMLButtonElement).addEventListener('click', async () => {
      this.loadMode();
    });

    old_element = (this._SfButtonMapChosenProject as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonMapChosenProject as HTMLButtonElement).addEventListener('click', async () => {
      (this._SfTitleChosenMapping as HTMLElement).innerHTML = this.truncate((this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0], 20, true);
      this.showChosenMapping();
      this.fetchEventMap();
      this.renderMappingTabs(this.TAB_REPORTER);
    });


    old_element = (this._SfButtonBackCalendarMapping as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonBackCalendarMapping as HTMLButtonElement).addEventListener('click', async () => {
      this.fetchCalendar()
    });

    old_element = (this._SfButtonBackSyncMapping as HTMLButtonElement);
    new_element = old_element!.cloneNode(true);
    old_element?.parentElement?.replaceChild(new_element, old_element!);
    (this._SfButtonBackSyncMapping as HTMLButtonElement).addEventListener('click', async () => {
      this.fetchList();
    });

  }

  isAdmin = () => {
    return Util.readCookie('admin') == "true"
  }

  initDecryptView = () => {
    if (this.isAdmin()) {
      let divsArr = this._SfDecryptContainer.querySelectorAll("#decrypt-container > div")
      console.log('decrypt divs', divsArr);
      for (let divElement of divsArr) {
        (divElement as HTMLElement).classList.remove('hide');
      }
      this.initDecryptListeners()
    } else {
      let divsArr = this._SfDecryptContainer.querySelectorAll("#decrypt-container > div")
      console.log('decrypt divs', divsArr);
      for (let divElement of divsArr) {
        (divElement as HTMLElement).classList.add('hide');
      }
    }
  }

  initDecryptListeners = () => {
    (this._SfDecryptProjectInput as SfIForm).addEventListener('valueChanged', () => {
      let projectId = (this._SfDecryptProjectInput as SfIForm).selectedValues()[0]
      this.decryptProjectId = projectId.split(';')[projectId.split(';').length - 1];
      this.evalDecrypt()
    });
    (this._SfDecryptFileInput as HTMLInputElement).addEventListener('keyup', () => {
      console.log('keyup called');
      this.decryptFileName = (this._SfDecryptFileInput as HTMLInputElement).value;
      this.evalDecrypt()
    });
    (this._SfDecryptButton as HTMLButtonElement).addEventListener('click', () => {
      console.log('decrypt clicked', this.decryptProjectId, this.decryptFileName);
      this.submitDecrypt()
    })
  }

  evalDecrypt = () => {
    console.log((this._SfDecryptFileInput as HTMLInputElement))
    console.log('evalDecrypt', this.decryptProjectId, this.decryptFileName)
    if (this.decryptProjectId != null && this.decryptProjectId != "" && this.decryptFileName != null && this.decryptFileName.length > 3) {
      (this._SfDecryptContainer?.querySelector('#button-decrypt') as HTMLButtonElement).removeAttribute('disabled');
    } else {
      (this._SfDecryptContainer?.querySelector('#button-decrypt') as HTMLButtonElement).setAttribute('disabled', 'true');
    }
  }

  submitDecrypt = async () => {

    this.clearMessages();

    console.log('submitDecrypt called');

    const body: any = {};
    let url = "https://" + this.apiId + "/getdecryptedjson";

    body["projectid"] = this.decryptProjectId;
    body["key"] = this.decryptFileName + ".json";

    console.log(body);
    console.log(JSON.stringify(body));

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(body, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      const jsonRespose = JSON.parse(xhr.responseText);
      let data = await this.fetchPresignedUrl(jsonRespose.signedUrlGet);
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      console.log('decrypt response', jsonRespose)
      this.setSuccess('Operation Successful!');
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
      a.download = this.decryptFileName + ".json";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      setTimeout(() => {
        this.clearMessages();
      }, 2000);

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      const jsonRespose = JSON.parse(xhr.responseText);
      this.setError(jsonRespose.error);
      setTimeout(() => {
        this.clearMessages();
      }, 5000);
    }

  }

  fetchNext = async (page: number, role: string, status: string) => {

    //this.apiBodyList = '{"id": "' +(this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedValues()[0]+ '"}'
    this.nextPage = page;
    let url = "https://" + this.apiId + "/getnextuserevents";
    let statusArr: string[] = []
    if (status == this.TAB_ALL) {
      statusArr = [this.STATUS_NOT_STARTED, this.STATUS_PENDING_APPROVAL, this.STATUS_REJECTED, this.STATUS_APPROVED]
    } else if (status == this.TAB_PENDING_ON_ME) {
      if (role == this.TAB_REPORTER) {
        statusArr = [this.STATUS_NOT_STARTED, this.STATUS_REJECTED]
      } else if (role == this.TAB_APPROVER) {
        statusArr = [this.STATUS_PENDING_APPROVAL]
      }
    } else if (status == this.TAB_PENDING_ON_REPORTER) {
      statusArr = [this.STATUS_NOT_STARTED, this.STATUS_REJECTED]
    } else if (status == this.TAB_PENDING_ON_APPROVER) {
      statusArr = [this.STATUS_PENDING_APPROVAL]
    } else if (status == this.TAB_DONE) {
      statusArr = [this.STATUS_APPROVED]
    }
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    console.log('params', JSON.stringify({ "projectid": this.projectId, "userprofileid": this.userProfileId, "roles": [role], "year": this.calendarStartYYYY, "page": this.nextPage, "blocksize": parseInt(this.blocksize), "status": statusArr }))
    console.log('authorization', authorization)
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "roles": [role], "year": this.calendarStartYYYY + "", "page": this.nextPage, "blocksize": parseInt(this.blocksize), "status": statusArr, "list": "yes" }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      console.log('next response', jsonRespose)
      // this.renderChosenProject(events);
      // this.renderRoleTabsNext(jsonRespose.data, page)
      this.nextEvents = jsonRespose.data;
      this.renderNextEvents(this.nextEvents, page, role);
      this.fetchBulkReportingData();
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  clearButtonSelectionNext = () => {

    const buttonSelect = (this._SfIEventsC as HTMLDivElement).querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;

    for (var i = 0; i < buttonSelect.length; i++) {

      (buttonSelect[i] as HTMLInputElement).checked = false;

    }

  }

  renderRoleTabsNext = (page: number, loadData: boolean = true) => {

    //console.log('render role tabs');

    (this._SfRoleTabContainer as HTMLDivElement).innerHTML = '';
    if (this.nextTabRole == "") {
      // if(JSON.parse(this.myroles).length > 1){
      //   this.nextTabRole = this.TAB_ALL_ROLES
      // }else{
      this.nextTabRole = JSON.parse(this.myroles)[0]
      // }
    }
    console.log('rendering tabs', this.nextTabRole);
    var html = '';
    // if(JSON.parse(this.myroles).length > 1 && eventsData[this.TAB_ALL_ROLES] != null){
    //   html += '<button class="tab-button" id="consumer-tab-all-roles" part="'+(this.nextTabRole == this.TAB_ALL_ROLES ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected')+'">All Roles</button>';
    // }
    if (JSON.parse(this.myroles).indexOf(this.TAB_VIEWER) >= 0) {
      html += '<button class="tab-button" id="consumer-tab-viewer" part="' + (this.nextTabRole == this.TAB_VIEWER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Viewer</button>';
    }
    if (JSON.parse(this.myroles).indexOf(this.TAB_APPROVER) >= 0) {
      html += '<button class="tab-button" id="consumer-tab-approver" part="' + (this.nextTabRole == this.TAB_APPROVER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Approver</button>';
    }
    if (JSON.parse(this.myroles).indexOf(this.TAB_REPORTER) >= 0) {
      html += '<button class="tab-button" id="consumer-tab-reporter" part="' + (this.nextTabRole == this.TAB_REPORTER ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Reporter</button>';
    }
    if (JSON.parse(this.myroles).indexOf(this.TAB_FUNCTION_HEAD) >= 0) {
      html += '<button class="tab-button" id="consumer-tab-functionhead" part="' + (this.nextTabRole == this.TAB_FUNCTION_HEAD ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Function Head</button>';
    }
    if (JSON.parse(this.myroles).indexOf(this.TAB_AUDITOR) >= 0) {
      html += '<button class="tab-button" id="consumer-tab-auditor" part="' + (this.nextTabRole == this.TAB_AUDITOR ? 'calendar-tab-button-selected' : 'calendar-tab-button-not-selected') + '">Auditor</button>';
    }

    (this._SfRoleTabContainer as HTMLDivElement).innerHTML = html;

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-all-roles')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_ALL_ROLES;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });
    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-reporter')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_REPORTER;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-approver')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_APPROVER;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-functionhead')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_FUNCTION_HEAD;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });

    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-auditor')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_AUDITOR;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });


    (this._SfRoleTabContainer as HTMLDivElement).querySelector('#consumer-tab-viewer')?.addEventListener('click', async () => {

      this.nextTabRole = this.TAB_VIEWER;
      this.nextTabStatus = this.TAB_ALL;
      // this.fetchNext(0, this.nextTabRole);
      this.renderRoleTabsNext(0, loadData);

    });
    if (loadData) {
      this.renderStatusTabsNext(page);
    } else {
      (this._SfIEventsC.querySelector('#next-calendar-data').querySelector('#button-load-next') as HTMLButtonElement).addEventListener('click', () => {
        (this._SfIEventsC.querySelector('#next-calendar-data').querySelector('#button-load-next') as HTMLButtonElement).style.display = 'none';
        (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).classList.add('flex-col');
        this.renderRoleTabsNext(0)
      })
      let changeEvent = new CustomEvent('valueChanged', { bubbles: true });
      this.dispatchEvent(changeEvent);
    }
    let roleChangeEvent = new CustomEvent("roleChanged", {
      detail: {
        selectedRole: this.nextTabRole
      }
    });
    this.dispatchEvent(roleChangeEvent)
  }

  renderStatusTabsNext = (page: number) => {

    (this._SfStatusTabContainer as HTMLDivElement).innerHTML = '';
    if (this.nextTabStatus == "") {
      this.nextTabStatus = this.TAB_ALL
    }
    console.log('rendering status tabs', this.nextTabStatus);
    var html = '';

    html += '<button class="tab-button-small" id="consumer-tab-status-all" part="' + (this.nextTabStatus == this.TAB_ALL ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">All</button>';
    if (this.nextTabRole == this.TAB_REPORTER || this.nextTabRole == this.TAB_APPROVER) {
      html += '<button class="tab-button-small" id="consumer-tab-status-pending-on-me" part="' + (this.nextTabStatus == this.TAB_PENDING_ON_ME ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">Pending On Me</button>';
    }
    if (this.nextTabRole == this.TAB_APPROVER || this.nextTabRole == this.TAB_FUNCTION_HEAD || this.nextTabRole == this.TAB_AUDITOR || this.nextTabRole == this.TAB_VIEWER) {
      html += '<button class="tab-button-small" id="consumer-tab-status-pending-on-reporter" part="' + (this.nextTabStatus == this.TAB_PENDING_ON_REPORTER ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">Pending On Reporter</button>';
    }
    if (this.nextTabRole == this.TAB_REPORTER || this.nextTabRole == this.TAB_FUNCTION_HEAD || this.nextTabRole == this.TAB_AUDITOR || this.nextTabRole == this.TAB_VIEWER) {
      html += '<button class="tab-button-small" id="consumer-tab-status-pending-on-approver" part="' + (this.nextTabStatus == this.TAB_PENDING_ON_APPROVER ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">Pending On Approver</button>';
    }
    html += '<button class="tab-button-small" id="consumer-tab-status-done" part="' + (this.nextTabStatus == this.TAB_DONE ? 'calendar-tab-button-selected-small' : 'calendar-tab-button-not-selected-small') + '">Completed</button>';

    (this._SfStatusTabContainer as HTMLDivElement).innerHTML = html;

    (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-all')?.addEventListener('click', async () => {

      this.nextTabStatus = this.TAB_ALL;
      this.renderStatusTabsNext(0);

    });
    (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-me')?.addEventListener('click', async () => {

      this.nextTabStatus = this.TAB_PENDING_ON_ME;
      this.renderStatusTabsNext(0);

    });

    (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-reporter')?.addEventListener('click', async () => {

      this.nextTabStatus = this.TAB_PENDING_ON_REPORTER;
      this.renderStatusTabsNext(0);

    });

    (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-pending-on-approver')?.addEventListener('click', async () => {

      this.nextTabStatus = this.TAB_PENDING_ON_APPROVER;
      this.renderStatusTabsNext(0);

    });

    (this._SfStatusTabContainer as HTMLDivElement).querySelector('#consumer-tab-status-done')?.addEventListener('click', async () => {

      this.nextTabStatus = this.TAB_DONE;
      this.renderStatusTabsNext(0);

    });

    this.fetchNext(page, this.nextTabRole, this.nextTabStatus);
  }

  renderNextEvents = (eventsData: any, page: number, role: string) => {
    console.log('eventsData', eventsData)
    console.log('role', role)
    // if(Object.keys(eventsData[role]).length > 0){
    var notStarted = 0, approved = 0, pendingApproval = 0, rejected = 0, inTime = 0, pastDueDate = 0, lateExecuted = 0, lateApproved = 0, lateReported = 0, scheduled = 0, partiallyComplied = 0, notComplied = 0, complied = 0, compliedWithGaps = 0, reportedNonCompliance = 0;
    var html = '';
    this.selectedItemIds = [];
    this.selectedStatus = "";
    html += '<div id="stream-event-next" part="stream-event-list" class="stream-event-list">';
    for (var i = 0; i < Object.keys(eventsData[role]).length; i++) {

      let mmdd: string = Object.keys(eventsData[role])[i];

      //console.log('mmdd', mmdd);
      //console.log('mmddevent', mmdd,eventsData[role][mmdd]);


      if (eventsData[role][mmdd] != null) {
        html += '<div part="stream-event-selected" class="d-flex stream-event-selected mb-5">';
        html += '<div part="stream-event-selected-date">' + (mmdd.split("/")[1] + "/" + mmdd.split("/")[0]) + ' |</div>';
        html += '<div class="stream-event-list-container flex-grow" id="date-' + mmdd.replace(/\//g, '-') + '">'


        for (var j = 0; j < (eventsData[role][mmdd] as Array<any>).length; j++) {

          let eventHtml = '';
          eventsData[role][mmdd][j]['mmdd'] = mmdd

          let functionStr = eventsData[role][mmdd][j]['functions'][0]
          if (functionStr.indexOf(';') >= 0) {
            functionStr = functionStr.split(';')[0].replace(/\([^)]*\)/g, "");
          }
          // let reporterArr = []
          // for(let reporter of eventsData[role][mmdd][j]['reporters']) {
          //   reporterArr.push(reporter.split(';')[0])
          // }
          console.log('function', functionStr)
          var partStatus = "";
          var lateStatus = "";
          var complianceStatus = "";
          partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(eventsData[role][mmdd][j])));
          lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(eventsData[role][mmdd][j])), partStatus);
          complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(eventsData[role][mmdd][j])).percentage, JSON.parse(JSON.stringify(eventsData[role][mmdd][j])));
          notStarted = notStarted + (partStatus == "not-started" ? 1 : 0);
          pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0);
          rejected = rejected + (partStatus == "rejected" ? 1 : 0);
          approved = approved + (partStatus == "approved" ? 1 : 0);
          inTime = inTime + (lateStatus == "in-time" ? 1 : 0);
          pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0);
          lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0);
          lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0);
          lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0);
          scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0);
          partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0);
          notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0);
          complied = complied + (complianceStatus == "complied" ? 1 : 0);
          compliedWithGaps = compliedWithGaps + (complianceStatus == "complied-with-gaps" ? 1 : 0);
          reportedNonCompliance = reportedNonCompliance + (complianceStatus == "reported-non-compliance" ? 1 : 0);

          eventsData[role][mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus;
          eventsData[role][mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus;
          eventsData[role][mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus;
          // let thisRole = ""
          // if ((JSON.stringify(eventsData[role][mmdd][j].reporters)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Reporter'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].approvers)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Approver'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].functionheads)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Functionhead'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].auditors)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Auditor'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].viewers)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Viewer'
          // } 

          let reportersStr = this.getReporterStringFromEvent(eventsData[role][mmdd][j]).replace(/mb-20/g, '')
          eventHtml += '<div class="stream-events-container flex-grow">';
          eventHtml += '<div class="hidden-tags hide">' + JSON.stringify(eventsData[role][mmdd][j]['tags']) + '</div>'
          eventHtml += '<div class="hidden-title hide"><table><thead><th part="badge-filtered"><i>not filtered</i></th></thead></table></div>'
          eventHtml += '<div part="stream-events-event-title" class="stream-events-event-title d-flex align-center pl-5 pb-5 mb-10">' + (eventsData[role][mmdd][j].isbulk ? ('<div class="lds-dual-ring1 bulk-loader mr-10"></div>') : ('<input id="button-select-' + mmdd.replace('/', '-') + '-' + j + '-' + (((eventsData[role][mmdd][j].makercheckers != null && (eventsData[role][mmdd][j].makercheckers).length > 0)) ? '1' : '0') + '-' + (((eventsData[role][mmdd][j].docs != null && (eventsData[role][mmdd][j].docs).length > 0)) ? '1' : '0') + '-' + eventsData[role][mmdd][j].entityid.replace(/-/g, '_') + '-' + eventsData[role][mmdd][j].locationid.replace(/-/g, '_') + '-' + eventsData[role][mmdd][j].id.replace(/-/g, '_') + '-' + eventsData[role][mmdd][j].duedate.split('/')[1] + '-' + eventsData[role][mmdd][j].duedate.split('/')[0] + '-' + eventsData[role][mmdd][j].duedate.split('/')[2] + '-' + partStatus.replace(/-/g, '_') + '" class="button-select mr-10 ' + ((eventsData[role][mmdd][j].reportformat != null && eventsData[role][mmdd][j].reportformat.length > 0) ? 'hide' : '') + '" type="checkbox" />')) + (eventsData[role][mmdd][j].isbulk ? '' : ('<button id="button-unmapped-expand-' + mmdd.replace('/', '-') + '-' + j + '" part="button-icon-small" class="material-icons button-expand mr-10">open_in_new</button>')) + '<sf-i-elastic-text exportparts="highlight,highlight-count" class="mobile-only m-w-200" text="' + eventsData[role][mmdd][j]['obligationtitle'] + '" minLength="50"></sf-i-elastic-text><sf-i-elastic-text exportparts="highlight,highlight-count" class="desktop-only" text="' + eventsData[role][mmdd][j]['obligationtitle'] + '" minLength="80"></sf-i-elastic-text>&nbsp;&nbsp;' + '<div part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + eventsData[role][mmdd][j]["locationname"].replace(/ *\([^)]*\) */g, "") + '" minLength="30"></sf-i-elastic-text></div>&nbsp;&nbsp;<div part="upcoming-function">' + functionStr + '</div>' + reportersStr + '&nbsp;&nbsp;' + this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i)

          console.log('next isBulk', eventsData[role][mmdd][j].isbulk);
          if (eventsData[role][mmdd][j].isbulk == null || eventsData[role][mmdd][j].isbulk == false) {
            eventHtml += '<button id="button-list-reporting-' + mmdd.replace('/', '-') + '-' + j + '-" part="button-list-reporting" class="material-icons ml-10 button-list-reporting">edit_note</button>'
          }
          eventHtml += '</div>';
          eventHtml += '<div class="list-reporting-container d-flex flex-col hide" part="list-reporting-container" id="list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j + '"></div>'

          eventHtml += '</div>';
          html += eventHtml

        }
        html += '</div>';
        html += '</div>';
      }
    }
    console.log('eventsData Role length', Object.keys(eventsData[role]).length)
    if (Object.keys(eventsData[role]).length == 0) {
      html += `
            <div class="dashboard-container d-flex-plain flex-col align-center justify-start section-start section-end">
                <div class="no-donut d-flex justify-center flex-col align-center pl-10 pr-10">
                    <h1 class="mb-5"><span class="material-symbols-outlined">check_circle</span></h1>
                    <h5 class="mt-5">Nothing to show here.</h5>
                </div>
            </div>`;
    } else {

      html += '<div class="d-flex align-center mt-10">'
      html += '<button id="button-prev" part="icon-button-small" class="material-symbols-outlined mr-10">keyboard_arrow_left</button>';
      html += '<p part="page-next">Page ' + (page >= 0 ? (page + 1) : page) + '</p>'
      html += '<button id="button-next" part="icon-button-small" class="material-symbols-outlined ml-10">keyboard_arrow_right</button>';
      html += '</div>';
    }
    html += '</div>';

    let nextEventsContainer = (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement);
    nextEventsContainer.innerHTML = html;
    nextEventsContainer.style.display = "flex";
    this.myRole = role;
    let buttonListReports = nextEventsContainer.querySelectorAll('.button-list-reporting') as NodeListOf<HTMLButtonElement>
    for (let buttonListReport of buttonListReports) {
      buttonListReport?.addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const yyyy = this.getCurrentYear(idArr[3]);
        // const i = idArr[5];
        const j = idArr[5];
        let listReportingContainer = nextEventsContainer.querySelector('#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j) as HTMLDivElement
        console.log('mmddyyyy', eventsData[role][mmdd][j], listReportingContainer, '#list-reporting-container-' + mmdd.replace(/\//g, '-') + '-' + j);
        if (listReportingContainer.style.display == 'none' || listReportingContainer.style.display == '') {
          this.renderListReporting(listReportingContainer, eventsData[role][mmdd][j], mmdd + '/' + yyyy, nextEventsContainer)
        } else {
          listReportingContainer.innerHTML = '';
          listReportingContainer.style.display = 'none';
          ev.target.setAttribute('part', 'button-list-reporting')
          let streamEventTitles = nextEventsContainer.querySelectorAll('.stream-event-title') as NodeListOf<SfIElasticText>
          for (let streamEventTitle of streamEventTitles) {
            streamEventTitle.removeAttribute('part')
          }
        }
        // console.log('part', ev.target.getAttribute('part'));
      })
    }


    // }else{
    //   let innerDivHtml = (this._SfIEventsC.querySelector('#stream-event-next') as HTMLDivElement).innerHTML;
    //   innerDivHtml.replace('<button id="button-expand" part="icon-button-small" class="material-symbols-outlined">keyboard_arrow_down</button>','');
    //   console.log('innerDivHtml', innerDivHtml)
    //   innerDivHtml += html;
    //   innerDivHtml += '<button id="button-expand" part="icon-button-small" class="material-symbols-outlined">keyboard_arrow_down</button>';
    //   (this._SfIEventsC.querySelector('#stream-event-next') as HTMLDivElement).innerHTML = innerDivHtml;
    // }
    // if(page != 0){
    let buttonPrev = this._SfIEventsC.querySelector('#button-prev') as HTMLButtonElement;
    buttonPrev?.addEventListener('click', () => {
      this.myRole = role;
      this.fetchNext(page - 1, this.nextTabRole, this.nextTabStatus)
    });
    // }
    let buttonNext = this._SfIEventsC.querySelector('#button-next') as HTMLButtonElement;

    // buttonExpand = Util.clearListeners(buttonExpand) as HTMLButtonElement;

    buttonNext?.addEventListener('click', () => {
      this.myRole = role;
      this.fetchNext(page + 1, this.nextTabRole, this.nextTabStatus)
    })
    const buttonArr = this._SfIEventsC.querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (var i = 0; i < buttonArr.length; i++) {
      let indexPrevNext = i;
      buttonArr[i].addEventListener('click', (ev: any) => {

        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];

        let found = false;
        for (var k = 0; k < this.selectedItemIds.length; k++) {
          if (this.selectedItemIds[k].indexOf(idArr[3] + '-' + idArr[4] + '-' + idArr[5]) >= 0) {
            found = true;
          }
        }
        if (!found) {
          this.selectedItemIds = [];
          this.clearButtonSelectionNext();
        }

        // (this._SfDetailContainer as HTMLDivElement).style.display = 'block'`

        var yyyy = this.getCurrentYear(idArr[3]);
        console.log('yyyy', yyyy, idArr[3]);
        console.log(eventsData[role][mmdd][j])
        if (role == this.TAB_ALL_ROLES) {
          if (JSON.stringify(eventsData[role][mmdd][j]['viewers']).indexOf(this.userProfileId) >= 0) {
            this.myRole = this.TAB_VIEWER
          }
          if (JSON.stringify(eventsData[role][mmdd][j]['auditors']).indexOf(this.userProfileId) >= 0) {
            this.myRole = this.TAB_AUDITOR
          }
          if (JSON.stringify(eventsData[role][mmdd][j]['functionheads']).indexOf(this.userProfileId) >= 0) {
            this.myRole = this.TAB_FUNCTION_HEAD
          }
          if (JSON.stringify(eventsData[role][mmdd][j]['approvers']).indexOf(this.userProfileId) >= 0) {
            this.myRole = this.TAB_APPROVER
          }
          if (JSON.stringify(eventsData[role][mmdd][j]['reporters']).indexOf(this.userProfileId) >= 0) {
            this.myRole = this.TAB_REPORTER
          }
        } else {
          this.myRole = this.nextTabRole
        }
        console.log('redering detail', this.myRole)
        // this.renderEventDetail(eventsData[role][mmdd][j], mmdd + "/" + yyyy, null);
        let prevString = "";
        if (indexPrevNext > 0) {
          prevString = (buttonArr[indexPrevNext - 1] as HTMLButtonElement).id;
        }
        let nextString = "";
        if (indexPrevNext < buttonArr.length - 1) {
          nextString = (buttonArr[indexPrevNext + 1] as HTMLButtonElement).id;
        }
        this.fetchEventDetails(eventsData[role][mmdd][j], mmdd + "/" + yyyy, null, (this._SfIEventsC as HTMLDivElement), prevString, nextString);

      })

    }

    const streamEventsContainer = this._SfIEventsC.querySelectorAll('.stream-events-container') as NodeListOf<HTMLDivElement>;
    const buttonSelect = this._SfIEventsC.querySelectorAll('.button-select') as NodeListOf<HTMLInputElement>;

    for (i = 0; i < buttonSelect.length; i++) {

      buttonSelect[i].addEventListener('click', (ev: any) => {

        //console.log('eventscontainer', streamEventsContainer.length, buttonSelect.length);

        const id = ev.target.id;
        const idArr = id.split("-")
        // const mmdd = idArr[2] + "/" + idArr[3];
        // const j = idArr[4];
        // const makercheckers = idArr[5];
        const docs = idArr[6];

        if ((ev.target as HTMLInputElement).checked) {
          this.selectedItemIds.push(id);
        } else {
          this.selectedItemIds.splice(this.selectedItemIds.indexOf(id), 1);
        }

        if (this.selectedItemIds.length === 0) {

          for (var k = 0; k < buttonSelect.length; k++) {

            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const isbulk = idArr1[15] == "bulk"
            console.log('isBulk button-select3', id1, isbulk)
            if (isbulk) {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'block';
            }
            (streamEventsContainer[k] as HTMLDivElement).style.display = 'block';

          }

        } else {

          if (this.selectedItemIds.length === 1) {

            const id1 = id;
            const idArr1 = id1.split("-")
            const status = idArr1[13].replace(/_/g, '-');
            this.selectedStatus = status;

          }

          for (var k = 0; k < buttonSelect.length; k++) {

            const id1 = buttonSelect[k].id;
            const idArr1 = id1.split("-")
            const docs1 = idArr1[6];
            const status = idArr1[13].replace(/_/g, '-');

            if (docs == docs1 && status == this.selectedStatus) {
            } else {
              (buttonSelect[k] as HTMLInputElement).style.display = 'none';
              (streamEventsContainer[k] as HTMLDivElement).style.display = 'none';
            }

          }

        }

      })
      let changeEvent = new CustomEvent('valueChanged', { bubbles: true });
      this.dispatchEvent(changeEvent);
    }
    // return html;
    // }else{
    //   let html = `
    //         <div class="dashboard-container d-flex-plain flex-col align-center justify-start section-start section-end">
    //             <div class="no-donut d-flex justify-center flex-col align-center pl-10 pr-10">
    //                 <h1 class="mb-5"><span class="material-symbols-outlined">check_circle</span></h1>
    //                 <h5 class="mt-5">All good! Nothing is due.</h5>
    //             </div>
    //         </div>`;
    //   (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).innerHTML = html;
    //   // (this._SfIEventsC.querySelector('#next-calendar-data') as HTMLDivElement).style.display = "none";
    //   let emptyEvent = new CustomEvent('valueChanged',{bubbles:false});
    //   this.dispatchEvent(emptyEvent);
    // }

  }

  fetchReports = async () => {
    let url = "https://" + this.apiId + "/getreports";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    console.log('this.myroles', this.myroles)
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "userprofileid": this.userProfileId, "year": this.calendarStartYYYY }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonRespose = JSON.parse(xhr.responseText);
      let arrReports = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
      await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete)
      console.log('reports response', Object.keys(arrReports).length);
      console.log('report', arrReports);
      this.renderReports(arrReports)
    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }

  }

  renderReports = (reportsData: any) => {
    let html = '<div class="d-flex flex-col w-100-m-0">'
    html += '<div part="stream-event-list" class="d-flex flex-col align-stretch">'
    for (let reportKey of Object.keys(reportsData)) {

      if (reportKey == '3/31/*,30;c989a44e-7d3d-427e-b712-90eacf585075;38dc8c53-643f-4fee-83fe-f15239606277;0a5fb99f-c36f-46c0-85b4-7fa3d48fa134') { continue; }

      let report = JSON.parse(reportsData[reportKey])
      if (report['event'] == null) {
        continue;
      }

      html += '<div part="stream-event-selected" class="w-100 scroll-x mr-10 ml-10 mt-10">'
      html += '<table>';

      html += '<tr>';
      html += '<th part="td-head">Select</th>'
      html += '<th part="td-head">Processed</th>'
      html += '<th part="td-head">Date</th>'
      html += '<th part="td-head">Docs</th>'
      html += '<th part="td-head">Comments</th>'
      html += '<th part="td-head">LastUpdated</th>'
      html += '<th part="td-head">CompletionDate</th>'
      html += '<th part="td-head">Location</th>'
      html += '<th part="td-head">Compliance</th>'
      html += '</tr>';

      html += '<tr>';
      html += '<td part="td-body"><button id="button-select-' + reportKey.replace(/-/g, '_') + '"  part="button-icon-small" class="material-icons button-expand mr-10 button-select">check</button></td>'
      html += `<td part="td-body"><span class="material-symbols-outlined mr-10">${report['processed'] ?? false ? "done_all" : ""}</span></td>`
      html += `<td part="td-body">${reportKey.split(';')[0]}</td>`;
      html += `<td part="td-body">${JSON.parse(report['docs']).length}</td>`;
      html += `<td part="td-body">${report['comments'].length}</td>`;
      html += `<td part="td-body">${Util.getDateTimeStrings(new Date(report['lastupdated']).getTime())}</td>`;
      html += `<td part="td-body">${new Date(parseInt(report['dateofcompletion'])).toLocaleDateString('en-US', { timeZone: 'Asia/Kolkata' })}</td>`;
      let locationname = ""
      let eventHtml = ""
      if (report['event'] != null) {
        locationname = JSON.parse(report['event'])['locationname'] ?? "";
        for (var i = 0; i < Object.keys(JSON.parse(report['event'])).length; i++) {
          if (!this.EXCLUDE_COLS_FROM_REGS.includes(Object.keys(JSON.parse(report['event']))[i].toLowerCase())) {

            eventHtml += '<td part="td-body-register">';
            eventHtml += ('<span part="td-head" style="padding-left: 0px !important">' + Object.keys(JSON.parse(report['event']))[i] + '</span>');
            eventHtml += ('<span part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + JSON.parse(report['event'])[Object.keys(JSON.parse(report['event']))[i]] + '" lineSize="4" minLength="60"></sf-i-elastic-text>' + '</span>');
            eventHtml += '</td>';

          }

        }
      }
      html += `<td part="td-body">${locationname}</td>`;
      html += '<th part="td-head">';

      // const jsonReportEvent = JSON.parse(report['comments'].reportevent);
      // console.log('jsonReportEvent', report['event']);
      if (report['event'] != null) {
        html += '<table>';
        html += '<tr>';
        html += eventHtml;
        html += '</tr>';
        html += '</table>';
      }


      html += '</th>';
      html += '</tr>';

      html += '</table>';
      html += '</div>';

    }

    html += '</div>';
    html += '</div>';

    (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html;

    const arrButtonSelect = this._SfIEventsC.querySelectorAll('.button-select') as NodeListOf<HTMLButtonElement>;

    for (let buttonSelect of arrButtonSelect) {
      buttonSelect.addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        console.log('id', id)
        const idArr = id.split("-")
        console.log('idArr', idArr)
        const sortid = idArr[2].replace(/_/g, '-')
        console.log('selected sortid', sortid)
        let reportData = JSON.parse(reportsData[sortid]);
        console.log('selectedReportData', reportData);
        this.renderComplianceSelector(sortid, reportData.processed ?? false);
      })
    }

    const arrButtonCheck = this._SfIEventsC.querySelectorAll('.button-check') as NodeListOf<HTMLButtonElement>;
    for (let buttonCheck of arrButtonCheck) {
      buttonCheck.addEventListener('click', async (ev: any) => {

        const id = ev.target.id;
        console.log('id', id)
        const idArr = id.split("-")
        console.log('idArr', idArr)
        const sortid = idArr[2].replace(/_/g, '-')
        console.log('selected sortid', sortid)
        let complianceEntityId = sortid.split(';')[1]
        let complianceLocationId = sortid.split(';')[2]
        let complianceId = sortid.split(';')[3]
        let mmddyyyy = sortid.split(';')[0];
        let mm = mmddyyyy.split('/')[0];
        let dd = mmddyyyy.split('/')[1];
        let yyyy = mmddyyyy.split('/')[2];
        let date = new Date(parseInt(yyyy), parseInt(mm) - 1, parseInt(dd));
        let sDateObj = date
        sDateObj.setDate(date.getDate() - 3)
        let day = '' + sDateObj.getDate();
        let month = '' + (sDateObj.getMonth() + 1);
        let year = '' + sDateObj.getFullYear();
        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        let sDate = month + "/" + day + "/" + year
        let eDateObj = date
        eDateObj.setDate(date.getDate() + 6)
        day = '' + eDateObj.getDate();
        month = '' + (eDateObj.getMonth() + 1);
        year = '' + eDateObj.getFullYear();
        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        let eDate = month + "/" + day + "/" + year
        let urlBody: any = { "projectid": this.projectId, "userprofileid": this.userProfileId, "role": this.myRole, "entityid": complianceEntityId, "countryid": "", "functionid": "", "locationid": complianceLocationId, "tagid": this.tagId, "adhoc": "false", "exclusivestartkey": 0, "sdate": sDate, "edate": eDate, "view": "location", "year": this.calendarStartYYYY, "contractstartdate": this.contractStartDate };
        let url = "https://" + this.apiId + "/getallcountryevents6";
        const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
        const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
        this._SfLoader.innerHTML = '';
        if (xhr.status == 200) {

          const jsonRespose = JSON.parse(xhr.responseText);
          console.log('jsonRespose', jsonRespose);
          let arrCompliances = (await this.fetchPresignedUrl(jsonRespose.signedUrlGet));
          if (arrCompliances == null || Object.keys(arrCompliances).length === 0) {
            this.setSuccess('Zombie detected!')
            setTimeout(() => { this.clearMessages() }, 5000);
          } else {

            let zombie: boolean = true;
            Object.keys(arrCompliances).forEach((key: string) => {
              console.log('checking', key, mm + "/" + dd);
              if (key == mm + "/" + dd) {
                const compliances = arrCompliances[key] as Array<any>;
                compliances.forEach((compliance: any) => {
                  console.log('checking', compliance.id, complianceId);
                  if (compliance.id == complianceId) {
                    zombie = false;
                  }
                })

              }

            });

            if (zombie) {
              this.setSuccess('Zombie detected!')
              setTimeout(() => { this.clearMessages() }, 5000);
            } else {
              this.setSuccess('Not a Zombie!')
              setTimeout(() => { this.clearMessages() }, 5000);
            }

          }
          await this.fetchPresignedUrlDelete(jsonRespose.signedUrlDelete);
          console.log('receivedCompliacnes', arrCompliances)
          // this.renderReportsComplainces(arrCompliances, sortid);
        } else {
          if (xhr.status == 401) {
            let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
            this.dispatchEvent(changeEvent);
          }
          if (xhr.status === 404) {

            this.showChosenProject();
            (this._SfTitleChosenProject as HTMLElement).innerHTML = (this._SfProject[0].querySelector('#sf-i-project') as SfIForm).selectedTexts()[0];
            this.renderChosenProject();

          } else {
            const jsonRespose = JSON.parse(xhr.responseText);
            this.setError(jsonRespose.error);
            setTimeout(() => {
              this.clearMessages();
            }, 5000);
          }

        }
      })
    }

  }
  renderComplianceSelector = (sortid: string, processed: boolean = false) => {
    let html = ''
    html += '<div class="w-100-m-0 d-flex flex-col justify-center">'
    html += '<div class="w-100-m-0 d-flex justify-start">'
    html += '<button id="button-reports-date-selector-back" part="button-icon" class="button-icon"><span class="material-icons">keyboard_backspace</span></button>'
    html += '</div>'
    html += `<sf-i-form id="input-user" class="m-20" name="Users" label="Select Reporter" apiId="${this.apiIdUserProfiles}" mode="select" searchPhrase="${this.projectName}" selectProjection="name" ignoreProjections="[&quot;updatetype&quot;,&quot;project&quot;,&quot;tagtype&quot;,&quot;userid&quot;,&quot;usermap&quot;,&quot;kra&quot;,&quot;role&quot;,&quot;trainingstatute&quot;,&quot;shortid&quot;,&quot;shortnumid&quot;,&quot;lastmodifiedby&quot;,&quot;lastmodifiedtime&quot;]"></sf-i-form>`
    html += `<sf-i-form id="input-entity-tags" class="m-20" name="Tags" label="Select Entity" apiId="${this.apiIdTags}" mode="select" searchPhrase="${this.projectName}&Entity" selectProjection="name" ignoreProjections="[&quot;updatetype&quot;,&quot;project&quot;,&quot;tagtype&quot;,&quot;shortid&quot;,&quot;shortnumid&quot;,&quot;lastmodifiedby&quot;,&quot;lastmodifiedtime&quot;]"></sf-i-form>`
    html += `<sf-i-form id="input-location-tags" class="m-20" name="Tags" label="Select Location" apiId="${this.apiIdTags}" mode="select" searchPhrase="${this.projectName}&Location" selectProjection="name" ignoreProjections="[&quot;updatetype&quot;,&quot;project&quot;,&quot;tagtype&quot;,&quot;shortid&quot;,&quot;shortnumid&quot;,&quot;lastmodifiedby&quot;,&quot;lastmodifiedtime&quot;]"></sf-i-form>`
    html += '<div class="w-100-m-0 d-flex justify-start">'
    html += '<button id="button-reports-search" part="button-icon" class="button-icon d-flex justify-between align-center ml-10" disabled><span class="material-icons">search</span>&nbsp;&nbsp;Search</button>'
    html += `<button id="button-reports-mark" part="button-icon" class="button-icon d-flex justify-between align-center ml-10"><span class="material-icons">${processed ? "remove_done" : "done_all"}</span>&nbsp;&nbsp;${processed ? "Unmark" : "Mark"} Processed</button>`
    html += '</div>';
    html += '</div>';
    (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html;
    let inputReporter = (this._SfIEventsC.querySelector('#input-user') as SfIForm)
    let inputEntityForm = (this._SfIEventsC.querySelector('#input-entity-tags') as SfIForm);
    let inputLocationForm = (this._SfIEventsC.querySelector('#input-location-tags') as SfIForm);

    inputReporter.loadMode();
    inputReporter.addEventListener('valueChanged', (ev: any) => {
      let targetForm = ev.target as SfIForm;
      let selectedReporter = targetForm.selectedTexts()[0]
      console.log('reporter selected', selectedReporter)
      checkButtonSearch()
    })
    let entityId = sortid.split(';')[1]
    inputEntityForm.selectedSearchId = entityId;
    inputEntityForm.loadMode();
    inputEntityForm.addEventListener('valueChanged', (ev: any) => {
      let targetForm = ev.target as SfIForm;
      let selectedEntity = targetForm.selectedTexts()[0]
      console.log('entity selected', selectedEntity)
      inputLocationForm.searchPhrase = this.projectName + '&Location&' + selectedEntity.replace(/\([^)]*\)/g, "");
      inputLocationForm.loadMode();
      checkButtonSearch()
    })
    let locationId = sortid.split(';')[2]
    inputLocationForm.selectedSearchId = locationId;
    inputLocationForm.loadMode();
    inputLocationForm.addEventListener('valueChanged', (ev: any) => {
      let targetForm = ev.target as SfIForm;
      let selectedLocation = targetForm.selectedTexts()[0]
      console.log('location selected', selectedLocation)
      checkButtonSearch()
    })

    let buttonBack = (this._SfIEventsC.querySelector('#button-reports-date-selector-back') as HTMLButtonElement)
    buttonBack.addEventListener('click', () => {
      this.fetchReports()
    })
    let buttonSearch = (this._SfIEventsC.querySelector('#button-reports-search') as HTMLButtonElement)
    buttonSearch.addEventListener('click', () => {
      let selectedReporterId = inputReporter.selectedValues()[0];
      let selectedEntityId = inputEntityForm.selectedValues()[0];
      let selectedLocationId = inputLocationForm.selectedValues()[0];
      this.fetchReportCompliances(selectedReporterId, selectedEntityId, selectedLocationId, sortid, processed)
    })

    let buttonMark = (this._SfIEventsC.querySelector('#button-reports-mark') as HTMLButtonElement)
    buttonMark.addEventListener('click', () => {
      let [mmddyyyy, entityid, locationid, complianceid] = sortid.split(';');
      let year = this.getFinancialYear(mmddyyyy)
      this.markReport(mmddyyyy, entityid, locationid, complianceid, year, !processed)
    })
    function checkButtonSearch() {
      let selectedReporterId = inputReporter.selectedValues()[0];
      let selectedEntityId = inputEntityForm.selectedValues()[0];
      let selectedLocationId = inputLocationForm.selectedValues()[0];
      if (selectedReporterId != null && selectedEntityId != null && selectedLocationId != null) {
        buttonSearch.disabled = false;
      } else {
        buttonSearch.disabled = true;
      }
    }

  }

  markReport = async (mmddyyyy: string, entityid: string, locationid: string, eventid: string, year: string, processed: boolean) => {
    console.log('marking report', eventid, processed)
    let url = "https://" + this.apiId + "/markreportprocessed";

    let urlBody: any = { "projectid": this.projectId, "eventid": eventid, "mmddyyyy": mmddyyyy, "entityid": entityid, "locationid": locationid, "year": year, "processed": processed };
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      this.setSuccess("Report " + ((processed == true) ? "marked" : "unmarked") + " successfully.");
      this.fetchReports();
      setTimeout(() => {
        this.clearMessages();
      }, 5000);
    } else {
      const jsonResponse = JSON.parse(xhr.responseText);
      this.setError(jsonResponse.error);
      setTimeout(() => {
        this.clearMessages();
      }, 5000);
    }
  }

  fetchReportCompliances = async (reporterid: string, entityid: string, locationid: string, sortid: string, processed: boolean) => {
    console.log('fetching compliances', sortid)
    let url = "https://" + this.apiId + "/geteventfromreport";

    let urlBody: any = { "projectid": this.projectId, "sortid": sortid, "reporterid": reporterid, "entityid": entityid, "locationid": locationid };
    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    const xhr: any = (await this.prepareXhr(urlBody, url, this._SfLoader, authorization, 'Preparing')) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {

      const jsonResponse = JSON.parse(xhr.responseText);
      console.log('fetch compliances jsonRespose', jsonResponse);

      if (jsonResponse.event == null) {
        this.setError("Compliance status is - " + jsonResponse.completenessstatus);
        setTimeout(() => {
          this.clearMessages();
        }, 5000);
      } else {
        let returnedEvent = jsonResponse.event
        let arrCompliances = [(returnedEvent)];
        let assocEvents: any = {};
        let mmdd = (returnedEvent.duedate).split('/')[1] + "/" + (returnedEvent.duedate).split('/')[0];
        assocEvents[mmdd] = arrCompliances;
        this.renderReportsCompliances(assocEvents, sortid, processed);
      }
    } else {
      const jsonResponse = JSON.parse(xhr.responseText);
      this.setError(jsonResponse.error);
      setTimeout(() => {
        this.clearMessages();
      }, 5000);
    }
  }

  renderReportsCompliances = (compliancesData: any, sortid: string, processed: boolean) => {
    let eventsData: any = {}
    let complianceId = sortid.split(';')[3]
    console.log('renderReportsComplainces', compliancesData, complianceId);
    for (let dateStr of Object.keys(compliancesData)) {
      for (var j = 0; j < (compliancesData[dateStr] as Array<any>).length; j++) {
        console.log('renderReportsComplainces comparing id', compliancesData[dateStr][j].id, complianceId);
        if (compliancesData[dateStr][j].id == complianceId && this.getCompletenessStatus(JSON.parse(JSON.stringify(compliancesData[dateStr][j]))) == "not-started") {
          console.log(compliancesData[dateStr][j])
          // if(compliancesData[dateStr][j].id == complianceId){
          if (eventsData[dateStr] == null) {
            eventsData[dateStr] = []
          }
          eventsData[dateStr].push(compliancesData[dateStr][j])
        }
      }
    }
    console.log('eventsData', eventsData)
    let html = '';
    html += '<div class="w-100-m-0 d-flex justify-start mb-20">'
    html += '<button id="button-reports-date-selector-back" part="button-icon" class="button-icon"><span class="material-icons">keyboard_backspace</span></button>'
    html += '</div>'
    html += '<div id="stream-event-next" part="stream-event-list" class="stream-event-list">';

    for (var i = 0; i < Object.keys(eventsData).length; i++) {

      let mmdd: string = Object.keys(eventsData)[i];

      //console.log('mmdd', mmdd);
      //console.log('mmddevent', mmdd,eventsData[role][mmdd]);


      if (eventsData[mmdd] != null) {
        html += '<div part="stream-event-selected" class="d-flex stream-event-selected mb-5">';
        html += '<div part="stream-event-selected-date">' + (mmdd.split("/")[1] + "/" + mmdd.split("/")[0]) + ' |</div>';
        html += '<div class="stream-event-list-container flex-grow" id="date-' + mmdd.replace(/\//g, '-') + '">'

        for (var j = 0; j < (eventsData[mmdd] as Array<any>).length; j++) {
          let eventHtml = '';
          eventsData[mmdd][j]['mmdd'] = mmdd

          let functionStr = eventsData[mmdd][j]['functions'][0]
          if (functionStr.indexOf(';') >= 0) {
            functionStr = functionStr.split(';')[0].replace(/\([^)]*\)/g, "");
          }
          console.log('function', functionStr)
          var partStatus = "";
          var lateStatus = "";
          var complianceStatus = "";
          partStatus = this.getCompletenessStatus(JSON.parse(JSON.stringify(eventsData[mmdd][j])));
          if (partStatus != "not-started") { continue; }
          lateStatus = this.getTimelinessStatus(mmdd, JSON.parse(JSON.stringify(eventsData[mmdd][j])), partStatus);
          complianceStatus = this.getComplianceStatus(partStatus, lateStatus, JSON.parse(JSON.stringify(eventsData[mmdd][j])).percentage, JSON.parse(JSON.stringify(eventsData[mmdd][j])));
          // notStarted = notStarted + (partStatus == "not-started" ? 1 : 0);
          // pendingApproval = pendingApproval + (partStatus == "pending-approval" ? 1 : 0);
          // rejected = rejected + (partStatus == "rejected" ? 1 : 0);
          // approved = approved + (partStatus == "approved" ? 1 : 0);
          // inTime = inTime + (lateStatus == "in-time" ? 1 : 0); 
          // pastDueDate = pastDueDate + (lateStatus == "past-due-date" ? 1 : 0);
          // lateReported = lateReported + (lateStatus == "late-reported" ? 1 : 0);
          // lateApproved = lateApproved + (lateStatus == "late-approved" ? 1 : 0);
          // lateExecuted = lateExecuted + (lateStatus == "late-executed" ? 1 : 0);
          // scheduled = scheduled + (complianceStatus == "scheduled" ? 1 : 0);
          // partiallyComplied = partiallyComplied + (complianceStatus == "partially-complied" ? 1 : 0);
          // notComplied = notComplied + (complianceStatus == "not-complied" ? 1 : 0);
          // complied = complied + (complianceStatus == "complied" ? 1 : 0);

          eventsData[mmdd][j][this.FLOW_GRAPH_COMPLETENESS] = partStatus;
          eventsData[mmdd][j][this.FLOW_GRAPH_TIMELINESS] = lateStatus;
          eventsData[mmdd][j][this.FLOW_GRAPH_COMPLIANCE] = complianceStatus;
          // let thisRole = ""
          // if ((JSON.stringify(eventsData[role][mmdd][j].reporters)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Reporter'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].approvers)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Approver'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].functionheads)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Functionhead'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].auditors)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Auditor'
          // } else if ((JSON.stringify(eventsData[role][mmdd][j].viewers)).indexOf(this.userProfileId) >= 0){
          //   thisRole = 'Viewer'
          // } 
          eventHtml += '<div class="stream-events-container flex-grow">';
          eventHtml += '<div class="hidden-tags hide">' + JSON.stringify(eventsData[mmdd][j]['tags']) + '</div>'
          eventHtml += '<div class="hidden-title hide"><table><thead><th part="badge-filtered"><i>not filtered</i></th></thead></table></div>'
          eventHtml += '<div part="stream-events-event-title" class="stream-events-event-title d-flex align-center pl-5 pb-5 mb-10">' + '<button id="button-unmapped-expand-' + mmdd.replace('/', '-') + '-' + j + '" part="button-icon-small" class="material-icons button-expand mr-10">check</button>' + '<sf-i-elastic-text exportparts="highlight,highlight-count" text="' + eventsData[mmdd][j]['obligationtitle'] + '" minLength="100"></sf-i-elastic-text>&nbsp;&nbsp;' + '<div part="td-body"><sf-i-elastic-text exportparts="highlight,highlight-count" text="' + eventsData[mmdd][j]["locationname"].replace(/ *\([^)]*\) */g, "") + '" minLength="30"></sf-i-elastic-text></div>&nbsp;&nbsp;<div part="upcoming-function">' + functionStr + '</div>&nbsp;&nbsp;' + this.renderStatusHtml(partStatus, lateStatus, complianceStatus, i) + '</div>';
          eventHtml += '</div>';
          html += eventHtml

        }
        html += '</div>';
        html += '</div>';
      }
    }
    html += '</div>';

    (this._SfIEventsC.querySelector('#reports-data') as HTMLDivElement).innerHTML = html;

    const arrButtonSelect = this._SfIEventsC.querySelectorAll('.button-expand') as NodeListOf<HTMLButtonElement>;

    for (let buttonSelect of arrButtonSelect) {
      buttonSelect.addEventListener('click', (ev: any) => {
        const id = ev.target.id;
        const idArr = id.split("-")
        const mmdd = idArr[3] + "/" + idArr[4];
        const j = idArr[5];
        let eventObj = eventsData[mmdd][j];
        console.log('move reporting', mmdd + '/' + this.calendarStartYYYY, sortid)
        this.submitUpdateReporting(mmdd + '/' + this.calendarStartYYYY, eventObj['entityid'], eventObj['locationid'], sortid);
      })
    }

    let buttonBack = (this._SfIEventsC.querySelector('#button-reports-date-selector-back') as HTMLButtonElement)
    buttonBack.addEventListener('click', () => {
      this.renderComplianceSelector(sortid, processed)
    })
  }

  submitUpdateReporting = async (mmddyyyy: string, entityid: string, locationid: string, sortid: string) => {
    let url = "https://" + this.apiId + "/updatereportdate";

    const authorization = btoa(Util.readCookie('email') + ":" + Util.readCookie('accessToken'));
    console.log('this.myroles', this.myroles)
    const xhr: any = (await this.prepareXhr({ "projectid": this.projectId, "mmddyyyy": mmddyyyy, "entityid": entityid, "locationid": locationid, "sortid": sortid }, url, this._SfLoader, authorization)) as any;
    this._SfLoader.innerHTML = '';
    if (xhr.status == 200) {
      this.setSuccess("update successful!");
      setTimeout(() => {
        this.clearMessages();
        this.fetchReports();
      }, 3000)

    } else {
      if (xhr.status == 401) {
        let changeEvent = new CustomEvent('tokenExpired', { bubbles: true });
        this.dispatchEvent(changeEvent);
      }
      if (xhr.status === 404) {
        const jsonRespose = JSON.parse(xhr.responseText);
        this.setError(jsonRespose.error);
      }

    }
  }

  loadMode = async () => {

    Chart.register(...registerables);
    Chart.register(exportBackgroundPlugin);
    //Chart.register(Colors);

    if (this.mode == "rcmnotifications") {

      this.loadRcmNotifications();


    } else if (this.mode == "rcm") {

      this.renderRcmTabs();
      ((this._SfRcmTabContainer as HTMLDivElement).querySelector('#rcm-tab-compliances') as HTMLButtonElement).click();

    } else if (this.mode == "onboarding") {

      //this.myOnboardingTab = this.TAB_STATUTES;

      this.renderOnboardingTabs();
      // this.clickOnboardingTabs();
      //this.loadOnboardingStatutes();
      //((this._SfOnboardingTabContainer as HTMLDivElement).querySelector('#onboarding-tab-compliances') as HTMLButtonElement).click();

    } else if (this.mode == "admin") {

      this.showChooseProject();
      this.initListenersAdmin();

    } else if (this.mode == "downloader") {
      setTimeout(() => {
        this.initDecryptView();
      }, 500)
    } else if (this.mode == "next") {
      // this.fetchNext(0)
      this.renderRoleTabsNext(0, false)
    } else if (this.mode == "reports") {
      this.fetchReports();
    } else if (this.mode == "viewer") {
      this.enableCustom();
      this.selectedTab = this.TAB_CUSTOM
      this.renderCustom();
      this.renderWithFeatures(this.sdate, this.edate, "", "yes")
    } else {

      this.flowGraph = this.FLOW_GRAPH_COMPLETENESS;
      this.enableCalendar();
      this.initInputs();
      this.initCalendar();
      let tempRole = this.myRole;
      if (tempRole == "") {
        this.myRole = this.TAB_REPORTER;
      }
      this.renderRoleTabs();
      if (tempRole != "") {
        this._SfRoleTabContainer.innerHTML = '';
      }
      // this.selectedFeatures = this.getFeatures()
      //console.log('stream received', this.stream, this.TAB_STREAM, this.TAB_YEAR);

      if (this.stream == this.TAB_YEAR) {
        this.renderTabs(this.TAB_YEAR);
        ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-year') as HTMLButtonElement)?.click();
      } else {
        //console.log('stream received rendering year', this.stream);
        this.selectedFeatures = Util.getFeatures();
        for (let feature of this.selectedFeatures) {
          if (this.getFeatures().indexOf(feature) < 0) {
            this.selectedFeatures = ['compliances']
            break;
          }
        }
        if (this.selectedFeatures.indexOf('contracts') >= 0) {
          this.renderTabs(this.TAB_CUSTOM);
          ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
        } else {
          if (this.myRole == this.TAB_VIEWER) {
            this.renderTabs(this.TAB_CUSTOM);
            ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-custom') as HTMLButtonElement)?.click();
          } else {
            let userAdHocCheckTime = Util.getUserAdhocCheckTime();
            this.flagAdhoc = true;
            if (userAdHocCheckTime != null) {
              let adHocCheckTime = new Date(parseInt(userAdHocCheckTime));
              let currentTime = new Date();
              if (adHocCheckTime.getMonth() == currentTime.getMonth()) {
                this.flagAdhoc = false
              }
            }
            console.log('FlagAdHoc', this.flagAdhoc, this.selectedFeatures)
            if (this.flagAdhoc && this.selectedFeatures.indexOf('contracts') < 0 && this.selectedFeatures.indexOf('licenses') < 0 && this.selectedFeatures.indexOf('rcmresources') < 0) {
              this.renderTabs(this.TAB_ADHOC);
              ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-adhoc') as HTMLButtonElement)?.click();
            } else {
              this.renderTabs(this.TAB_STREAM);

              ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
            }
          }
        }
        // this.renderTabs(this.TAB_STREAM);
        // ((this._SfTabContainer as HTMLDivElement).querySelector('#calendar-tab-month') as HTMLButtonElement)?.click();
      }
      //await this.fetchUserCalendar_2();


      // if(this.events != null && !this.foundCalendarInLocal()) {
      //   this.renderTabs(this.TAB_YEAR);
      //   this.renderCalendar();
      // }

    }

  }

  constructor() {
    super();
  }

  protected override firstUpdated(_changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>): void {

    this.loadMode();

  }

  override connectedCallback() {
    super.connectedCallback()
  }

  override render() {
    console.log('rendering', this.mode);
    if (this.mode == "rcmnotifications") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          
          <div class="d-flex justify-center mb-20 flex-wrap" part="rcm-container" id="rcm-container">

          </div>
          
          
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;

    } else if (this.mode == "rcm") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          
          <div class="d-flex justify-center mb-20 flex-wrap" id="rcm-tab-container">

          </div>
          
          <div class="d-flex justify-center">
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="rcm-compliance-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="rcm-projects-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="rcm-date-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="rcm-confirm-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="rcm-jobs-container">
              
            </div>
          </div>
          
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;

    } else if (this.mode == "onboarding") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          
          <div class="d-flex mb-20 flex-wrap" id="onboarding-status-container">

          </div>

          <div class="d-flex justify-center mb-20 flex-wrap" id="onboarding-tab-container">

          </div>
          
          <div class="d-flex justify-center">
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="statutes-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="compliances-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="countries-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="entities-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="locations-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch w-100" id="functions-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="tags-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="reporters-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="approvers-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="functionheads-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="auditors-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="viewers-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="docs-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="makercheckers-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="duedates-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="extensions-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="alertschedules-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="activations-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="invalidations-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="triggers-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="internalcontrols-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="reportedlocations-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="signoff-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="calendar-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="suspense-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="gov-locations-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="gov-users-container">
              
            </div>
          </div>
          
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;


    } else if (this.mode == "admin") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <div class="SfIEventsC">
            
          <div class="d-flex justify-center">
            <h1 part="title">${this.name}</h1>
          </div>
          <div class="d-flex justify-center">
            <div part="badge" class="badge">Admin</div>
          </div>
          <br />
          <div class="loader-element"></div>
          <div class="choose-project" class="d-flex justify-center align-start">
            <div class="d-flex flex-grow justify-center align-start">
              <h3 part="results-title" id="title-choose-project" class="m-0">Choose Project</h3>
            </div>
          </div>
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div class=" main-container">
                <div class="chosen-project" class="d-flex justify-center align-start">
                  <div class="d-flex flex-grow justify-between align-start">
                    <div class="d-flex justify-center">
                      &nbsp;<button id="button-back-chosen-project" part="button-icon" class="button-icon"><span class="material-icons">keyboard_backspace</span></button>
                      &nbsp;<button part="button-icon" class="invisible button-icon"><span class="material-icons">keyboard_backspace</span></button>
                    </div>
                    <h3 part="results-title" id="title-chosen-project" class="m-0">Project Name</h3>
                    <div class="d-flex justify-center">
                      <button id="button-sync-chosen-project" part="button-icon" class="button-icon"><span class="material-icons">sync</span></button>
                      &nbsp;
                      <button id="button-map-chosen-project" part="button-icon" class="button-icon"><span class="material-icons">person_add</span></button>
                      &nbsp;
                    </div>
                  </div>
                </div>
                <div class="chosen-mapping" class="d-flex justify-center align-center">
                  <div class="d-flex flex-grow justify-between align-start">
                    <div>
                      &nbsp;
                      <button id="button-back-chosen-mapping" part="button-icon" class="button-icon"><span class="material-icons">keyboard_backspace</span></button>
                      <button part="button-icon" class="invisible button-icon"><span class="material-icons">calendar_month</span></button>
                    </div>
                    <h3 part="results-title" id="title-chosen-mapping" class="m-0">Project Name</h3>
                    <div>
                      <button id="button-back-sync-mapping" part="button-icon" class="button-icon"><span class="material-icons">cloud_download</span></button>
                      <button id="button-back-calendar-mapping" part="button-icon" class="invisible button-icon"><span class="material-icons">calendar_month</span></button>
                      &nbsp;
                    </div>
                  </div>
                </div>
                <div class="choose-project" class="d-flex justify-center align-start">
                  <div class=" mt-20">
                    <slot name="project"></slot>
                  </div>
                </div>
                <div id="container-chosen-project" class="chosen-project hide d-flex justify-center align-start mt-20">
                  
                </div>
                <div class="chosen-project d-flex justify-center flex-wrap" id="tab-container">

                </div>
              
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="calendar-container">
                  
                </div>
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="stream-container">
                  
                </div>
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="upcoming-container">
                  
                </div>
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="this-container">
                  
                </div>
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="past-container">
                  
                </div>
                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="custom-container">
                  
                </div>

                <div class="chosen-project d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="adhoc-container">
                  
                </div>

                <div class="chosen-mapping d-flex justify-center mt-20" id="mapping-tab-container">

                </div>
                <div class="chosen-mapping d-flex flex-col mb-100" id="mapping-container">
                </div>
              </div>
              <div class="rb"></div>
          </div>
          <div id="detail-container" class="hide" part="detail-container"></div>
          <div id="detail-list-container" class="hide" part="detail-list-container">
          </div>
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;

    } else if (this.mode == "downloader") {
      /* eslint-disable lit/no-unknown-attribute */
      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <div class="SfIEventsC">
          <div class="d-flex justify-center">
              <h1 part="title">${this.name}</h1>
          </div>
          <div id="decrypt-container" class="d-flex flex-col justify-center mt-20">
            <div class="d-flex mb-10">
              <div class="lb" part="lb"></div>
              <div class="d-flex align-end justify-between flex-grow">
                <div class="d-flex flex-col">
                  <sf-i-form id="sf-i-project-decrypt" class="mr-10" name="Projects" label="Select Project *" apiid="dnytrdlrmxgsy.cloudfront.net/project" mode="multiselect-dropdown" selectprojection="name" searchphrase="" ignoreprojections="[&quot;locations&quot;,&quot;plan&quot;,&quot;logo&quot;,&quot;shortid&quot;,&quot;plan&quot;]" mandatory>
                  </sf-i-form>
                </div>
                <div class="d-flex flex-col">
                  <label>Decrypt Utility</label>
                  <div class="d-flex align-end">
                    <input part="input" id="input-decrypt" type="text" placeholder="file key" />.json&nbsp;&nbsp;
                    <button id="button-decrypt" part="button-icon-small" class="material-icons button-icon" disabled>download</button>
                  </div>
                  <div class="loader-element"></div>
                </div>
              </div>
              <div class="rb" part="rb"></div>
            </div>
            <div class="d-flex justify-center">
              <div class="lb" part="lb"></div>
              <div class="d-flex flex-col">
                <div class="d-flex justify-center gone">
                </div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
                <div class="div-row-notif div-row-submit">
                  <div part="notifmsg" class="div-row-notif-message"></div>
                </div>
              </div>
              <div class="rb" part="rb"></div>
            </div>
          </div>
        </div>

      `;
      /* eslint-disable lit/no-unknown-attribute */
    } else if (this.mode == "next") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          <div class="d-flex" id="role-tab-container">
          </div>
          <div class="d-flex mb-20" id="status-tab-container" part="status-tab-container">
          </div>
          <div id="next-calendar-data" class="calendar-right-data d-flex w-100">
            <button id="button-load-next" part="button-icon" class="d-flex align-center button-icon align-self-start ml-5">View Obligations<span class="material-symbols-outlined">keyboard_arrow_down</span></button>
          </div>
          <div id="detail-container" class="hide" part="detail-container">
          </div>
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;
    } else if (this.mode == "reports") {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          <div id="reports-data" class="calendar-right-data d-flex flex-col w-100">
          </div>
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;
    } else {

      return html`
          
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <div class="SfIEventsC">
          
          <div class="d-flex justify-center">
              <div class="loader-element"></div>
          </div>
          
          <div class="d-flex justify-center mb-20" id="role-tab-container">

          </div>
          
          <div class="d-flex justify-center" id="tab-container">

          </div>
          <div class="d-flex justify-center">
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="stream-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="upcoming-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="this-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="past-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="custom-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="calendar-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="find-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="adhoc-container">
              
            </div>
            <div class="d-flex flex-grow flex-wrap justify-start align-stretch scroll-x" id="register-container">
              
            </div>
          </div>
          <div id="report-summary-container" class="hide" part="report-summary-container">
          </div>
          <div id="detail-container" class="hide" part="detail-container"></div>
          <div id="detail-list-container" class="hide" part="detail-list-container">
          </div>
          <div class="d-flex justify-between">
              <div class="lb"></div>
              <div>
                <div class="div-row-error div-row-submit gone">
                  <div part="errormsg" class="div-row-error-message"></div>
                </div>
                <div class="div-row-success div-row-submit gone">
                  <div part="successmsg" class="div-row-success-message"></div>
                  <div part="successmsgbtncontainer" class="div-row-success-message-btn-container"></div>
                </div>
              </div>
              <div class="rb"></div>
          </div>
        </div>

      `;
    }

  }

}

declare global {
  interface HTMLElementTagNameMap {
    'sf-i-events': SfIEvents;
  }
}