if ($('#newsletterSignUp').length) {
  // wait for Heap cookie to exist
  function waitForHeap() {
    var startTimeInMs = Date.now();
    if (readCookie('_hp2_id.588835629') != null) {
      var decoded = decodeURIComponent(readCookie('_hp2_id.588835629'));
      document.querySelector('#heap_user_id').value =
        JSON.parse(decoded).userId;
    } else {
      // if cookie not found after 10 seconds, stop running
      setTimeout(function () {
        if (10000 && Date.now() - startTimeInMs > 10000) return;
        waitForHeap();
      }, 150);
    }
  }
  waitForHeap();

  jQuery('#newsletterSignUpForm').on('submit', (e) => {
    e.preventDefault();
    var email = jQuery('#newsletterEmail').val();
    var first = jQuery('#newsletterFirst').val();
    var last = jQuery('#newsletterLast').val();
    var url = window.location.href;
    var path = window.location.pathname
    var utm_campaign = jQuery('#utm_campaign').val();
    var utm_content = jQuery('#utm_content').val();
    var utm_term = jQuery('#utm_term').val();
    var utm_source = jQuery('#utm_source').val();
    var utm_medium = jQuery('#utm_medium').val();
    var heap_user_id = jQuery('#heap_user_id').val();

    window.dataLayer.push({
      event: 'hubspot-form-success',
      'hs-form-guid': '21432d3a-3e12-461d-ab1b-cd1cc3374a89',
    });

    // https://starburst.pantheonlocal.com/
    // https://www.starburst.io/
    // https://localhost:54739/

    jQuery.ajax({
      type: 'POST',
      url: 'https://www.starburst.io/wp-admin/admin-ajax.php',
      data: {
        action: 'newsletter_sign_up',
        email: email,
        first: first,
        last: last,
        url: url,
        path: path,
        utm_campaign: utm_campaign,
        utm_content: utm_content,
        utm_term: utm_term,
        utm_source: utm_source,
        utm_medium: utm_medium,
        heap_user_id: heap_user_id,
      },
      success: function (data) {
        jQuery('#newsletterSignUp').html(
          '<p style="color:#fff;">Thanks for signing up!</p>'
        );
      },
      error: function (xhr, ajaxOptions, thrownError) {
        console.log('error', thrownError);
      },
    });
  });
}
