if ($('.blog-subscribe-form').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('.blog-subscribe-form').on('submit', (e) => {
    e.preventDefault();
    var formid = 'ea8eff40-4a4d-4003-a2ea-cf980f94c249';
    var email = jQuery('.blog-subscribe-input').val();
    var opt_in = jQuery('.blog-subscribe-opt_in').val();
    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': formid,
    });

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

    jQuery.ajax({
      type: 'POST',
      url: 'https://www.starburst.io/wp-admin/admin-ajax.php',
      data: {
        action: 'blog_subscribe',
        formid: formid,
        email: email,
        opt_in: opt_in,
        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('.blog-subscribe-form').html(
          '<p>Thank you for subscribing to the Starburst blog!</p>'
        );
      },
      error: function (xhr, ajaxOptions, thrownError) {
        console.log('error', thrownError);
      },
    });
  });
}
