<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/41a3aee3ad.js" crossorigin="anonymous"></script>

<script>
  var autocomplete = null
  function initAutocomplete() {
    const options = {
      componentRestrictions: { country: ["au", "nz"]},
      fields: ["address_components"],
      types: ["address"]
    }
    const address1 = $('#street_address')[0];
    autocomplete = new google.maps.places.Autocomplete(address1, options);
    autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    const address1 = $('#street_address')[0];
    const address2 = $('#street_address_2')[0];
    const suburb = $('#suburb')[0];
    const city = $('#city')[0];
    const postal = $('#postal')[0];

    const place = autocomplete.getPlace();
    const address_components = place.address_components;
    var street_number = '';
    var street = '';
    var full_street_address = '';
    for (let i = 0; i < address_components.length; i++) {
      const component = address_components[i];
      switch (component.types[0]) {
        case 'street_number':
          street_number = component.long_name;
          break;
        case 'route':
          street = component.long_name;
          break;
        case 'street_address':
          full_street_address = component.long_name;
          break;
        case 'sublocality_level_1':
          suburb.value = component.long_name;
          break;
        case 'locality':
          city.value = component.long_name;
          break;
        case 'postal_code':
          postal.value = component.long_name;
          break;
      }
    }
    address1.value = full_street_address || street_number + ' ' + street;
    address2.focus();
    document.querySelectorAll('input[req]').forEach(checkInput)
  }

  window.addEventListener('load', function() {
    initAutocomplete();
  })
</script>

<script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD5tTAncWjVZPaPO30fNogteWYvlm2wnIk&libraries=places&callback=initAutocomplete"></script>



{% assign ANZ_group = 'eeabc17d-8364-42fc-b667-c83ca18797f8' %}
{% if current_school.id == '30e76dee-eb3f-46d1-9faf-852e8650287f' %}
  {% comment %} sandbox school variables {% endcomment %}
  {% assign ANZ_group = 'f7cf641a-3198-4897-81c9-993ca28f7f6c' %}
{% endif %}
{% assign ANZ = false %}
{% for group in current_person.groups %}
  {% if group.id == ANZ_group %}
    {% assign ANZ = true %}
    {% break %}
  {% endif %}
{% endfor %}
{% if current_school.properties.anz_address_form == false or current_person.signed_in? == false or current_person.properties.learner_vehicle != 'None' or ANZ == false %}
  <script>
    window.location.replace("/app/courses")
  </script>
{% endif %}

<body>
  <div class="form-window col-12 col-sm-10 col-md-8">
    <div class="form-wrapper">
      <img class="logo" src="{{current_school.logo_url}}">
      <div class="title">
        Let's order your Dasher Kit 
      </div>
      <div class="subtitle">
        All activated Dashers will receive a kit including a DoorDash Hoodie, a delivery Hotbag, and PPE hygiene essentials. Enter your postal details so we can get the right kit sent to you      </div>
      <form class="form">
        <div class="form-row">
          <label class="form-label" for="vehicle">
            Your Vehicle Type
          </label>
          <div class="form-selection-wrapper">
            <select class="form-selection pre-required" id="vehicle" name="vehicle" autocomplete="off" req-sel>
              <option class="form-selection-default" disabled selected value="None">
                Please Select
              </option>
              <option class="form-selection-option" value="Car">
                Car
              </option>
              <option class="form-selection-option" value="Bike">
                Bike
              </option>
              <option class="form-selection-option" value="Scooter/Motorbike">
                Scooter/Motorbike
              </option>
            </select>
            <i class="fal fa-angle-down form-selection-arrow"></i>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label" for="hoodie">
            Size For Your Dasher Hoodie
          </label>
          <div class="form-selection-wrapper">
            <select class="form-selection pre-required" id="hoodie" name="hoodie" autocomplete="off" req-sel>
              <option class="form-selection-default" disabled selected value="None">
                Please Select
              </option>
              <option class="form-selection-option" value="S">
                S
              </option>
              <option class="form-selection-option" value="M">
                M
              </option>
              <option class="form-selection-option" value="L">
                L
              </option>
              <option class="form-selection-option" value="XL">
                XL
              </option>
            </select>
            <i class="fal fa-angle-down form-selection-arrow"></i>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label">
            Address To Send Your Dasher Kit To
          </label>
        </div>

        <div class="form-row">
          <input class="form-input pre-required" type="text" id="street_address" name="street_address" req autocomplete="off">
          <label class="form-label-small" for="street_address">
            Street Address
          </label>
        </div>

        <div class="form-row">
          <input class="form-input" type="text" id="street_address_2" name="street_address_2" autocomplete="off">
          <label class="form-label-small" for="street_address_2">
            Street Address 2
          </label>
        </div>

        <div class="form-one-line">
          <div class="form-row short-width margin">
            <input class="form-input pre-required" type="text" id="suburb" name="suburb" req autocomplete="off">
            <label class="form-label-small" for="suburb">
              Suburb
            </label>
          </div>

          <div class="form-row short-width">
            <input class="form-input pre-required" type="text" id="city" name="city" req autocomplete="off">
            <label class="form-label-small" for="city">
              City
            </label>
          </div>
        </div>

        <div class="form-row">
          <input class="form-input pre-required" type="text" id="postal" name="postal" req autocomplete="off">
          <label class="form-label-small" for="postal">
            Postal Code
          </label>
        </div>
      </form>
      <button class="form-button disabled-button" disabled>
        Continue
      </button>
    </div>
  </div>
</body>

<style>
  
  @font-face {
    font-family: TTNormsPro;
    src: url(https://s3.amazonaws.com/static.northpass.com/fonts/TT+Norms+Pro+Regular.otf);
  }
  @font-face {
    font-family: TTNormsPro;
    src: url(https://s3.amazonaws.com/static.northpass.com/fonts/TT+Norms+Pro+Bold.otf);
    font-weight: bold;
  }
  body {
    background: #f7f7f7;
    display: flex;
    flex-direction: column;
    font-family: TTNormsPro, sans-serif;
    color: black;
  }
  .form-window {
    background: white;
    box-shadow: rgba(87, 100, 126, 0.21) 0px 4px 4px 0px;
    border-radius: 3px;
    margin: 0 auto 40px;
  }
  .form-wrapper {
    width: 90%;
    margin: 40px auto;
  }
  .logo {
    width: 200px;
  }
  .title {
    font-weight: bold;
    font-size: 32px;
    margin-top: 15px;
    margin-bottom: 15px;
  }
  .subtitle {
    margin-bottom: 10px;
  }
  .form {
    display: flex;
    flex-direction: column;
  }
  .form-row {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;
  }
  .form-label {
    font-weight: bold;
  }
  .form-selection-wrapper {
    position: relative;
    margin-top: 5px;
  }
  .form-selection {
    -webkit-appearance: none;
    appearance: none;
    width: 100%;
    background: none;
    border: none;
  }
  .form-selection {
    color: rgb(87, 100, 126);
    background: rgb(247, 247, 247);
    font-weight: bold;
    padding: 8px 8px;
    border-radius: 5px;
  }
  .form-selection-default {
    display: none;
  }
  .form-selection-option {
    color: black;
    font-family: TTNormsPro, sans-serif !important;
  }
  .form-selection-arrow {
    position: absolute;
    top: 50%;
    transform: translate(-150%, -50%);
    color: rgb(87, 100, 126);
    font-weight: 600;
  }
  .form-input {
    border: none;
    border-radius: 5px;
    padding: 8px 8px;
    font-weight: bold;
    background: rgb(247, 247, 247);
  }
  .form-input:hover, .form-input:focus {
    border: #57647e 2px solid;
  }
  .form-label-small {
    color: #57647E;
    font-size: 12px;
    margin-top: 3px;
    font-weight: bold;
  }
  .form-one-line {
    display: flex;
    width: 100%;
  }
  .form-button {
    width: 100%;
    background-color: rgb(235, 22, 0);
    color: white;
    padding: 8px 0;
    border: none;
    border-radius: 100px;
    font-size: 16px;
    font-weight: 700;
    line-height: 19px;
    margin-top: 20px;
    cursor: pointer;
  }
  .required {
    background: rgba(255, 127, 127, 0.6);
  }
  .disabled-button {
    background: lightgray;
    pointer-events: none;
  }
  .short-width {
    width: 48%;
  }
  .margin {
    margin-right: 4%;
  }
  @media only screen and (max-width: 400px) {
    .form-one-line {
      flex-direction: column;
    }
    .short-width {
      width: 100%;
    }
    .margin {
      margin-right: 0;
    }
  }

</style>

<script>
  function debounce(callback, wait) {
    let timeout;
    return (...args) => {
        clearTimeout(timeout);
        timeout = setTimeout(function () { callback.apply(this, args); }, wait);
    };
  }
  function sendForm(){
    if (!checkBeforeSending()) { return false }

    localStorage.setItem("form_filled", "true");

    $('.form-button').unbind("click");
    var form_data = JSON.stringify({
      school_id: '{{current_school.id}}',
      user_id: '{{ current_person.id }}',
      user_email: '{{ current_person.email }}',
      user_name: '{{ current_person.name }}',
      vehicle: $('#vehicle').val(),
      hoodie: $('#hoodie').val(),
      street_address: $('#street_address').val(),
      street_address_2: $('#street_address_2').val(),
      suburb: $('#suburb').val(),
      city: $('#city').val(),
      postal: $('#postal').val()
    })
    var xhr = new XMLHttpRequest();
    var url = "https://www.workato.com/webhooks/rest/bd1a1eb7-7e79-4208-a1db-8e9c7440bcc9/order_kit";
    xhr.addEventListener("load", e => {
        window.location.replace('/app/courses#ommit-infos');
      });
    xhr.open("POST", url, true);
    xhr.send(form_data);
  }

  function checkBeforeSending() {
    $('[req]').each(function(){
      if ($(this).val().length == 0) {
        $(this).addClass('required');
      }

    })
    $('[req-sel]').each(function(){
      if ($(this).val() == "None") {
        $(this).addClass('required');
      }
    })
    return checkIfReady()
  }

  function checkIfReady() {
    if ($('[class*="required"]').length > 0) {
      $('#missing-info-alert').show();
      $('.form-button').prop('disabled', true);
      $('.form-button').addClass('disabled-button');
      $('.form-button').unbind("click")
      return false
    }
    else {
      $('#missing-info-alert').hide();
      $('.form-button').prop('disabled', false);
      $('.form-button').removeClass('disabled-button');
      $('.form-button').click(sendForm)
      return true
    }
  }

  function checkInput(element) {
    if (element.value.length == 0) {
        element.classList.add('required');
      }
    else {
      element.classList.remove('required');
      element.classList.remove('pre-required');
    }
    checkIfReady();
  }

  function checkSelect() {
    if (this.value == "None") {
      this.classList.add('required');
      }
    else {
      this.classList.remove('required');
      this.classList.remove('pre-required');
    }
    checkIfReady();
  }

  function addSelectListener(element) {
    element.addEventListener('change', checkSelect);
  }

  function addInputListener(element) {
    element.addEventListener('keyup', debounce( () => {
      checkInput(element);
    }, 500));
  }

  $(document).ready(function(){
    document.querySelectorAll('select[req-sel]').forEach(addSelectListener);
    document.querySelectorAll('input[req]').forEach(addInputListener);
  });
</script>