let devChatEnvironments = ["pegasus.lesliespool.com", "development-na01-lesliespoolmart.demandware.net", "slalom-de-poc.s3.us-west-2.amazonaws.com"];
let uatChatEnvironments = ["staging-na01-lesliespoolmart.demandware.net"];
let prodChatEnvironments = ["intheswim.com", "www.intheswim.com"];

let myDomain;
let hostingSite;
let orgId;
let eswPath = "/embeddedservice/5.0/esw.min.js";

if (devChatEnvironments.includes(location.hostname)) {
  myDomain = "https://lesliesc2020--dev.sandbox.my.salesforce.com";
  hostingSite = "https://lesliesc2020--dev.sandbox.my.site.com/helpcenter";
  orgId = "00D7d000008qWDE";
  eswPath = myDomain + '/embeddedservice/5.0/esw.min.js';
} else if (uatChatEnvironments.includes(location.hostname)) {
  myDomain = "https://lesliesc2020--uat.sandbox.my.salesforce.com";
  hostingSite = "https://lesliesc2020--uat.sandbox.my.site.com/helpcenter";
  orgId = "00D3I0000000g29";
  eswPath = myDomain + '/embeddedservice/5.0/esw.min.js';
} else if (prodChatEnvironments.includes(location.hostname)) {

  myDomain = "https://lesliesc2020.my.salesforce.com";
  hostingSite = "https://lesliesc2020.force.com/helpcenter";
  orgId = "00D4R000001XO9r";
  eswPath = myDomain + '/embeddedservice/5.0/esw.min.js';
} else {
  console.log('This domain is not supported', location.hostname)
}

var initESW = function (gslbBaseURL) {

    // embedded_svc.addEventHandler("onChatTransferSuccessful", function (data) {
        // console.log('handle embedded_svc event onChatTransferSuccessful, connected to agent');
        embedded_svc.addEventHandler("onAgentMessage", function (data) {
            // console.log('handle embedded_svc event onAgentMessage');
            embedded_svc.liveAgentAPI.sendCustomEvent("onAgentMessage", data.liveAgentSessionKey);
        });
        embedded_svc.addEventHandler("onChasitorMessage", function (data) {
            // console.log('handle embedded_svc event onChasitorMessage');
            embedded_svc.liveAgentAPI.sendCustomEvent("onChasitorMessage", data.liveAgentSessionKey);
        });
        embedded_svc.addEventHandler("onChatEndedByChasitor", function (data) {
            // console.log('handle embedded_svc event onChatEndedByChasitor');
            embedded_svc.liveAgentAPI.sendCustomEvent("onChatEndedByChasitor", data.liveAgentSessionKey);
        });
        embedded_svc.addEventHandler("onChatEndedByAgent", function (data) {
            // console.log('handle embedded_svc event onChatEndedByAgent');
            embedded_svc.liveAgentAPI.sendCustomEvent("onChatEndedByAgent", data.liveAgentSessionKey);
        });
        embedded_svc.addEventHandler("onIdleTimeoutWarningStart", function (data) {
            // console.log('handle embedded_svc event onIdleTimeoutWarningStart');
            embedded_svc.liveAgentAPI.sendCustomEvent("onIdleTimeoutWarningStart", data.liveAgentSessionKey);
        });
    // });

    embedded_svc.settings.displayHelpButton = true; //Or false
    embedded_svc.settings.language = "en-US"; //For example, enter 'en' or 'en-US'

  embedded_svc.settings.enabledFeatures = ["LiveAgent"];
  embedded_svc.settings.entryFeature = "LiveAgent";
  // set all fields entered in the pre-chat widown into custom fields on the chat transcript object
  // fields without a value entered here - will get the value from the form itself
  embedded_svc.settings.extraPrechatFormDetails = [
    {
      label: "First Name",
      name: "FirstName",
      transcriptFields: ["First_Name__c"],
      displayToAgent: true,
    },
    {
      label: "Last Name",
      name: "LastName",
      transcriptFields: ["Last_Name__c"],
      displayToAgent: true,
    },
    {
      label: "Email",
      name: "email",
      transcriptFields: ["Email__c"],
      displayToAgent: true,
    },
    {
      label: "Subject",
      name: "Subject",
      transcriptFields: ["Subject__c"],
      displayToAgent: true,
    },

    {
      label: "Phone",
      name: "Phone",
      transcriptFields: ["Phone__c"],
      displayToAgent: true,
    },
    {
      label: "Order #",
      transcriptFields: ["Order_Number__c"],
      displayToAgent: true,
    },
  ];

  // disable creation of a contact and a case:
  // this will be handled by the chat transcript trigger that will create a case that will create a contact
  embedded_svc.settings.extraPrechatInfo = [
    {
      entityName: "Contact",
      entityFieldMaps: [
        {
          doCreate: false,
          doFind: false,
          fieldName: "LastName",
          isExactMatch: false,
          label: "Last Name",
        },
        {
          doCreate: false,
          doFind: false,
          fieldName: "FirstName",
          isExactMatch: false,
          label: "First Name",
        },
        {
          doCreate: false,
          doFind: false,
          fieldName: "Email",
          isExactMatch: false,
          label: "Email",
        },
        {
          doCreate: false,
          doFind: false,
          fieldName: "Phone",
          isExactMatch: false,
          label: "Phone",
        },
      ],
    },
    {
      entityName: "Case",
      entityFieldMaps: [
        {
          doCreate: false,
          doFind: false,
          fieldName: "Subject",
          isExactMatch: false,
          label: "Subject",
        },
        {
          doCreate: false,
          doFind: false,
          fieldName: "Order_Number__c",
          isExactMatch: false,
          label: "Order #",
        },
      ],
    },
  ];

  embedded_svc.settings.disabledMinimizedText = "Chat Now"

  embedded_svc.init(
    myDomain,
    hostingSite,
    gslbBaseURL,
    orgId,
    "ITS_Live_Agent",
    {
      baseLiveAgentContentURL: 'https://c.la1-c2-ia4.salesforceliveagent.com/content',
      deploymentId: '5724R000000PcCf',
      buttonId: '5734R000000Pd9n',
      baseLiveAgentURL: 'https://d.la1-c2-ia4.salesforceliveagent.com/chat',
      eswLiveAgentDevName: 'EmbeddedServiceLiveAgent_Parent04I4R000000bpH6UAI_17fae5a0ab1'
    }
  );
  var oldClickHandler;
  var clickHandlerOverwritten = false;

  embedded_svc.addEventHandler("onAvailability", function (data) {

    let agentIsOnline = data.isAgentAvailable ? true : false;

    if (agentIsOnline && clickHandlerOverwritten) {
      clickHandlerOverwritten = false
    }

    if (!agentIsOnline && !clickHandlerOverwritten) {
      setTimeout(function () {
        let helpButton = document.getElementsByClassName('helpButtonDisabled')
        if (helpButton && helpButton.length == 1) {
          let helpButtonEl = helpButton[0];
          oldClickHandler = helpButtonEl.onclick;
          clickHandlerOverwritten = true
          helpButtonEl.onclick = function () {
            // call the leslie code that shows the offline form and scrolls
            var $offlineChatForm = $('.offline-chat-form');
            $offlineChatForm.removeClass('d-none');
            $('html, body').animate(
              {
                scrollTop: $offlineChatForm.offset().top
              },
              2000
            );
          };
        }
      }, 200)
    }
  });

  embedded_svc.addEventHandler("onSettingsCallCompleted", function (data) {

    // get the live agent button span that contains the button text
    let helpButtonSpan = document.getElementById("helpButtonSpan");

    // make sure we have it
    if (helpButtonSpan) {

      // get the text in the help button
      let messageSpan = helpButtonSpan.querySelector(".message");
      let messageText = messageSpan.innerHTML;

      // if chat is offline, override the button onclick
      if (messageText == embedded_svc.settings.disabledMinimizedText) {

        // get the live agent button
        let helpButton = document.getElementsByClassName('helpButtonDisabled')

        // make sure we have a help button
        if (helpButton && helpButton.length == 1) {

          // get the help button
          let helpButtonEl = helpButton[0];

          helpButtonEl.style.cursor = 'pointer';

          // make sure we have an offline form
          if ($('.offline-chat-form').length) {

            // remember the click handler incase the agent comes online
            oldClickHandler = helpButtonEl.onclick;

            // indicate we have overwritten the handler
            clickHandlerOverwritten = true;

            // override help button onclick event
            helpButtonEl.onclick = function () {

              // call the leslie code that shows the offline form and scrolls
              var $offlineChatForm = $('.offline-chat-form');
              $offlineChatForm.removeClass('d-none');
              $('html, body').animate(
                {
                  scrollTop: $offlineChatForm.offset().top
                },
                2000
              );
            };
          }
        }
      }
    }

    // If #live-chat is in the url, click the live agent button to launch the chat automatically
    // If the chat is offline, scroll to the offline form
    if (location.hash && location.hash.substr(1) && location.hash.substr(1) == 'live-chat') {

      // get the live agent button span that contains the button text
      let helpButtonSpan = document.getElementById("helpButtonSpan");

      // make sure we have it
      if (helpButtonSpan) {

        // get the text in the help button
        let messageSpan = helpButtonSpan.querySelector(".message");
        let messageText = messageSpan.innerHTML;

        // if chat is offline, override the button onclick
        if (messageText == embedded_svc.settings.disabledMinimizedText) {

          // call the leslie code that shows the offline form and scrolls
          var $offlineChatForm = $('.offline-chat-form');
          $offlineChatForm.removeClass('d-none');
          $('html, body').animate(
            {
              scrollTop: $offlineChatForm.offset().top
            },
            2000
          );

        } else {
          embedded_svc.onHelpButtonClick();
        }
      }
    }
  });
};

if (!window.embedded_svc) {
  var s = document.createElement("script");
  s.setAttribute(
    "src",
    eswPath
  );
  s.onload = function () {
    initESW(null);
  };
  document.body.appendChild(s);
} else {
  initESW("https://service.force.com");
}