ebc8f72c0de4f358888e054eafafed01179dc06361048ecaf2b74665ced339c0

Source Code:

$(function(){
  
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  
  function request(url) {
    return new Promise(function (resolve, reject) {
      const xhr = new XMLHttpRequest();
      xhr.timeout = 2000;
      xhr.onreadystatechange = function(e) {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            resolve(xhr.response)
          } else {
            reject(xhr.status)
          }
        }
      }
      xhr.ontimeout = function () {
        reject('timeout')
      }
      xhr.open('get', url, true)
      xhr.send();
    })
  }
  let getPermalinkFromURL = (url) => {
    return url.substring(url.indexOf('/programs/') + 10).split('?')[0]
  }
  let getStoreFromURL = (url) => {
    return url.substring(0, url.indexOf('/programs/'))
  }
  let isValidDate = (d) => {
    return d instanceof Date && !isNaN(d);
  }
  let getOrdinalNum = (n) => {
    return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
  }
  let renderGoLiveButton = () => {
    console.log('renderGoLiveButton')
    let liveCountDown = document.querySelector('.live-stream-countdown');
    let countDownFinished = true;
    document.querySelectorAll('.countdown__value').forEach(val => {
      if (val.innerText !== '00') {
        countDownFinished = false;
      }
    })
    if (liveCountDown) {
      if (countDownFinished) {
        console.log('render new go live button because countdown finished')
        $('.register-button').hide()
        let href = $('.register-button').attr('href')
        let markup = `<a class="go-to-zoom" href="${href}" target="_blank">Go to Zoom</a>`
        document.querySelector('.cbt-action.cbt--share-button.s-button').insertAdjacentHTML('afterend', markup)
      }
    }
    if (document.querySelector('.live-event .player')) {
      let hasWebinarLink = false
      
      $('.program-description-text').find('a').each((i, link) => {
        if ($(link).attr('href').includes('/webinar/register/') || $(link).attr('href').includes('zoom.us')) {
          hasWebinarLink = true
        }
      })
      
      console.log('hasWebinarLink: ' + hasWebinarLink)
      if (hasWebinarLink) {
        console.log('render new go live button because live player started')
        let href = $('.program-description-text').find('a').attr('href')
        let markup = `<a class="go-to-zoom" href="${href}" target="_blank">Go to Zoom</a>`
        document.querySelector('.cbt-action.cbt--share-button.s-button').insertAdjacentHTML('afterend', markup)
      }
      
    }
  }
  let replaceRelatedTitle = () => {
    let categoryName = document.querySelector('.cbt-tabs--categories .s-button.rounded > div').innerText
    let relatedTitle = document.querySelector('.cbt-related-title')
    relatedTitle.innerText = ''
    relatedTitle.insertAdjacentHTML('beforeend',  `Also in <strong>${categoryName}</strong>`)
  }
  let replaceZoomLink = () => {
    //console.log('replaceZoomLink')
    let URL = `${getStoreFromURL(document.location.href)}/api/contents/${getPermalinkFromURL(document.location.href)}`;
    let program = request(URL);
    let getAccessButton = document.querySelector('.access-screen--btn')  
    if (getAccessButton) {
      $('.container.cbt-program').addClass('no-add-to-calendar')
    }
    program.then(function(data){
      let program = JSON.parse(data)
      if ($(program.description).find('a').length) {
        
        let hasWebinarLink = false
      
        $('.program-description-text').find('a').each((i, link) => {
          if ($(link).attr('href').includes('/webinar/register/') || $(link).attr('href').includes('zoom.us')) {
            hasWebinarLink = true
          }
        })
        
        console.log('hasWebinarLink: ' + hasWebinarLink)
        
        if (hasWebinarLink) {
          //console.log('check condition')
          if (!location.href.includes('user_share')) {
            if (getAccessButton) {
              getAccessButton.href = $(program.description).find('a').attr('href');
              getAccessButton.innerText = 'Sign up to Switch+'
            } else {
              renderRegisterButton($(program.description).find('a').attr('href'))
              renderGoLiveButton()
            }
            $('.cce-area').attr('data-zoom-link', $(program.description).find('a').attr('href')) 
            $('.cce-area').attr('data-live-strart', program.short_description) 
          }
        }
      } else {
          //console.log('no zoom link in description!')
          let replay = false;
          program.categories.forEach(categoryId => {
            if (categoryId == 44029) {
              replay = true;
            }
          })
          //console.log(program)
          if (replay) {
            let link = `${getStoreFromURL(document.location.href)}${program.url}`
            if ($('.cce-area').attr('data-zoom-link')) {
              link = $('.cce-area').attr('data-zoom-link')
            }
            let title = 'Reminder: ' + program.title.replace('&', 'and').replace('#', '');
            title = title.replace('&', 'and')
            let start = new Date(program.short_description.split('|')[0]);
            let duration = 30;
            let replayCalendar = createCalendar({
              options: {
                class: 'add-calendar-custom-class'
              },
              data: {
                // Event title
                title: title,
                // Event Address
                address: link,
                // Event start date
                start: start,
                // Event duration (IN MINUTES)
                duration: duration,
                // Event Description
                description: program.description
              }
            });
            let replayModal = new tingle.modal({
              footer: true,
              stickyFooter: false,
              closeMethods: ['overlay', 'button', 'escape'],
              closeLabel: "Close",
              cssClass: ['custom-modal', 'replay-modal']
            });
            replayModal.setContent(`
              <img class="close-popup-button" src="https://s3.amazonaws.com/unode1/assets/12090/gWyn07TNaDG34y3GFoQN_times-solid-new.svg">
              <h3 class="add-calendar-title">Your spot has been confirmed!</h3>
              <p>The livestream will be hosted from this page <br> Add a reminder in your schedule</p>
              <div id="addToCalendarReplay"></div>
            `);
            document.querySelector('#addToCalendarReplay').appendChild(replayCalendar);
            $('.close-popup-button').on('click', function(){
              replayModal.close();
            })
            if (getAccessButton) {
              
            } else {
              $('.program-add-to-calendar').hide()
              if ($(program.description).find('a').attr('href')) {
                renderRegisterButton($(program.description).find('a').attr('href'))
              } else {
                console.log('register string new popup')
                let markup = `<a class="register-button" href="">Register</a>`
                container = $('.access-screen__content > div')
                container.append(markup)
                $('.register-button').on('click', function(e){
                  e.preventDefault();
                  replayModal.open()
                })
              }
              
            }
          }
            
        }
    })
  }
  let renderRegisterButton = (link) => {
    let webinarLink = link || $('.cce-area').attr('data-zoom-link')
    let markup = `<a class="register-button" href="${webinarLink}">Register</a>`
    container = $('.access-screen__content > div')
    container.append(markup)
  }
  let renderAddToCalendarButton = () => {
    let URL = `${getStoreFromURL(document.location.href)}/api/contents/${getPermalinkFromURL(document.location.href)}`;
    let program = request(URL);
    program.then(function(data){
      let program = JSON.parse(data)
      //console.log(program)
      let ationsContainer = document.querySelector('.cbt-header')
      let markup = `
        <button class="program-add-to-calendar">
          <i class="icon-calendar small"></i>
          Add a reminder
        </button>
      `
      if (program.content_type === "live_event") {
        markup = `
          <button class="program-add-to-calendar">
            <i class="icon-calendar small"></i>
            Add a reminder
          </button>
        `
      }
      ationsContainer.insertAdjacentHTML('beforeend', markup)
      var modal = new tingle.modal({
        footer: true,
        stickyFooter: false,
        closeMethods: ['overlay', 'button', 'escape'],
        closeLabel: "Close",
        cssClass: ['custom-modal'],
        onOpen: function() {
        },
        onClose: function() {
        }
      });
      $('.program-add-to-calendar').on('click', function(){
        let link = `${getStoreFromURL(document.location.href)}${program.url}`
        //console.log($('cce-area').attr('data-zoom-link'))
        if ($('.cce-area').attr('data-zoom-link')) {
          
          link = $('.cce-area').attr('data-zoom-link')
        }
        let title = 'Reminder: ' + program.title.replace('&', 'and');
        title = title.replace('&', 'and')
        //console.log(title.replace('&', 'and'))
        let start = new Date();
        let duration = program.duration.split(':')[0];
        if ($('.cce-area').attr('data-live-strart')) {
          start = new Date($('.cce-area').attr('data-live-strart').split('|')[0]) 
          duration = 60
        }
        //console.log(duration, start)
        let myCalendar = createCalendar({
          options: {
            class: 'add-calendar-custom-class'
          },
          data: {
            // Event title
            title: title,
            // Event Address
            address: link,
            // Event start date
            start: start,
            // Event duration (IN MINUTES)
            duration: duration,
            // Event Description
            description: program.description
          }
        });
        modal.setContent(`
          <img class="close-popup-button" src="https://s3.amazonaws.com/unode1/assets/12090/gWyn07TNaDG34y3GFoQN_times-solid-new.svg">
          <i class="icon-calendar medium"></i>
          <h3 class="add-calendar-title">Get it booked in. Add a time in your calendar for when you want to complete this session<h3>
          <div id="addToCalendar"></div>
        `);
        // console.log(myCalendar)
        document.querySelector('#addToCalendar').appendChild(myCalendar);
        
        modal.open();
        
        $('.close-popup-button').on('click', function(){
          modal.close();
        })
        
      })
    })
   
  }
  let renderNewDescriptionWithCommnets = () => {
    let tabsContainer = $('.cbt-tabs > .container')
    tabsContainer.hide()
  }
  let renderLiveEventDate = () => {
    let URL = `${getStoreFromURL(document.location.href)}/api/contents/${getPermalinkFromURL(document.location.href)}`;
    let program = request(URL);
    program.then(function(data){
      let program = JSON.parse(data)
      let date = new Date (program.short_description.split('|')[0])
      if (isValidDate(date)) {
        let dayName = days[date.getDay()];
        let monthName = monthNames[date.getMonth()]
        let dateNumber = date.getDate();
        let time = date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
        let markup = `<div class="custom-date">${dayName}, ${monthName}, ${getOrdinalNum(dateNumber)}, ${time}</div>`
        let container = $('.access-screen--wait-text')
        container.append(markup)
      }
      
      
    })
  }
  let detectProgramPage = () => {
    if (document.location.href.includes('/programs/')) {
      
      let ationsContainer = document.querySelector('.cbt-header')
      if (ationsContainer) {
        if (!ationsContainer.classList.value.includes('touched')) {
          renderAddToCalendarButton()
          ationsContainer.classList.add('touched')
        }
      }
      
      let relatedTitle = document.querySelector('.cbt-related-title')
      let categoriesText = document.querySelector('.cbt-tabs--categories .s-button.rounded > div')
      if (relatedTitle && categoriesText) {
        if (!relatedTitle.classList.value.includes('touched')) {
          replaceRelatedTitle()
          relatedTitle.classList.add('touched')
        }
      }
      
      let commnetTabButton = $('.cbt-tabs--tab-link:nth-of-type(2)')[0]
      if (commnetTabButton) {
        if (!commnetTabButton.classList.value.includes('touched')) {
          renderNewDescriptionWithCommnets()
          commnetTabButton.classList.add('touched')
        }
      }
      
      let coundown = document.querySelector('.live-stream-countdown') 
      if (coundown) {
        if (!coundown.classList.value.includes('touched')) {
          renderLiveEventDate()
          replaceZoomLink()
          coundown.classList.add('touched')
        }
      }
      
      let liveEvent = document.querySelector('.live-event .player')
      if (liveEvent) {
        if (!liveEvent.classList.value.includes('touched')) {
          renderGoLiveButton()
          liveEvent.classList.add('touched')
        }
      }
      
      let getAccessButton = document.querySelector('.access-screen--btn') 
      if (getAccessButton) {
        if (!getAccessButton.classList.value.includes('touched')) {
          replaceZoomLink()
          getAccessButton.classList.add('touched')
        }
      } else {
        let coundown = document.querySelector('.live-stream-countdown') 
        if (coundown) {
          if (!coundown.classList.value.includes('touched')) {
            replaceZoomLink()
            coundown.classList.add('touched')
          }
        }
      }
      
      
      
    }
    setTimeout(() => detectProgramPage(), 300)
  }
  let detectCatalogPage = () => {
    if (document.location.href.includes('/catalog')) {
      let filterButton = $('.main-filters .s-button')  
      if (filterButton.length) {
        if (!filterButton.hasClass('touched')) {
          filterButton.click()
          filterButton.addClass('touched')
        }
      }
    }
    setTimeout(() => detectCatalogPage(), 300)
  }
  detectCatalogPage()
  detectProgramPage()
  
})