function initializeBaseTracking() {
  var wait = 0;
  var addedGA = false;
  var waitingOnGA = setInterval(function() {
    if (!addedGA) {
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    }
    addedGA = true;
    wait++;
    if (window.ga && ga.create) {
      ga('create', '<%= ApplicationConfig["GA_TRACKING_ID"] %>', 'auto');
      ga('send', 'pageview', location.pathname + location.search);
      if (document.location.search.indexOf('newly-registered-user=true') > -1) {
        ga('send', 'event', 'registration', 'New user registration', location.pathname, null);
      }
      clearInterval(waitingOnGA);
      logImpressions();
    }
    if (wait > 85) {
      clearInterval(waitingOnGA);
      fallbackActivityRecording();
    }
  }, 25);
  eventListening();
  trackCustomImpressions();
}

function fallbackActivityRecording() {
  var tokenMeta = document.querySelector("meta[name='csrf-token']")
  if (!tokenMeta) {
    return
  }
  var csrfToken = tokenMeta.getAttribute('content')
  var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  var screenW = window.screen.availWidth;
  var screenH = window.screen.availHeight;
  var dataBody = {
    path: location.pathname + location.search,
    user_language: navigator.language,
    referrer: document.referrer,
    user_agent: navigator.userAgent,
    viewport_size: h + 'x' + w,
    screen_resolution: screenH + 'x' + screenW,
    document_title: document.title,
    document_encoding: document.characterSet,
    document_path: location.pathname + location.search,
  };
  window.fetch('/fallback_activity_recorder', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'X-CSRF-Token': csrfToken,
    },
    body: JSON.stringify(dataBody),
    credentials: 'same-origin'
  });
}

function eventListening(){
  var registerNowButt = document.getElementById("cta-comment-register-now-link");
  if (registerNowButt) {
    registerNowButt.onclick = function(){
      ga('send', 'event', 'click', 'register-now-click', null, null);
    }
  }
}

function logImpressions() {
  var el = document.getElementById("featured-story-marker")
  if (el){
    var data = el.dataset.featuredArticle;
    ga('send', 'event', 'view', 'featured-feed-impression', data, null);
  }
}

function trackCustomImpressions() {
  setTimeout(function(){
    var stickyNav = document.getElementById('article-show-primary-sticky-nav');
    var sidebarHTMLVariant = document.getElementById('html-variant-article-show-sidebar');
    var ArticleElement = document.getElementById('article-body');
    var tokenMeta = document.querySelector("meta[name='csrf-token']")
    var randomNumber = Math.floor(Math.random() * 10); // 1 in 10; Only track 1 in 10 impressions
    var isBot = /bot|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex/i.test(navigator.userAgent) // is crawler
    if (sidebarHTMLVariant && ArticleElement && tokenMeta && !isBot) {
      var dataBody = {
        html_variant_id: sidebarHTMLVariant.dataset.variantId,
        article_id: ArticleElement.dataset.articleId,
      };
      var csrfToken = tokenMeta.getAttribute('content');
      if (randomNumber === 1) {
        window.fetch('/html_variant_trials', {
          method: 'POST',
          headers: {
            'X-CSRF-Token': csrfToken,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(dataBody),
          credentials: 'same-origin',
        });
      }
      var successLinks = stickyNav.querySelectorAll('a,button'); //track all links and button clicks within nav
      for(var i = 0; i < successLinks.length; i++)
      {
        successLinks[i].addEventListener('click', function() { trackHtmlVariantSuccess(dataBody, csrfToken) });
      }
    }
  }, 1500)
}

function trackHtmlVariantSuccess(dataBody, csrfToken) {
  window.fetch('/html_variant_successes', {
    method: 'POST',
    headers: {
      'X-CSRF-Token': csrfToken,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(dataBody),
    credentials: 'same-origin',
  })
}