function nextPage(keyName, iframe) {
  console.log(`${keyName} saved to firestore`);
  iframe.src = "https://www.judicialacademy.org/thankyou.html"
}

function submitError(keyName, error) {
  console.error(`ERROR saving ${keyName} to firestore`, error);
  alert("Sorry, something went wrong and the answer wasn't saved. Please try again and if the problem continues contact an administrator.");
}

function saveToFirestore() {
  event.preventDefault();

  const iframeWrapper = parent.document.querySelectorAll('[id*=test_form]')[0]
  const keyName = iframeWrapper.id
  const iframe = iframeWrapper.querySelector('iframe:first-of-type')
  const docId = firebase.auth().currentUser.uid
  const answer = document.getElementById('form-answer').value

  db.collection("users").doc(docId).set({
    [keyName]: answer
  }, { merge: true })
  .then(function() {
    nextPage(keyName, iframe);
  })
  .catch(function(error) {
    submitError(keyName, error);
  });
}
