<main class="np-main np-box-container">
  <div class="np-box">
    {% include "header_minimal" %}
    <div class="np-box-content-container">
      <form class="np-form np-box-content" name="secondaryRegistrationForm" onsubmit(return false)>
        <div class="np-form-title"> Tell us more </div>
        <div class="form-description">Please provide the additional information below to tailor your experience on the Vision Excellence Institute. We will only use the information to share Professional Education Events happening in your area and to highlight content from the site related to your role and specialty under the My Topics section.</div>

        <div class="form-disclaimer">All fields are required</div>
          <div class="np-form-field">
            <label class="np-input-label" for="company">
              Company / Practice Name*
            </label>
            <input
              class="np-input"
              autofocus="autofocus"
              type="text"
              name="company"
              id="company"
              required
            >
          </div>
          <input type="hidden" id="country" name="country" value="us">
          <div class="np-form-field">
            <label class="np-input-label" for="city">
              City*
            </label>
            <input
              class="np-input"
              type="text"
              name="city"
              id="city"
              required
            >
          </div>
          <div class="np-form-field">
            <label class="np-input-label" for="learner_state">
              State*
            </label>
            <select id="stateSelect">
              <option value="" selected>Select a state</option>
              <option value="Alabama">Alabama</option>
              <option value="Alaska">Alaska</option>
              <option value="Arizona">Arizona</option>
              <option value="Arkansas">Arkansas</option>
              <option value="California">California</option>
              <option value="Colorado">Colorado</option>
              <option value="Connecticut">Connecticut</option>
              <option value="Delaware">Delaware</option>
              <option value="District Of Columbia">District Of Columbia</option>
              <option value="Florida">Florida</option>
              <option value="Georgia">Georgia</option>
              <option value="Hawaii">Hawaii</option>
              <option value="Idaho">Idaho</option>
              <option value="Illinois">Illinois</option>
              <option value="Indiana">Indiana</option>
              <option value="Iowa">Iowa</option>
              <option value="Kansas">Kansas</option>
              <option value="Kentucky">Kentucky</option>
              <option value="Louisiana">Louisiana</option>
              <option value="Maine">Maine</option>
              <option value="Maryland">Maryland</option>
              <option value="Massachusetts">Massachusetts</option>
              <option value="Michigan">Michigan</option>
              <option value="Minnesota">Minnesota</option>
              <option value="Mississippi">Mississippi</option>
              <option value="Missouri">Missouri</option>
              <option value="Montana">Montana</option>
              <option value="Nebraska">Nebraska</option>
              <option value="Nevada">Nevada</option>
              <option value="New Hampshire">New Hampshire</option>
              <option value="New Jersey">New Jersey</option>
              <option value="New Mexico">New Mexico</option>
              <option value="New York">New York</option>
              <option value="North Carolina">North Carolina</option>
              <option value="North Dakota">North Dakota</option>
              <option value="Ohio">Ohio</option>
              <option value="Oklahoma">Oklahoma</option>
              <option value="Oregon">Oregon</option>
              <option value="Pennsylvania">Pennsylvania</option>
              <option value="Rhode Island">Rhode Island</option>
              <option value="South Carolina">South Carolina</option>
              <option value="South Dakota">South Dakota</option>
              <option value="Tennessee">Tennessee</option>
              <option value="Texas">Texas</option>
              <option value="Utah">Utah</option>
              <option value="Vermont">Vermont</option>
              <option value="Virginia">Virginia</option>
              <option value="Washington">Washington</option>
              <option value="West Virginia">West Virginia</option>
              <option value="Wisconsin">Wisconsin</option>
              <option value="Wyoming">Wyoming</option>
            </select>
          </div>
          {% comment %} Country is currently hard coded as United states to start. Eventually will add Canada and Latam (Latin America)  {% endcomment %}
          <div class="np-form-field" style="display:none">
            <label class="np-input-label" for="country">
              Country*
            </label>
            <select id="countrySelect">
              {% comment %} <option value="">Select your Country</option> {% endcomment %}
              <option value="United States" selected>United States</option>
            </select>
          </div>
        <div class="np-form-field">
          <label class="np-input-label" for="learner_role">
            Role*
          </label>
            <select id="roleSelect">
              <option value="" selected>Select your role</option>
              <option value="Ophthalmologist">Ophthalmologist</option>
              <option value="Optometrist">Optometrist</option>
              <option value="Technician">Technician</option>
              <option value="Nurse">Nurse</option>
              <option value="Staff">Staff</option>
              <option value="JNJ Employee">JNJ Employee</option>
            </select>
        </div>
        <div class="np-form-field">
          <label class="np-input-label" for="learner_specialty">
            Primary Specialty*
          </label>
            <select id="specialtySelect">
              <option value="" selected>Select your primary specialty</option>
              <option value="Cataract">Cataract</option>
              <option value="General">General</option>
              <option value="Glaucoma">Glaucoma</option>
              <option value="Vitreoretinal">Vitreoretinal</option>
              <option value="Teaching Institution Faculty">Teaching Institution Faculty</option>
              <option value="JNJ Employee">JNJ Employee</option>
            </select>
        </div>
        <button type="submit" class="np-button np-button-big np-button-large-font np-form-action" id="completeRegistrationBtn">
          <span>Complete Registration</span> <div class="loader" style="display:none;"></div>
        </button>
        <span class="err-msg" style="display:none;">Please complete all fields</span>
      </form>    
    </div>
  </div>
</main>

<script>
console.log("{{current_person.email}}")

  $(document).ready(function() {
    $('#completeRegistrationBtn').click(function(e) {
      e.preventDefault()
      validateForm()
    })
  })
 
 function validateForm() {
  let allDataValidated = false;
  
  let userData = {
    learner_uuid: '{{current_person.id}}',
    company: '',
    city: '',
    state: '',
    country: '',
    role: '',
    specialty: '',
  }
  
  const form = document.forms['secondaryRegistrationForm']

  // validate company field
  let companyField = form["company"].value;
  let cityField = form["city"].value;
  let stateField = $('#stateSelect').val();
  let countryField = $('#countrySelect').val();
  let roleField = $('#roleSelect').val();
  let specialtyField = $('#specialtySelect').val();

  companyField == "" ? "" : userData.company = companyField
  cityField == "" ? "" : userData.city = cityField
  stateField == "" ? "" : userData.state = stateField
  countryField == "" ? "" : userData.country = countryField
  roleField == "" ? "" : userData.role = roleField
  specialtyField == "" ? "" : userData.specialty = specialtyField

  if (userData.company && userData.city && userData.state && userData.country && userData.role && userData.specialty) {

    console.log("user Data: ", userData)

    submitValidatedDataToLocalStorage(userData)
    submitValidatedDataToWorkato(userData)
  } else {
    $('.err-msg').show()
  }
}

function submitValidatedDataToLocalStorage(data) {
  console.log("submitting user data to local storage")

  // Save entered data as individual variables in local storage for later use 
  localStorage.setItem("learnerCompany", data.company);
  localStorage.setItem("learnerCity", data.city);
  localStorage.setItem("learnerState", data.state);
  localStorage.setItem("learnerCountry", data.country);
  localStorage.setItem("learnerRole", data.role);
  localStorage.setItem("learnerSpecialty", data.specialty);

  // Set isValidated value in local storage to true
  localStorage.setItem("learnerCompletedSecondaryRegistration", "true");
}

function submitValidatedDataToWorkato(data) {
  console.log("submitting user data to Workato")

  const secondaryInfoStored = localStorage.getItem("learnerCompletedSecondaryRegistration")

  $('#completeRegistrationBtn').prop("disabled",true);
  $('#completeRegistrationBtn').addClass('submitting')
  $('.loader').show()
  $('#completeRegistrationBtn span').text('Completing Registration')

  $.ajax({
    url: "https://www.workato.com/webhooks/rest/bd1a1eb7-7e79-4208-a1db-8e9c7440bcc9/additional-learner-info",
    data: JSON.stringify(data),
    method: 'POST',
    success: function(res){
      console.log(res)

      setTimeout(function() {
        window.location.replace("/app")
      }, 2000)
    },
    error: function (xhr, status, error) {
      console.error("Error posting to workato!");

      if (secondaryInfoStored == "true") {
        console.log("secondary information completed and stored in local storage")

        setTimeout(function() {
          window.location.replace("/app")
        }, 2000) 
      }
    }
  });
}

</script>

<style>
  body {
    height:auto;
  }

  .np-box {
    margin:64px 0;
  }

  .form-disclaimer {
    font-size:12px;
    margin-bottom:12px;
    margin-top:32px;
    font-weight:700;
  }

  select {
    width: 100%;
    font-size: .9375rem;
    padding: 1rem;
    background: #f2f4f5;
    border: 1px solid #ccd4d8;
    border-radius: 4px;
    color: #1b3e4f;
  }

  .err-msg {
    font-size:14px;
    color:#cc0033;
    margin-top:16px;
  }

  .loader {
    border: 3px solid #f3f3f3;
    border-top: 3px solid #009999;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    animation: spin 1.5s linear infinite;
    margin-left: 12px;
  }

  #completeRegistrationBtn.submitting {
    background-color:#63666a;
    cursor:text;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  @media screen and (min-width: 768px) {
    .np-box-header {
      height: 70px;
      margin-top: 50px;
    }
  }
</style>
