if ($('#progressive_form_wrapper').length) {
  function setCookie(name, value, days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '') + expires + '; path=/';
  }

  function getCookie(name) {
    var pattern = RegExp(name + '=.[^;]*');
    var matched = document.cookie.match(pattern);
    if (matched) {
      var cookie = matched[0].split('=');
      return cookie[1];
    }
    return false;
  }

  function readCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  console.log('cooks', navigator.cookieEnabled);

  // takes one argument, must be unique
  var expanded = [];
  var multiselects = document.getElementsByClassName('multiselect-checkboxes');
  var overselect = document.getElementsByClassName('overSelect');

  function showCheckboxes(i, event) {
    if (multiselects[i]) {
      if (!expanded.includes(multiselects[i].getAttribute('data-type'))) {
        multiselects[i].style.display = 'block';
        expanded.push(multiselects[i].getAttribute('data-type'));
        var isClickInside =
          multiselects[i].getAttribute('data-type') ==
          event.target.getAttribute('data-type');
        if (isClickInside) {
          event.target.classList.add('active');
        }
      } else {
        overselect[i].classList.remove('active');
        multiselects[i].style.display = 'none';
        expanded.splice(
          expanded.indexOf(multiselects[i].getAttribute('data-type')),
          1
        );
      }
    }
  }

  document.onclick = function (e) {
    for (var i = 0; overselect[i]; ++i) {
      if (
        !overselect[0].contains(e.target) &&
        !multiselects[0].contains(e.target) &&
        overselect[0].classList.contains('active')
      ) {
        overselect[0].classList.remove('active');
        multiselects[0].style.display = 'none';
        expanded.splice(
          expanded.indexOf(multiselects[0].getAttribute('data-type')),
          1
        );
      }

      if (
        overselect[1] &&
        !overselect[1].contains(e.target) &&
        !multiselects[1].contains(e.target) &&
        overselect[1].classList.contains('active')
      ) {
        overselect[1].classList.remove('active');
        multiselects[1].style.display = 'none';
        expanded.splice(
          expanded.indexOf(multiselects[1].getAttribute('data-type')),
          1
        );
      }
    }
  };

  var roleElem = document.getElementById('role');
  var expertElem = document.querySelector('#progressive-form-expert');

  if (roleElem) {
    roleElem.addEventListener('change', function () {
      if (document.getElementById('role').value != 'Student') {
        expertElem ? (expertElem.style.display = 'flex') : null;
      } else {
        expertElem ? (expertElem.style.display = 'none') : null;
      }
    });
  } else if (getCookie('prog_role') && getCookie('prog_role') != 'Student') {
    expertElem ? (expertElem.style.display = 'flex') : null;
  }

  var checkedValues = [];
  var dataSourceItems = [];
  var dataInitiativeItems = [];
  var liveDemoMultiselect = [];
  var privatePreviewMultiselect = [];
  var checkboxElements = document.getElementsByClassName(
    'multiselect-checkbox'
  );

  for (var i = 0; checkboxElements[i]; ++i) {
    checkboxElements[i].addEventListener('change', function (event) {
      var type =
        event.target.parentElement.parentElement.getAttribute('data-type');

      if (event.target.checked) {
        dataSourceItems = [];
        dataInitiativeItems = [];
        liveDemoMultiselect = [];
        privatePreviewMultiselect = [];

        checkedValues.push({ id: type, value: event.target.value });
        for (i = 0; i < checkedValues.length; i++) {
          if (checkedValues[i]['id'] == 'datasource') {
            dataSourceItems[i] = checkedValues[i]['value'];
          } else if (checkedValues[i]['id'] == 'datainitiative') {
            dataInitiativeItems[i] = checkedValues[i]['value'];
          } else if (checkedValues[i]['id'] == 'live_demo_multiselect') {
            liveDemoMultiselect[i] = checkedValues[i]['value'];
          } else if (
            checkedValues[i]['id'] == 'private_preview_interest_multiselect'
          ) {
            privatePreviewMultiselect[i] = checkedValues[i]['value'];
          }
        }
      } else if (!event.target.checked) {
        for (var i = 0; i < checkedValues.length; i++) {
          if (checkedValues[i].value === event.target.value) {
            checkedValues.splice(i, 1);
          }
        }

        dataSourceItems = [];
        dataInitiativeItems = [];
        liveDemoMultiselect = [];
        privatePreviewMultiselect = [];

        for (i = 0; i < checkedValues.length; i++) {
          if (checkedValues[i]['id'] == 'datasource') {
            dataSourceItems[i] = checkedValues[i]['value'];
          } else if (checkedValues[i]['id'] == 'datainitiative') {
            dataInitiativeItems[i] = checkedValues[i]['value'];
          } else if (checkedValues[i]['id'] == 'live_demo_multiselect') {
            liveDemoMultiselect[i] = checkedValues[i]['value'];
          } else if (
            checkedValues[i]['id'] == 'private_preview_interest_multiselect'
          ) {
            privatePreviewMultiselect[i] = checkedValues[i]['value'];
          }
        }
      }

      dataSourceItems = dataSourceItems.filter(function (el) {
        return el != null;
      });

      dataInitiativeItems = dataInitiativeItems.filter(function (el) {
        return el != null;
      });

      liveDemoMultiselect = liveDemoMultiselect.filter(function (el) {
        return el != null;
      });

      privatePreviewMultiselect = privatePreviewMultiselect.filter(function (
        el
      ) {
        return el != null;
      });

      if (document.querySelector('#datasource')) {
        if (dataSourceItems.length == 1) {
          document.querySelector('#datasource > option').innerHTML =
            dataSourceItems.length + ' item selected';
        } else if (dataSourceItems.length > 1) {
          document.querySelector('#datasource > option').innerHTML =
            dataSourceItems.length + ' items selected';
        } else {
          document.querySelector('#datasource > option').innerHTML =
            'Select as many as apply...';
        }
        document.querySelector('#datasourcevalues').value = dataSourceItems
          .map(function (item) {
            return item;
          })
          .join(';');
      }

      if (document.querySelector('#datainitiative')) {
        if (dataInitiativeItems.length == 1) {
          document.querySelector('#datainitiative > option').innerHTML =
            dataInitiativeItems.length + ' item selected';
        } else if (dataInitiativeItems.length > 1) {
          document.querySelector('#datainitiative > option').innerHTML =
            dataInitiativeItems.length + ' items selected';
        } else {
          document.querySelector('#datainitiative > option').innerHTML =
            'Select as many as apply...';
        }
        document.querySelector('#datainitiativevalues').value =
          dataInitiativeItems
            .map(function (item) {
              return item;
            })
            .join(';');
      }

      if (document.querySelector('#live_demo_multiselect')) {
        if (liveDemoMultiselect.length == 1) {
          document.querySelector('#live_demo_multiselect > option').innerHTML =
            liveDemoMultiselect.length + ' item selected';
        } else if (liveDemoMultiselect.length > 1) {
          document.querySelector('#live_demo_multiselect > option').innerHTML =
            liveDemoMultiselect.length + ' items selected';
        } else {
          document.querySelector('#live_demo_multiselect > option').innerHTML =
            'Select as many as apply...';
        }
        document.querySelector('#live_demo_multiselect_values').value =
          liveDemoMultiselect
            .map(function (item) {
              return item;
            })
            .join(';');
      }

      if (document.querySelector('#private_preview_interest_multiselect')) {
        if (privatePreviewMultiselect.length == 1) {
          document.querySelector(
            '#private_preview_interest_multiselect > option'
          ).innerHTML = privatePreviewMultiselect.length + ' item selected';
        } else if (privatePreviewMultiselect.length > 1) {
          document.querySelector(
            '#private_preview_interest_multiselect > option'
          ).innerHTML = privatePreviewMultiselect.length + ' items selected';
        } else {
          document.querySelector(
            '#private_preview_interest_multiselect > option'
          ).innerHTML = 'Select as many as apply...';
        }
        document.querySelector(
          '#private_preview_interest_multiselect_values'
        ).value = privatePreviewMultiselect
          .map(function (item) {
            return item;
          })
          .join(';');
      }
    });
  }

  function progressiveCookiesClear() {
    document.cookie.split(';').forEach(function (cookie) {
      var cookieName = cookie.trim().split('=')[0];
      if (cookieName.indexOf('prog_') === 0) {
        setCookie(cookieName, '', 'Thu, 01 Jan 1970 00:00:00 GMT');
      } else if (cookieName.indexOf('wordpress_prog_') === 0) {
        setCookie(cookieName, '', 'Thu, 01 Jan 1970 00:00:00 GMT');
      }
    });

    window.location.reload();
  }

  var validDomain = false;

  var email = jQuery('#progressiveEmail').val();
  var progFormId = jQuery('.progressive_form').attr('data-form-id');
  var submitButton = jQuery('#progSubmitButton');
  var domain = email.split('@')[1];
  var validationError = jQuery('.validation-error');

  function validateDomain() {
    // if ID does not equal the free email form id
    if (
      progFormId != '01449389-d995-4d53-972d-d28575ab45fd' &&
      progFormId != '4dff987f-1641-4073-abcb-67a8e859f09e'
    ) {
      fetch(
        '/wp-content/themes/starburst-theme/includes/js/data/freemaildomains.json'
      )
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          if (
            email.includes('@') &&
            domain.includes('.') &&
            !data.includes(domain)
          ) {
            validationError.text('');
            submitButton.removeAttr('disabled');
            validDomain = true;
          } else if (!email.includes('@') || !domain.includes('.')) {
            validationError.text('Please enter a valid email address');
            submitButton.attr('disabled', 'disabled');
            validDomain = false;
          } else if (data.includes(domain)) {
            validationError.text(
              'Please enter  a valid business email address'
            );
            submitButton.attr('disabled', 'disabled');
            validDomain = false;
          }
        });
    }
  }

  if (email) {
    validateDomain();
  }

  jQuery('#progressiveEmail').on('keyup', function () {
    email = jQuery('#progressiveEmail').val();
    submitButton = jQuery('#progSubmitButton');
    domain = email.split('@')[1];

    if (!domain || !domain.includes('.')) {
      jQuery('#progressiveEmail').on('focusout', function () {
        validateDomain();
      });
    } else {
      validateDomain();
    }
  });

  jQuery(document).ready(function () {
    if (jQuery('#country').val() == 'United States') {
      jQuery('#state-fieldset').show();
    } else {
      jQuery('#state-fieldset').hide();
    }

    jQuery('#country').on('change', function () {
      if (jQuery('#country').val() == 'United States') {
        jQuery('#state-fieldset').show();
      } else {
        jQuery('#state-fieldset').hide();
      }
    });
  });

  // 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('.progressive_form').on('submit', (e) => {
    e.preventDefault();
    var formid = jQuery('.progressive_form').attr('data-form-id');
    var progressiveEmail = jQuery('#progressiveEmail').val();
    var firstname = jQuery('#firstname').val();
    var lastname = jQuery('#lastname').val();
    var fullname = jQuery('#fullname').val();
    var progressivePhone = jQuery('#progressivePhone').val();
    var company = jQuery('#company').val();
    var role = jQuery('#role').val();
    var jobfunction = jQuery('#jobfunction').val();
    var jobtitle = jQuery('#jobtitle').val();
    var datasourcevalues = jQuery('#datasourcevalues').val();
    var datainitiativevalues = jQuery('#datainitiativevalues').val();
    var livedemomultiselectvalues = jQuery(
      '#live_demo_multiselect_values'
    ).val();
    var opt_in = jQuery('#opt_in').val();
    var contact_type = jQuery('#contact_type').val();
    var any_questions_or_message_ = jQuery('#any_questions_or_message_').val();
    var expert = jQuery('#expert').val();
    var agree = jQuery('#agree').val();
    var address = jQuery('#address').val();
    var city = jQuery('#city').val();
    var zip = jQuery('#zip').val();
    var country = jQuery('#country').val();
    var state = jQuery('#state').val();
    var live_demo_dates = jQuery('#live_demo_dates').val();
    var private_preview_interest = jQuery(
      '#private_preview_interest_multiselect_values'
    ).val();
    var meeting_scheduler = jQuery('#meeting_scheduler').val();
    var refer_url = jQuery('#refer_url').val();
    var sf_campaign = jQuery('#sf_campaign').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();
    var chat_bot = jQuery('#chat_bot').val();
    var asset_name = jQuery('#asset_name').val();
    var insert_url = jQuery('#insert_url').val();
    var next = jQuery('#next').val();
    var message = jQuery('#message').val();
    var redirect = jQuery('#redirect').val();
    var datanova_2023___data_rebel_awards = jQuery(
      '#datanova_2023___data_rebel_awards'
    ).val();
    var nomination_behalf = jQuery('#nomination_behalf').val();
    var nomination_reason_question = jQuery(
      '#nomination_reason_question'
    ).val();
    var nominee_name = jQuery('#nominee_name').val();
    var nominee_info = jQuery('#nominee_info').val();
    var role_initiative_question = jQuery('#role_initiative_question').val();
    var real_world_impact_question = jQuery(
      '#real_world_impact_question'
    ).val();
    var job_title = jQuery('#job_title').val();
    var supporting_docs = jQuery('#supporting_docs').val();
    var token = jQuery('#token').val();

    if (token == '') {
      jQuery('#recaptchaMessage').text(
        'Please check Google Recaptcha box before submitting.'
      );
      return;
    } else {
      jQuery('#recaptchaMessage').text('');
    }

    /// move this until after recaptcha validation is successful
    window.dataLayer.push({
      event: 'hubspot-form-success',
      'hs-form-guid': formid,
    });

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

    jQuery.ajax({
      type: 'POST',
      url: 'https://www.starburst.io/wp-admin/admin-ajax.php',
      data: {
        action: 'progressive_form',
        formid: formid,
        progressiveEmail: progressiveEmail,
        firstname: firstname,
        lastname: lastname,
        fullname: fullname,
        progressivePhone: progressivePhone,
        company: company,
        role: role,
        jobfunction: jobfunction,
        jobtitle: jobtitle,
        datasourcevalues: datasourcevalues,
        datainitiativevalues: datainitiativevalues,
        livedemomultiselectvalues: livedemomultiselectvalues,
        opt_in: opt_in,
        contact_type: contact_type,
        any_questions_or_message_: any_questions_or_message_,
        expert: expert,
        agree: agree,
        country: country,
        address: address,
        city: city,
        zip: zip,
        state: state,
        live_demo_dates: live_demo_dates,
        private_preview_interest: private_preview_interest,
        refer_url: refer_url,
        sf_campaign: sf_campaign,
        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,
        chat_bot: chat_bot,
        asset_name: asset_name,
        insert_url: insert_url,
        redirect: redirect,
        datanova_2023___data_rebel_awards: datanova_2023___data_rebel_awards,
        nomination_behalf: nomination_behalf,
        nomination_reason_question: nomination_reason_question,
        nominee_name: nominee_name,
        nominee_info: nominee_info,
        role_initiative_question: role_initiative_question,
        real_world_impact_question: real_world_impact_question,
        job_title: job_title,
        supporting_docs: supporting_docs,
        token: token,
      },
      success: function (data) {
        if (next === 'message') {
          if (jQuery('#data-rebel-form_wrapper').length) {
            jQuery('#data-rebel-form_wrapper').html(
              '<div class="progressive_form_message_wrapper">' +
                message +
                '</div>'
            );
          } else {
            jQuery('.progressive_form_header_label').hide();
            jQuery('.event-form-policy-message').hide();
            jQuery('#progressive_form_wrapper').html(
              '<div class="progressive_form_message_wrapper">' +
                message +
                '</div>'
            );
          }
          if (typeof qualified !== undefined) {
            qualified('saveFormData', { email: progressiveEmail });
            qualified('showFormExperience', 'experience-1693316092442');
          }
        } else {
          if (meeting_scheduler) {
            if (typeof qualified !== undefined) {
              qualified('saveFormData', { email: progressiveEmail });
            }
            window.location.replace(redirect + '?qualifiedScheduler=true');
          } else {
            window.location.replace(redirect);
          }
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        console.log('error', thrownError);
      },
    });
  });

  jQuery(function () {
    let phoneValidationError = jQuery('.phone-validation-error');
    $('#progressivePhone').keyup(function () {
      var VAL = this.value;

      var phone = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/;
      if (!phone.test(VAL)) {
        phoneValidationError.text(
          'Please enter a valid phone number. Only numbers.'
        );
      } else {
        phoneValidationError.text('');
      }
    });
  });

  function getUrlParameter(param) {
    var pageURL = window.location.search.substring(1),
      URLVariables = pageURL.split('&'),
      parameterName,
      i;

    for (i = 0; i < URLVariables.length; i++) {
      parameterName = URLVariables[i].split('=');

      if (parameterName[0] === param) {
        return parameterName[1] === undefined
          ? true
          : decodeURIComponent(parameterName[1]);
      }
    }
    return false;
  }

  if (document.querySelector('.progressive_form')) {
    var campaignParam = getUrlParameter('utm_campaign');
    var sourceParam = getUrlParameter('utm_source');
    var mediumParam = getUrlParameter('utm_medium');
    var contentParam = getUrlParameter('utm_content');
    var termParam = getUrlParameter('utm_term');
    var chatBotParam = getUrlParameter('chat-bot');
    var theUrl = window.location.href;

    if (theUrl) {
      document.querySelector('.progressive_form > #refer_url').value = theUrl;
    }

    if (campaignParam) {
      document.querySelector('.progressive_form > #utm_campaign').value =
        campaignParam;
    }

    if (sourceParam) {
      document.querySelector('.progressive_form > #utm_source').value =
        sourceParam;
    }

    if (mediumParam) {
      document.querySelector('.progressive_form > #utm_medium').value =
        mediumParam;
    }

    if (contentParam) {
      document.querySelector('.progressive_form > #utm_content').value =
        contentParam;
    }

    if (termParam) {
      document.querySelector('.progressive_form > #utm_term').value = termParam;
    }

    if (chatBotParam) {
      if (chatBotParam == 'true') {
        document.querySelector('.progressive_form > #chat_bot').value =
          chatBotParam;
      }
    }
  }
}
