f1d8bc1a69452334ec9ea232cdaa7bba4e93b7d41caecf2675f8036cf92fa281

Source Code:

(function(){
  
  const FEATURED_CATEGORIES = [73102, 73122, 73105, 73107, 73123, 73110, 34526, 34888, 63305, 36795];
  const ACTIVE_CATEGORIES = [73102, 73103, 73122, 73104, 73105, 73106];
  const RELAX_CATEGORIES = [73107, 73108, 73123, 73109, 73110, 73111];
  const CHOOSE_CATEGORIES = [34526, 36626, 34888, 37070, 35454, 37072, 63305, 44029, 36795, 37076, 52846, 73109]
  
  // localStorage.setItem('user_style', '');
  //const CHOOSE_CATEGORIES = [73107, 73108, 73123, 73109, 73110, 73111]


  axios.get('/api/authors').then(function(response){
    let globalAuthors = response.data
    localStorage.setItem('globalAuthors', JSON.stringify(globalAuthors))
  })
  
  let getStoreFromURL = (url) => {
    return url.substring(0, url.indexOf('/programs/'))
  }
  
  let setBundleIdToCookie = () => {
    let url = new URL(window.location.href);
    let bundleID = url.searchParams.get('apply_product');
    if (bundleID) {
      let URL = `${getStoreFromURL(document.location.href)}/api/products/${bundleID}`;
      // let URL = `https://switchplus.online/api/products/${bundleID}`
      let bundleRequest = request(URL);
      bundleRequest.then(function(data){
        const bundle = JSON.parse(data)
        localStorage.setItem('bundle', JSON.stringify(bundle));
      }).catch(function (err) {
        console.log(err.message)
      });
    }
  }
  setBundleIdToCookie()
  
  function inviteFriendProgramInit() {
    console.log('inviteFriendProgramInit')
    let utm = '?utm_source=platform&utm_medium=videopage&utm_campaign=share'
    if (document.location.href.includes('?')) {
      utm = '&utm_source=platform&utm_medium=videopage&utm_campaign=share'
    }
    
    let modal = new tingle.modal({
      footer: false,
      stickyFooter: false,
      closeMethods: ['overlay', 'button', 'escape'],
      closeLabel: "Close",
      cssClass: ['custom-tingle', 'invite-tingle'],
      onOpen: function() {
        console.log('init copy script')
        new ClipboardJS('.copy-input--button-invite');
        
        $('.invite-popup--close').on('click', function(){
          //console.log('invite-popup--close')
          modal.close()
        })
      },
      onClose: function() {
        //console.log('modal closed');
      },
      beforeClose: function() {
        return true; // close the modal
        return false; // nothing happens
      }
    });
    
    
    let URL = `/api/ownerships`;
    let ownershipsRequest = request(URL);
    
    ownershipsRequest.then(function(data){
        let ownerships = JSON.parse(data)
        let emailSlug = 'switchplus-' + document.getElementById('body').dataset.userEmail.split('@')[0].substr(0,10).replace('+', '').replace('.', '-')
        let programSlug = document.location.href.split('https://switchplus.online/programs/')[1]
        let slug = 'switchplus-' + emailSlug.substr(0,7) + programSlug.substr(0,7)
        let shareUrl = `https://switchplus.online/pages/you_decide?&apply_product=${ownerships[0].product_id}&apply_coupon=REFERRAL&utm_source=switchplus&utm_medium=website&utm_campaign=invitecolleague&referredby=${slug}`
        let finalshareUrl = 'https://go.switchplus.online/'+slug
        let urlValue = `https://go.switchplus.online/${emailSlug}`;
        let shareValue = `${document.location.href}${utm}&user_share=${urlValue}`
        // if (!localStorage.getItem('sareUrl') || !localStorage.getItem('sareUrl').includes(emailSlug) && !localStorage.getItem('sareUrl').includes(slug)) {
          console.log('this request?')
          console.log(shareValue)
          console.log(slug)
          let linkRequest = {
            destination: shareValue,
            domain: { fullName: "go.switchplus.online" },
            slashtag: slug
          }
          let requestHeaders = {
            "Content-Type": "application/json",
            "apikey": "92758ef4b8e94747ba46f6e833c459c6"
          }
          // $.ajax({
          //   url: "https://api.rebrandly.com/v1/links",
          //   type: "POST",
          //   data: JSON.stringify(linkRequest),
          //   headers: requestHeaders,
          //   dataType: "json",
          //   success: (link) => {
          //     console.log(`Long URL was ${link.destination}, short URL is ${link.shortUrl}`);
          //     //localStorage.setItem('sareUrl', urlValue);
          //   },
          //   error: (msg) => {
          //     console.log()
          //   }
          // });
        //}
       
        
        
        
        
        let content = `
          <div class="invite-popup">
            <img class="invite-popup--close" src="https://s3.amazonaws.com/unode1/assets/10615/xUTfs0xoTKm63nOteZsi_x-icon-new.svg">
            <img class="invite-popup--icon" src="https://s3.amazonaws.com/unode1/assets/10615/KsADnsCmSeKuFDug0Sbh_Group%205.svg">
            <h2 class="invite-popup--title">Invite your team</h2>
            <p class="invite-popup--subtitle">There’s something for everyone. If you know someone on your team who is looking to get more active or find activities for their kids - share the love!</p>
            <div class="invite-popup--share">
              <a href="mailto:?subject=Join me on Switch%2B&body=Sending you an invite for Switch+ - it’s a platform where you can find all sorts of activities to do at home and work. Sign up using my link and we both get bonus points: ${urlValue}" class="invite-popup--share-icon">
                <img src="https://s3.amazonaws.com/unode1/assets/10615/4n8xK2LfQuqToq7ULt9Q_email.svg" />
              </a>
              <a href="https://api.whatsapp.com/send?text=Sending you an invite for Switch%2B - it’s a platform where you can find all sorts of activities to do at home and work. Sign up using my link and we both get bonus points: ${urlValue}" data-action="share/whatsapp/share" class="invite-popup--share-icon">
                <img src="https://s3.amazonaws.com/unode1/assets/10615/NluBw4LeRUGI5N110510_whatsapp.svg" />
              </a>
            </div>
            <p class="share-subtitle">or copy your personal link</p>
            <div class="copy-input">
              <input readonly id="copy_input_val" value="">
              <button class="copy-input--button-invite" data-clipboard-target="#copy_input_val">Copy</button>
            </div>
            <p class="invite-popup--bottom-title">*Only people within your organisation will be able to use this link.</p>
          </div>
        `
        modal.setContent(content)
        document.getElementById('copy_input_val').value = finalshareUrl;
        
        // let shareContentURL = localStorage.getItem('sareProgramUrl')
        // if (shareContentURL) {
        //   document.getElementById('copy_input_val').value = shareContentURL
        // }
        // if (true) {
        //   let linkRequest = {
        //     destination: shareValue,
        //     domain: { fullName: "go.switchplus.online" },
        //     slashtag: slug
        //   }
        //   let requestHeaders = {
        //     "Content-Type": "application/json",
        //     "apikey": "92758ef4b8e94747ba46f6e833c459c6"
        //   }
        //   $.ajax({
        //     url: "https://api.rebrandly.com/v1/links",
        //     type: "POST",
        //     data: JSON.stringify(linkRequest),
        //     headers: requestHeaders,
        //     dataType: "json",
        //     success: (link) => {
        //       console.log(`Long URL was ${link.destination}, short URL is ${link.shortUrl}`);
        //       localStorage.setItem('sareProgramUrl', link.shortUrl);
        //       shareContentURL = localStorage.getItem('sareProgramUrl')
        //       if (shareContentURL) {
        //         document.getElementById('copy_input_val').value = shareContentURL
        //       }
        //     },
        //     error: (msg) => {
        //       console.log(msg)
        //     }
        //   });
        // }
        
      }).catch(function (err) {
        console.log(err.message)
      });
    
      
    
    $('.invite-popup--close').on('click', function(){
      modal.close()
    })
    window.showInviteFriendProgramInit = function() {
      modal.open()
      $('.cbt-action-bar--popup').click()
    }
  }
  function inviteFriendInit() {
    console.log('inviteFriendInit')
    let button = $('.invite-friend--button')
    
    let modal = new tingle.modal({
      footer: false,
      stickyFooter: false,
      closeMethods: ['overlay', 'button', 'escape'],
      closeLabel: "Close",
      cssClass: ['custom-tingle', 'invite-tingle'],
      onOpen: function() {
        new ClipboardJS('.copy-input--button');
        
        $('.invite-popup--close').on('click', function(){
          //console.log('invite-popup--close')
          modal.close()
        })
      },
      onClose: function() {
        //console.log('modal closed');
      },
      beforeClose: function() {
        return true; // close the modal
        return false; // nothing happens
      }
    });
    
    let URL = `/api/ownerships`;
    let ownershipsRequest = request(URL);
    
    ownershipsRequest.then(function(data){
      let ownerships = JSON.parse(data)
      let slug = 'switchplus-' + document.getElementById('body').dataset.userEmail.split('@')[0].substr(0,10).replace('+', '').replace('.', '-')
      let shareUrl = `https://switchplus.online/pages/you_decide?&apply_product=${ownerships[0].product_id}&apply_coupon=REFERRAL&utm_source=switchplus&utm_medium=website&utm_campaign=invitecolleague&referredby=${slug}`
      //console.log(shareUrl)
      
      let linkRequest = {
        destination: shareUrl,
        domain: { fullName: "go.switchplus.online" },
        slashtag: slug
      }
      let urlValue = `https://go.switchplus.online/${slug}`;
      
      let requestHeaders = {
        "Content-Type": "application/json",
        "apikey": "92758ef4b8e94747ba46f6e833c459c6"
      }
      
      // $.ajax({
      //   url: "https://api.rebrandly.com/v1/links",
      //   type: "POST",
      //   data: JSON.stringify(linkRequest),
      //   headers: requestHeaders,
      //   dataType: "json",
      //   success: (link) => {
      //     console.log(`Long URL was ${link.destination}, short URL is ${link.shortUrl}`);
      //     //localStorage.setItem('sareUrl', urlValue);
      //   },
      //   error: (msg) => {
      //     console.log(msg)
      //   }
      // });

      modal.setContent(`
        <div class="invite-popup">
          <img class="invite-popup--close" src="https://s3.amazonaws.com/unode1/assets/10615/xUTfs0xoTKm63nOteZsi_x-icon-new.svg">
          <img class="invite-popup--icon" src="https://s3.amazonaws.com/unode1/assets/10615/KsADnsCmSeKuFDug0Sbh_Group%205.svg">
          <h2 class="invite-popup--title">Invite your team</h2>
          <p class="invite-popup--subtitle">There’s something for everyone. If you know someone on your team who is looking to get more active or find activities for their kids - share the love!</p>
          <div class="invite-popup--share">
            <a href="mailto:?subject=Join me on Switch%2B&body=Sending you an invite for Switch+ - it’s a platform where you can find all sorts of activities to do at home and work. Sign up using my link and we both get bonus points: ${urlValue}" class="invite-popup--share-icon">
              <img src="https://s3.amazonaws.com/unode1/assets/10615/4n8xK2LfQuqToq7ULt9Q_email.svg" />
            </a>
            <a href="https://api.whatsapp.com/send?text=Sending you an invite for Switch%2B - it’s a platform where you can find all sorts of activities to do at home and work. Sign up using my link and we both get bonus points: ${urlValue}" data-action="share/whatsapp/share" class="invite-popup--share-icon">
              <img src="https://s3.amazonaws.com/unode1/assets/10615/NluBw4LeRUGI5N110510_whatsapp.svg" />
            </a>
          </div>
          <p class="share-subtitle">or copy your personal link</p>
          <div class="copy-input">
            <input readonly id="copy_input_val" value="${urlValue}">
            <button class="copy-input--button" data-clipboard-target="#copy_input_val">Copy</button>
          </div>
          <p class="invite-popup--bottom-title">*Only people within your organisation will be able to use this link.</p>
        </div>
      `)
      
      
      
    }).catch(function (err) {
      console.log(err.message)
    });
    
    $('.invite-popup--close').on('click', function(){
      modal.close()
    })
    button.on('click', function(){
      modal.open()
    })
    
    window.showInviteFriendPopup = function() {
      console.log('showInviteFriendPopup')
      modal.open()
      $('.cbt-action-bar--popup').click()
    }
    
  }
  
  let detectProgramPage = () => {
    if (document.location.href.includes('/programs/')) {
      let myPlayer = document.querySelector('.plyr__video-wrapper video');
      if (myPlayer) {
        if (!myPlayer.classList.value.includes('touched')) {
          
          // dissable autoplay
          myPlayer.pause();
           
          let userGuest = $('body').attr('data-guest') == 'true'
          let userName =$('body').attr('data-user-name')
          let userEmail = $('body').attr('data-user-email')
          let programTitle = $('body').attr('data-program-title')
          let programId = $('body').attr('data-program-id')
          let chapterName = null
          let currentTime = parseFloat(myPlayer.currentTime / 60).toFixed(2).replace('.',':')
          
          if (new URL(location.href).searchParams.get('cid')) {
            chapterName = document.querySelector('.chapter-item-active.chapter-item .chapter-item--title.stable').innerText.trim()
          }
          
          var percentageCompleted = 0;
          var totalLength;
          var videoStarted, videoTwentyFive, videoFifty, videoSeventyFive, videoComplete = false;
          myPlayer.ontimeupdate = function() {
            let newCapterName = document.querySelector('.chapter-item-active.chapter-item .chapter-item--title.stable')
            if (newCapterName) {
              newCapterName = document.querySelector('.chapter-item-active.chapter-item .chapter-item--title.stable').innerText.trim()
            }
            //console.log(myPlayer)
            if (chapterName !== newCapterName) {
              console.log(newCapterName)
              chapterName = newCapterName
              console.log('update vars to 0');
              percentageCompleted = 0;
              totalLength = myPlayer.duration / 60;
              videoStarted = false
              videoTwentyFive = false
              videoFifty = false
              videoSeventyFive = false
              videoComplete = false;
              console.log('videoStarted '+videoStarted)
              
            }
            totalLength = myPlayer.duration / 60;   
            percentageCompleted = ((myPlayer.currentTime / 60) / totalLength) * 100;
            let webhookLink = 'https://hooks.zapier.com/hooks/catch/7151953/osv2qh5';
            let webhookStartedLink = 'https://hooks.zapier.com/hooks/catch/7151953/oznozco/'
            let webhookPoints = 'https://hooks.zapier.com/hooks/catch/7151953/okie0ts/'
            
            let liveEvent = false;
            if (document.querySelector('.live-event')) {
              webhookLink = 'https://hooks.zapier.com/hooks/catch/7151953/o8zncah'
              liveEvent = true;
            }
            
            if (liveEvent) {
              console.log('liveEvent')
              if ((!videoStarted) && (percentageCompleted > 0)) {
                console.log('LiveEvent_STARTED');
                videoStarted = true;
                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                   'event': 'playStart'
                });
                if (programTitle) {
                  let webhookData = {
                    "videoTitle" : programTitle,
                    "videoId" : programId,
                    "$email": userEmail,
                    "videoLength": totalLength,
                    "videoCompletion": 0
                  }
                  let webhookPointsData = {
                    "$email": userEmail,
                    "name": userName,
                    "videoTitle" : programTitle,
                    "Video progress": 0,
                    "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                  }
                  $.ajax({
                    type : 'POST',
                    url : webhookPoints,  
                    data: JSON.stringify(webhookPointsData),
                    success:function (data) {
                      console.log('webhook success data');
                      console.log(data);
                      console.log(webhookPointsData);
                    },
                    error: function(xhr, status, error) {
                    }
                  })
                  $.ajax({
                    type : 'POST',
                    url : webhookLink,  
                    data: JSON.stringify(webhookData),
                    success:function (data) {
                      console.log('webhook success data');
                      console.log(webhookData)
                      console.log(data);
                    },
                    error: function(xhr, status, error) {
                    }
                  })
                }
              }
              if ((!videoComplete) && (percentageCompleted > 99)) {
                  videoComplete = true;
                  if (!userGuest) {
                    console.log('VIDEO_100');
                    if (programTitle) {
                      let webhookData = {
                        "videoTitle" : programTitle,
                        "videoId" : programId,
                        "$email": userEmail,
                        "videoLength": totalLength,
                        "videoCompletion": 100
                      }
                      let webhookPointsData = {
                        "$email": userEmail,
                        "name": userName,
                        "videoTitle" : programTitle,
                        "Video progress": 100,
                        "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                      }
                      $.ajax({
                        type : 'POST',
                        url : webhookPoints,  
                        data: JSON.stringify(webhookPointsData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookPointsData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                      $.ajax({
                        type : 'POST',
                        url : webhookLink,  
                        data: JSON.stringify(webhookData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                    }
                  }
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playComplete'
                  });
              }
            } else {
              if ((!videoStarted) && (percentageCompleted > 0)) {
                  console.log('VIDEO_STARTED');
                  
                  let webhookPointsData = {
                    "$email": userEmail,
                    "name": userName,
                    "videoTitle" : programTitle,
                    "Video progress": 0,
                    "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                  }
                  
                  
                  videoStarted = true;
                  if (programTitle) {
                    
                    let webhookData = {
                      "videoTitle" : programTitle,
                      "videoId" : programId,
                      "$email": userEmail,
                      "videoLength": totalLength,
                      "$email": userEmail,
                      "videoCompletion": 0
                    }
                    if (chapterName) {
                      webhookData['videoTitle'] += ` | ${chapterName}`
                      webhookPointsData['videoTitle'] += ` | ${chapterName}`
                    }
                    
                    $.ajax({
                      type : 'POST',
                      url : webhookPoints,  
                      data: JSON.stringify(webhookPointsData),
                      success:function (data) {
                        console.log('webhook success data');
                        console.log(data);
                        console.log(webhookPointsData);
                      },
                      error: function(xhr, status, error) {
                      }
                    })
                    
                    $.ajax({
                      type : 'POST',
                      url : webhookStartedLink,  
                      data: JSON.stringify(webhookData),
                      success:function (data) {
                        console.log('webhook success data');
                        console.log(data);
                        console.log(webhookData);
                      },
                      error: function(xhr, status, error) {
                      }
                    })
                  }
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playStart'
                  });
              }
              // is 25
              if ((!videoTwentyFive) && (percentageCompleted > 25)) {
                  videoTwentyFive = true;
                  if (!userGuest) {
                    currentTime = parseFloat(myPlayer.currentTime / 60).toFixed(2).replace('.',':')
                    console.log('VIDEO_25');
                    // console.log(currentTime)
                    if (programTitle) {
                      let webhookData = {
                        "videoTitle" : programTitle,
                        "videoId" : programId,
                        "$email": userEmail,
                        "videoLength": totalLength,
                        "currentTime": currentTime,
                        "videoCompletion": 25
                      }
                      let webhookPointsData = {
                        "$email": userEmail,
                        "name": userName,
                        "videoTitle" : programTitle,
                        "Video progress": 25,
                        "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                      }
                      if (chapterName) {
                        webhookData['videoTitle'] += ` | ${chapterName}`
                        webhookPointsData['videoTitle'] += ` | ${chapterName}`
                      }
                      $.ajax({
                        type : 'POST',
                        url : webhookPoints,  
                        data: JSON.stringify(webhookPointsData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookPointsData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                      $.ajax({
                        type : 'POST',
                        url : webhookLink,  
                        data: JSON.stringify(webhookData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                    }
                      
                    mixpanel.track("videoProgress", {
                      "videoTitle": programTitle,
                      "videoId": programId,
                      "name": userName,
                      "$email": userEmail,
                      "videoLength": totalLength,
                      "videoCompletion": 25
                    });
                  }
                  
  
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playTwentyFive'
                  });
              }
              // is 50
              if ((!videoFifty) && (percentageCompleted > 50)) {
                  
                  videoFifty = true;
                  if (!userGuest) {
                    console.log('VIDEO_50');
                    currentTime = parseFloat(myPlayer.currentTime / 60).toFixed(2).replace('.',':')
                    if (programTitle) {
                      let webhookData = {
                        "videoTitle" : programTitle,
                        "videoId" : programId,
                        "$email": userEmail,
                        "videoLength": totalLength,
                        "currentTime": currentTime,
                        "videoCompletion": 50
                      }
                      let webhookPointsData = {
                        "$email": userEmail,
                        "name": userName,
                        "videoTitle" : programTitle,
                        "Video progress": 50,
                        "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                      }
                      if (chapterName) {
                        webhookData['videoTitle'] += ` | ${chapterName}`
                        webhookPointsData['videoTitle'] += ` | ${chapterName}`
                      }
                      $.ajax({
                        type : 'POST',
                        url : webhookPoints,  
                        data: JSON.stringify(webhookPointsData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookPointsData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                      $.ajax({
                        type : 'POST',
                        url : webhookLink,  
                        data: JSON.stringify(webhookData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                    }
                      
                    mixpanel.track("videoProgress", {
                      "videoTitle": programTitle,
                      "videoId": programId,
                      "name": userName,
                      "$email": userEmail,
                      "videoLength": totalLength,
                      "videoCompletion": 50
                    });
                  }
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playFifty'
                  });
              }
              // is 75
              if ((!videoSeventyFive) && (percentageCompleted > 75)) {
                  
                  videoSeventyFive = true;
                  if (!userGuest) {
                    console.log('VIDEO_75');
                    if (programTitle) {
                      let webhookData = {
                        "videoTitle" : programTitle,
                        "videoId" : programId,
                        "$email": userEmail,
                        "videoLength": totalLength,
                        "currentTime": currentTime,
                        "videoCompletion": 75
                      }
                      let webhookPointsData = {
                        "$email": userEmail,
                        "name": userName,
                        "videoTitle" : programTitle,
                        "Video progress": 75,
                        "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                      }
                      if (chapterName) {
                        webhookData['videoTitle'] += ` | ${chapterName}`
                        webhookPointsData['videoTitle'] += ` | ${chapterName}`
                      }
                      $.ajax({
                        type : 'POST',
                        url : webhookPoints,  
                        data: JSON.stringify(webhookPointsData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookPointsData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                      $.ajax({
                        type : 'POST',
                        url : webhookLink,  
                        data: JSON.stringify(webhookData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                    }
                      
                    mixpanel.track("videoProgress", {
                      "videoTitle": programTitle,
                      "videoId": programId,
                      "name": userName,
                      "$email": userEmail,
                      "videoLength": totalLength,
                      "videoCompletion": 75
                    });
                  }
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playSeventyFive'
                  });
              }
              // is 100
              if ((!videoComplete) && (percentageCompleted > 99)) {
                  
                  videoComplete = true;
                  if (!userGuest) {
                    console.log('VIDEO_100');
                    if (programTitle) {
                      let webhookData = {
                        "videoTitle" : programTitle,
                        "videoId" : programId,
                        "$email": userEmail,
                        "videoLength": totalLength,
                        "videoCompletion": 100
                      }
                      let webhookPointsData = {
                        "$email": userEmail,
                        "name": userName,
                        "videoTitle" : programTitle,
                        "Video progress": 100,
                        "Date": new Date().toLocaleString("en-GB", {timeZone: "Asia/Dubai", year: 'numeric', month: 'numeric', day: 'numeric'})
                      }
                      if (chapterName) {
                        webhookData['videoTitle'] += ` | ${chapterName}`
                        webhookPointsData['videoTitle'] += ` | ${chapterName}`
                      }
                      $.ajax({
                        type : 'POST',
                        url : webhookPoints,  
                        data: JSON.stringify(webhookPointsData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                          console.log(webhookPointsData);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                      $.ajax({
                        type : 'POST',
                        url : webhookLink,  
                        data: JSON.stringify(webhookData),
                        success:function (data) {
                          console.log('webhook success data');
                          console.log(data);
                        },
                        error: function(xhr, status, error) {
                        }
                      })
                    }
                      
                    mixpanel.track("videoProgress", {
                      "videoTitle": programTitle,
                      "videoId": programId,
                      "name": userName,
                      "$email": userEmail,
                      "videoLength": totalLength,
                      "videoCompletion": 100
                    });
                  }
                  window.dataLayer = window.dataLayer || [];
                  window.dataLayer.push({
                      'event': 'playComplete'
                  });
              }
            }
          };
          myPlayer.classList.add('touched')
        }
      }
      
      let shareButton = document.querySelector('.cbt--share-button.s-button');
      if (shareButton) {
        if (!shareButton.classList.value.includes('tocuhed')) {
          $(shareButton).on('click', function(e){
            e.preventDefault()
            window.showInviteFriendProgramInit()
            return false;
          })
          shareButton.classList.add('tocuhed')
        }
      }
      
      
    }
    setTimeout(() => detectProgramPage(), 500)
  }
  
  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }
  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 setCouponCodeToCookie = () => {
    let url = new URL(window.location.href);
    let couponCode = url.searchParams.get('apply_coupon');
    if (couponCode) {
      localStorage.setItem('couponCode', couponCode);
    }
  }
  
  let detectCompleteOrderPage = () => {
    if (document.location.href.includes('/complete_order')) {
      let couponCode = localStorage.getItem('couponCode')
      if (couponCode) {
        if (document.querySelector('.right-side')) {
          if (!document.querySelector('.right-side').classList.value.includes('coupon-applied')) {
            let couponInput = document.querySelector('.discount-form .input-group input')
            if (couponInput) {
              if (document.querySelector('.__PrivateStripeElement')) {
                clickApplyCoupon(couponCode)
              }
              document.querySelector('.right-side').classList.add('coupon-applied')
            }
          }
        }
      }
    }
    setTimeout(() => detectCompleteOrderPage(), 300)
  }
  
  let detectCustomerInfoPage = () => {
    if (document.location.href.includes('/customer_info')) {
      let layout = document.querySelector('.layout')
      if (layout) {
        if (!layout.classList.value.includes('touched')) {
          if (document.location.href.includes('28710')) {
            let url = 'https://switchplus.online/pages/you_decide?&apply_product=31798&apply_coupon=SCBPROGLO1?utm_source=direct&utm_medium=website&utm_campaign=redirect'
            document.location.href = url
          }
          if (document.location.href.includes('28711')) {
            let url = 'https://switchplus.online/pages/you_decide?&apply_product=31797&apply_coupon=SWCOFAM1?utm_source=direct&utm_medium=website&utm_campaign=redirect'
            document.location.href = url
          }
          layout.classList.add('touched')
        }
      }
    }
    setTimeout(() => detectCustomerInfoPage(), 300)
  }
  
  let detectSuccessOrderPage = () => {
    if (document.location.href.includes('/orders/success')) {
      // console.log('detectSuccessOrderPage')
      let form = document.querySelector('.completed')
      if (form) {
        if (!form.classList.value.includes('touched')) {
          form.classList.add('touched')
          window.open('/pages/my_library', '_self')
        }
      }
      
    }
    setTimeout(() => detectSuccessOrderPage(), 300)
  }
  
  let detectBundleLogo = () => {
    
    let wrapper = document.querySelector('.bundle-logo')
    let bundle = localStorage.getItem('bundle')
    if (wrapper) {
      if (bundle) {
        let BundleObj = JSON.parse(bundle)
        let bundleLogo = document.querySelector('.bundle-logo img')
        if (!bundleLogo.classList.value.includes('touched')) {
          //console.log(BundleObj)
          if (BundleObj.image_url !== 'https://dtsvkkjw40x57.cloudfront.net/images/offer/31797/big_data_2Fimages_2FTtP9s6oYS32AiHBoGPGx_20x21-live-session-holding-page-new-02.png') {
            bundleLogo.src = BundleObj.image_url
            bundleLogo.classList.add('touched')
          } else {
            bundleLogo.classList.add('hidden')
          }
          
        }
      }
    }
    setTimeout(() => detectBundleLogo(), 300)
  }

  let renderCategoryRowNew = (category, ownedIds, order, content, authors, customClass) => {
    //console.log('render category')
    if (content.length) {
      let cards = '';
      let limit = 12;
      content.forEach(card => {
        if (ownedIds.includes(card.id)) {
          let authorClass = '';
          let authorName = '';
          let authorImage = ''
          if (card.author_id) {
            authorClass = `author-${card.author_id}`
            authors.forEach(author => {
              //console.log(author)
              if (author.id === card.author_id) {
                authorName = `${author.title}`
                authorImage = author.avatar_url
                return true
              }
            })
            
          }
          if (limit > 0) {
            if (card.content_type == 2) {
              let date = new Date(card.short_description.split('|')[0])
              let lvlStyle = document.querySelector('.lvl-style');
              let cardSubtitle = ''
              liveDate = ''
              cardSubtitle = `
                <span class="library-card--subtitle">
                  ${date.toLocaleString('en-GB', { weekday: 'long' })},
                  ${date.toLocaleString('en-GB', { month: 'long' })}
                  ${date.toLocaleString('en-GB', { day: '2-digit' })}
                  ,
                  ${date.toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true })}
                </span>
              `
              let bottomTitle = ''
              if (authorImage) {
                bottomTitle = `
                  <span class="library-card--bottomtitle">
                    <img src="${authorImage}">
                    <span class="live-label">Live</span>
                  </span>
                `
              }
              cards += `
                <div>
                  <div class="library-card ${authorClass}" data-short-description="${card.short_description}" data-author="${authorName}">
                    <a class="library-card--image" href="/programs/${card.permalink}">
                      <img src="${card.preview}">
                    </a>
                    <span class="library-card--footer">
                      ${bottomTitle}
                      <a class="library-card--title" href="/programs/${card.permalink}">${card.title.split('|')[0]}</a>
                      ${cardSubtitle}
                    </span>
                  </div>
                </div>
              `
            } else {
              let chaptersIcon = ` Videos`;
              let durationRow = Math.floor(card.duration / 60) + ' Minutes'
              let subtiteBottom = ''
              if (card.content_type == 0) {
                durationRow =  card.children.length + chaptersIcon
                subtiteBottom = `
                  <span class="library-card--bottomtitle">
                    <img src="${authorImage}">
                    <span class="series-label">SERIES</span>
                  </span>
                `
              }
              
              cards += `
                <div>
                  <div class="library-card ${authorClass}" data-short-description="${card.short_description}">
                    <a class="library-card--image" href="/programs/${card.permalink}">
                      <img src="${card.preview}">
                    </a>
                    <span class="library-card--footer">
                      ${subtiteBottom}
                      <a class="library-card--title" href="/programs/${card.permalink}">${card.title}</a>
                      <span class="library-card--subtitle">
                       
                        ${durationRow}
                      </span>
                    </span>
                  </div>
                </div>
              `
            }
            limit -= 1
          }
        }
      })
      if (cards) {
        let lvlStyle = document.querySelector('.lvl-style');
        let seeAll = 'See All'
        //console.log(lvlStyle)
        if (lvlStyle) {
          seeAll = 'view more'
        }
        let categoryClass=""
        let sliderClass="js-slick-slider"
        //console.log(category.id)
        if (FEATURED_CATEGORIES.includes(category.id)) {
          categoryClass="category-row--featured"
          sliderClass="js-slick-slider-big"
        }
        
        let categoryMarkup = `
          <section class="${customClass} category-row ${categoryClass} category-${category.id}" style="order: ${order};">
            <h2 class="category-row--title">${category.title} <a href="/pages/category?category_slug=${category.permalink}&category_id=${category.id}">${seeAll}</a></h2>
            <div class="category-content ${sliderClass}">
              ${cards}
            </div>
          </section>
        `;
        $('#my_library_container').append(categoryMarkup)
        if (!$('.category-row.category-empty-state').hasClass('hidden')) {
          $('.category-row.category-empty-state').addClass('hidden')
        }
        
        
      }
    }
  }
  
  function clearFilters() {
    $('.custom-select--content').removeClass('selected')
    $('.my_library--filters-search input').val('')
    $('#search_container .library-card').removeClass('search-hide')
    $('.author-select .custom-select--header').text('Offered by:')
    $('.category-select .custom-select--header').text('Category')
  }
  
  function initSelects() {
    $('.author-select--header').on('click', function(){
      $('.custom-select--content').hide()
      $(this).parents('.custom-select').find('.custom-select--content').show()
    })
    $('.custom-select--content option').on('click', function(){
      clearFilters()
      let value = this.value
      if (value === '') {
        $('#my_library_container').show()
        $('#search_container').hide()
      } else {
        $('#my_library_container').hide()
        $('#search_container').show()
        $('#search_container .library-card').each((index, card) => {
          //console.log($(card)[0].classList.value)
          //console.log(value)
          if (!$(card)[0].classList.value.includes(value)) {
            $(card).addClass('search-hide')
          }
        })
      }
      
      // $('.category-select').on('change', function(){
      //   $('#my_library_container .category-row').removeClass('search-hide')
      //   $(".author-select").val($(".author-select option:first").val());
      //   $('.my_library--filters-search input').val('')
      //   let value = this.value
      //   if (value === '') {
      //     $('#my_library_container').show()
      //     $('#search_container').hide()
      //   } else {
      //     $('#my_library_container').show()
      //     $('#search_container').hide()
      //     $('#my_library_container .category-row').each((index, card) => {
      //       console.log($(card)[0].classList.value)
      //       console.log(value)
      //       if (!$(card)[0].classList.value.includes(value)) {
      //         $(card).addClass('search-hide')
      //       }
      //     })
      //   }
      // })
    })
  }
  
  let detectMyLibraryContainer = () => {
    let container = document.getElementById('my_library_container')
    let searchContainer = document.getElementById('search_container')
    let filtersContainer = document.getElementById('my_library-filters') 
    let bundle = localStorage.getItem('bundle')
    
    // if (filtersContainer) {
    //   let URL = `${getStoreFromURL(document.location.href)}/api/authors/`;
    //   let authorsRequest = request(URL);
    //   authorsRequest.then(function(data){
    //     let authors = JSON.parse(data)
    //     let options = ''
    //     authors.forEach(category => {
    //       options += `<option value="${category.id}">${category.title}</option>`
    //     })
    //     let authorsSelect = `
    //       <select class="author-select">
    //         <option value="" selected>Studio / Coach</option>
    //         ${options}
    //       </select>
    //     `
    //     $(filtersContainer).append(authorsSelect)
    //     $('.author-select').on('change', function(){
    //       $(".category-select").val($(".category-select option:first").val());
    //       $('.my_library--filters-search input').val('')
    //       $('#search_container .library-card').removeClass('search-hide')
    //       let value = this.value
    //       if (value === '') {
    //         $('#my_library_container').show()
    //         $('#search_container').hide()
    //       } else {
    //         $('#my_library_container').hide()
    //         $('#search_container').show()
    //         $('#search_container .library-card').each((index, card) => {
    //           //console.log($(card)[0].classList.value)
    //           //console.log(value)
    //           if (!$(card)[0].classList.value.includes(value)) {
    //             $(card).addClass('search-hide')
    //           }
    //         })
    //       }
    //     })
    //   }).catch(function (err) {
    //     console.log(err.message)
    //   });
    // }
    
    function fetchLibraryData() {
      
      function getUserContent() {
        console.log('getUserContent')
        let userContent = []
        return axios.all([
          axios.get('/api/contents?type=my_library&page=1'),
          axios.get('/api/contents?type=my_library&page=2'),
          axios.get('/api/contents?type=my_library&page=3'),
          axios.get('/api/contents?type=my_library&page=4'),
          axios.get('/api/contents?type=my_library&page=5')
        ]).then(responseArr => {
          let allProcessedResponses = [];
          responseArr.forEach(response => {
            allProcessedResponses.push(response.data)
          })
          userContent = [].concat.apply([], allProcessedResponses);
          console.log(userContent)
          return userContent;
        })
      }
      
      let userContent = JSON.parse(localStorage.getItem('user_content'));
      
      if (userContent) {
        myLibraryRender(userContent);
        let diff = Math.abs(new Date(+localStorage.getItem('user_content_date')) - Date.now());
        let minutes = Math.floor((diff/1000)/60);
        if (minutes >= 0) {
          getUserContent().then(data => {
            console.log('getUserContent DATA')
            console.log(data)
            localStorage.setItem('user_content', JSON.stringify(data))
            localStorage.setItem('user_content_date', Date.now())
          })
        }
      } else {
        getUserContent().then(data => {
          console.log('getUserContent DATA')
          console.log(data)
          myLibraryRender(data);
          localStorage.setItem('user_content', JSON.stringify(data))
          localStorage.setItem('user_content_date', Date.now())
        })
        
      }
      
    }
    
    function renderCategorySelect(markup) {
      let filtersContainer = document.getElementById('my_library-filters') 
      $(filtersContainer).append(markup)
      $('.category-select').on('change', function(){
        $('#my_library_container .category-row').removeClass('search-hide')
        $(".author-select").val($(".author-select option:first").val());
        $('.my_library--filters-search input').val('')
        let value = this.value
        if (value === '') {
          $('#my_library_container').show()
          $('#search_container').hide()
        } else {
          $('#my_library_container').show()
          $('#search_container').hide()
          $('#my_library_container .category-row').each((index, card) => {
            if (!$(card)[0].classList.value.includes(value)) {
              $(card).addClass('search-hide')
            }
          })
        }
        if ($('.js-slick-slider.slick-initialized').length) {
          $('.js-slick-slider').slick('unslick');
        }
        if ($('.js-slick-slider-big.slick-initialized').length) {
          $('.js-slick-slider-big').slick('unslick');
        }
        $('.js-slick-slider').slick({
          infinite: false,
          speed: 300,
          slidesToShow: 4,
          slidesToScroll: 1,
          responsive: [
            {
              breakpoint: 1070,
              settings: {
                slidesToShow: 3,
                slidesToScroll: 1,
              }
            },
            {
              breakpoint: 810,
              settings: {
                slidesToShow: 2,
                slidesToScroll: 2
              }
            },
            {
              breakpoint: 480,
              settings: {
                slidesToShow: 1,
                slidesToScroll: 1
              }
            }
          ]
        })
        
        $('.js-slick-slider-big').slick({
          infinite: false,
          speed: 300,
          slidesToShow: 2,
          slidesToScroll: 1,
          responsive: [
            {
              breakpoint: 800,
              settings: {
                slidesToShow: 1,
                slidesToScroll: 1
              }
            }
          ]
        })
      })
    }
    
    function libraryRenderingProcess(store, ownedIds, globalAuthors) {
      
      console.log(store)
      
      let categories = store.categories;
      let categoryIds = [];
      let categoryImages = [];
      let options = '';
      let userStyle = localStorage.getItem('user_style');
      let customClass = 'hidden-category'
      
      categories.forEach((category, index) => {
        
        let mode = 'choose'
        if (userStyle) {
          if (userStyle === 'relax-styles') {
            mode = 'relax'
          }
          if (userStyle === 'active-styles') {
            mode = 'active'
          }
        }
        
        
        
        
        
        
        let order = category.position
        let content = [];
          
        categoryImages.push(category.image)
        if (category.content_ids) {
          category.content_ids.forEach(cateogryProgramId => {
            store.contents.forEach(storeContent => {
              if (storeContent.id === cateogryProgramId) {
                content.push(storeContent)
              }
            })
          })
        }
        
        if (CHOOSE_CATEGORIES.includes(category.id)) {
          customClass = ''
          //console.log(category)
          if (category.id !== 37076) {
            options += `<option value="${category.id}">${category.title}</option>`
          }
          
          renderCategoryRowNew(category, ownedIds, order, content, globalAuthors, customClass)
        }
        
        // if (mode === 'choose') {
        //   if (CHOOSE_CATEGORIES.includes(category.id)) {
        //     customClass = ''
        //     console.log(category)
        //     options += `<option value="${category.id}">${category.title}</option>`
        //     renderCategoryRowNew(category, ownedIds, order, content, globalAuthors, customClass)
        //   }
        // }
        
        // if (mode === 'relax') {
        //   if (RELAX_CATEGORIES.includes(category.id)) {
        //     customClass = ''
        //     options += `<option value="${category.id}">${category.title}</option>`
        //     renderCategoryRowNew(category, ownedIds, order, content, globalAuthors, customClass)
        //   }
        // }
        
        // if (mode === 'active') {
        //   if (ACTIVE_CATEGORIES.includes(category.id)) {
        //     customClass = ''
        //     options += `<option value="${category.id}">${category.title}</option>`
        //     renderCategoryRowNew(category, ownedIds, order, content, globalAuthors, customClass)
        //   }
        // }
        
        
        
      });
      
      // sliders was there
      
      
      
      
      $('.js-slick-slider').slick({
        infinite: false,
        speed: 300,
        slidesToShow: 4,
        slidesToScroll: 1,
        responsive: [
          {
            breakpoint: 1070,
            settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
            }
          },
          {
            breakpoint: 810,
            settings: {
              slidesToShow: 2,
              slidesToScroll: 2
            }
          },
          {
            breakpoint: 480,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1
            }
          }
        ]
      })
      
      $('.js-slick-slider-big').slick({
        infinite: false,
        speed: 300,
        slidesToShow: 2,
        slidesToScroll: 1,
        responsive: [
          {
            breakpoint: 800,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1
            }
          }
        ]
      })
      
      var rowBg = categoryImages[Math.floor(Math.random() * categoryImages.length)];
      
      let bundle = localStorage.getItem('bundle')
      if (bundle) {
        let BundleObj = JSON.parse(bundle)
        console.log('HELO!' + BundleObj.id)
        if (BundleObj.id == 38972) {
          // rowBg = 'https://s3.amazonaws.com/unode1/assets/10615/eQEZnv4mQ2GVsI0A6nsu_Header-JE3.jpg'
          rowBg = 'https://s3.amazonaws.com/unode1/assets/10615/Hf7Qp7MThugSOKsOBHyQ_20x21-live-session-holding-page-new-02.png'
          console.log('rowBg: ' + rowBg)
        }
      }
      
      rowBg = 'https://s3.amazonaws.com/unode1/assets/10615/z3kGIgbTqNKImzTakWQD_20x21%20Bundle%20Image%201Feb21.png'
      
      $('.library-row-bg').css('background-image', 'url(' + rowBg + ')');
      
      let categorySelect = `
        <select class="category-select">
          <option value="" selected>Choose a category</option>
          ${options}
        </select>
      `
      renderCategorySelect(categorySelect)
      
    }
    
      window.myLibraryRender = function (processedResponses) {
        
        if ($('.js-slick-slider.slick-initialized').length) {
          $('.js-slick-slider').slick('unslick');
        }
        if ($('.js-slick-slider-big.slick-initialized').length) {
          $('.js-slick-slider-big').slick('unslick');
        }
        $(container).html('')
        $(searchContainer).html('')
        $(filtersContainer).html('')
        
        let library = processedResponses;
        console.log(library)
        let ownedIds = [];
        let librarySearchMarkup = '';
      
        // render Search container
        library.forEach(card => {
          ownedIds.push(card.id)
          let authorClass = '';
          if (card.author) {
            authorClass = `author-${card.author.id}`
          }
          librarySearchMarkup += `
            <div class="library-card ${authorClass}" data-short-description="${card.short_description}">
              <a class="library-card--image" href="${card.url}"><img src="${card.main_poster}"></a>
              <a class="library-card--title" href="${card.url}">${card.title}</a>
            </div>
          `
        })
        $(searchContainer).append(librarySearchMarkup)
  
        let storeURL = 'https://frontier-production.herokuapp.com/api/stores/full?store_key=qyM2b5vJJuPJRg=='
        let store = JSON.parse(localStorage.getItem('store'))
        
        let globalAuthorsUrl = '/api/authors'
        let globalAuthors = JSON.parse(localStorage.getItem('globalAuthors'))
        
        if (store && globalAuthors) {
          libraryRenderingProcess(store, ownedIds, globalAuthors)
          let diff = Math.abs(new Date(+localStorage.getItem('store_date')) - Date.now());
          let minutes = Math.floor((diff/1000)/60);
          if (minutes >= 0) {
            axios.get(storeURL).then(function(response){
              localStorage.setItem('store', JSON.stringify(response.data))
              localStorage.setItem('store_date', Date.now())
            })
          }
        } else {
          axios.get(storeURL).then(function(response){
            let store = response.data;
            localStorage.setItem('store', JSON.stringify(response.data))
            localStorage.setItem('store_date', Date.now())
            
            axios.get(globalAuthorsUrl).then(function(response){
              let globalAuthors = response.data
              libraryRenderingProcess(store, ownedIds, globalAuthors)
              localStorage.setItem('globalAuthors', JSON.stringify(globalAuthors))
            })
            
          })
        }
      }
  
      if (container) {
        let sharefriendMarkup = `
          <div class="invite-friend" >
            <div>
              <h2>Share that amazing feeling</h2>
              <p>Invite your colleagues and earn more points</p>
            </div>
            <div>
              <button class="invite-friend--button">Invite</button>
            </div>
          </div>
        `
        $(container).append(sharefriendMarkup)
        fetchLibraryData()
      }
  }
  
  let clickApplyCoupon = (couponCode) => {
    console.log('clickApplyCoupon: ' + couponCode)
    var $input = $('.discount-form .input-group input').val(couponCode);
    var e = document.createEvent('HTMLEvents');
    e.initEvent('input', true, true);
    $input[0].dispatchEvent(e);
    $('.discount-form .base').click()
    setTimeout(()=>{
      $('.discount-form .base').click()
    }, 500)
    
    // localStorage.setItem('couponCode', '');
  }
  
  let freeBundleApplay = () => {
    let image = $('img[alt="No credit card needed"]')
    if (image.length) {
      
      if (!image.hasClass('touched')) {
        console.log('freeBundleApplay ??')
        setTimeout(()=>{
          $('.finalize button').click()
          image.addClass('touched')
        }, 500)
      }
    }
    setTimeout(() => freeBundleApplay(), 500) 
  }
  
  $(function(){
    
    freeBundleApplay()
    setCouponCodeToCookie()
    detectCompleteOrderPage()
    detectMyLibraryContainer()
    detectBundleLogo()
    detectSuccessOrderPage()
    detectCustomerInfoPage()
    detectProgramPage()
    
    let activateRelaxStyles = () => {
      // $('#body').addClass('relax-styles');
      // $('#body').removeClass('active-styles');
      
      $('.lvl-banner--choose-side').addClass('hidden');
      $('.lvl-banner--choose-side-active').addClass('hidden');
      $('.lvl-banner--choose-side-relax').removeClass('hidden');
      
      // $('.js-switch-mood').removeClass('hidden');
      // $('.js-switch-mood').addClass('js-switch-mood--relax')
      // $('.js-switch-mood').removeClass('js-switch-mood--active') 
      
      // let userContent = JSON.parse(localStorage.getItem('user_content'));
      // window.myLibraryRender(userContent);
    }
    
    let activateActiveStyles = () => {
      // $('#body').addClass('active-styles');
      // $('#body').removeClass('relax-styles');
      
      $('.lvl-banner--choose-side').addClass('hidden') 
      $('.lvl-banner--choose-side-active').removeClass('hidden') 
      $('.lvl-banner--choose-side-relax').addClass('hidden') 
      
      // $('.js-switch-mood').removeClass('hidden') 
      // $('.js-switch-mood').addClass('js-switch-mood--active') 
      // $('.js-switch-mood').removeClass('js-switch-mood--relax')
      
      //let userContent = JSON.parse(localStorage.getItem('user_content'));
      //window.myLibraryRender(userContent);
    }
    
    let activateChooseSide = () => {
      $('#body').addClass('relax-styles')
      $('.lvl-banner--choose-side').removeClass('hidden')
      
      let userContent = JSON.parse(localStorage.getItem('user_content'));
      window.myLibraryRender(userContent);
    }
    
    $('.js-choose-relax').on('click', function(){
      //localStorage.setItem('user_style', 'relax-styles')
      activateRelaxStyles()
    })
    
    $('.js-choose-active').on('click', function(){
      //localStorage.setItem('user_style', 'active-styles')
      activateActiveStyles()
    })
    
    $('.js-switch-mood').on('click', function(){
      let userContent = localStorage.getItem('user_style');
      
      if (userContent === 'relax-styles') {
       localStorage.setItem('user_style', 'active-styles')
       activateActiveStyles()
      }
      if (userContent === 'active-styles') {
        localStorage.setItem('user_style', 'relax-styles')
        activateRelaxStyles()
      }
    })
    
    let userStyle = localStorage.getItem('user_style')
    if (userStyle) {
      $('#body').addClass(userStyle)
      if (userStyle === 'relax-styles') {
        activateRelaxStyles()
      }
      if (userStyle === 'active-styles') {
        activateActiveStyles()
      }
    } else {
      activateChooseSide()
    }

    if (document.location.href.includes('pages/my_library')) {
      inviteFriendInit()
    }
    
    if (document.querySelector('body').dataset.user !== "Liquid error: internal" && location.href.includes('/programs/')) {
      inviteFriendProgramInit()
    }
    
    
  })
  
})()