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('set', 'anonymizeIp', true);
      ga('send', 'pageview', location.pathname + location.search);
      clearInterval(waitingOnGA);
    }
    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 trackCustomImpressions() {
  setTimeout(function(){
    var ArticleElement = document.getElementById('article-body');
    var tokenMeta = document.querySelector("meta[name='csrf-token']")
    var isBot = /bot|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex/i.test(navigator.userAgent) // is crawler
    var windowBigEnough =  window.innerWidth > 1250

    // Sidebar HTML variant tracking
    var stickyNav = document.getElementById('article-show-primary-sticky-nav');
    var sidebarHTMLVariant = document.getElementById('html-variant-article-show-sidebar');
    if (sidebarHTMLVariant && ArticleElement && tokenMeta && !isBot && windowBigEnough) {
      var dataBody = {
        html_variant_id: sidebarHTMLVariant.dataset.variantId,
        article_id: ArticleElement.dataset.articleId,
      };
      var csrfToken = tokenMeta.getAttribute('content');
      trackHTMLVariantTrial(dataBody, csrfToken)
      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) });
      }
    }

    // Below article HTML variant tracking
    var belowArticleHTMLVariant = document.getElementById('html-variant-article-show-below-article');
    if (belowArticleHTMLVariant && ArticleElement && tokenMeta && !isBot && windowBigEnough) {
      var dataBody = {
        html_variant_id: belowArticleHTMLVariant.dataset.variantId,
        article_id: ArticleElement.dataset.articleId,
      };
      var csrfToken = tokenMeta.getAttribute('content');
      trackHTMLVariantTrial(dataBody, csrfToken)
      var successLinks = belowArticleHTMLVariant.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) });
      }
    }

    // page view
    if (ArticleElement && tokenMeta && !isBot) {
      var randomNumber = Math.floor(Math.random() * 10); // 1 in 10; Only track 1 in 10 impressions
      if (!checkUserLoggedIn() && randomNumber != 1) {
        return;
      }
      var dataBody = {
        article_id: ArticleElement.dataset.articleId,
        referrer: document.referrer,
        user_agent: navigator.userAgent,
      };
      var csrfToken = tokenMeta.getAttribute('content');
      trackPageView(dataBody, csrfToken);
      var timeOnSiteCounter = 0;
      var timeOnSiteInterval = setInterval(function(){
        timeOnSiteCounter++
        var ArticleElement = document.getElementById('article-body');
        if (ArticleElement && checkUserLoggedIn()) {
          trackFifteenSecondsOnPage(ArticleElement.dataset.articleId, csrfToken);
        } else {
          clearInterval(timeOnSiteInterval);
        }
        if ( timeOnSiteCounter > 118 ) {
          clearInterval(timeOnSiteInterval);
        }
      }, 15000)
    }

    // display add
    var adBox = document.getElementById('sponsorship-arbitrary-display-widget')
    if (adBox
      && tokenMeta
      && !isBot
      && windowBigEnough
      && checkUserLoggedIn()) {
        var csrfToken = tokenMeta.getAttribute('content');
        trackAdImpression(csrfToken, adBox)
        adBox.removeEventListener('click', trackAdClick, false );
        adBox.addEventListener('click', function() { trackAdClick(csrfToken, adBox) });
      }
  }, 1800)
}

function trackHTMLVariantTrial(dataBody, csrfToken) {
  var randomNumber = Math.floor(Math.random() * 10); // 1 in 10; Only track 1 in 10 impressions
  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',
    });
  }
}

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',
  })
}

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

function trackFifteenSecondsOnPage(articleId, csrfToken) {
  window.fetch('/page_views/' + articleId, {
    method: 'PATCH',
    headers: {
      'X-CSRF-Token': csrfToken,
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin',
  })
}

function trackAdImpression(token, adBox) {
  var dataBody = {
    display_ad_event: {
      display_ad_id: adBox.dataset.id,
      context_type: "home",
      category: "impression",
    }
  }
  window.fetch('/display_ad_events', {
    method: 'POST',
    headers: {
      'X-CSRF-Token': token,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(dataBody),
    credentials: 'same-origin',
  })
}

function trackAdClick(token, adBox) {
  if (!adClicked) {
    var dataBody = {
      display_ad_event: {
        display_ad_id: adBox.dataset.id,
        context_type: "home",
        category: "click",
      }
    }
    window.fetch('/display_ad_events', {
      method: 'POST',
      headers: {
        'X-CSRF-Token': token,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(dataBody),
      credentials: 'same-origin',
    })
  }
  adClicked = true;
}
