{{ $formClasses := "bg-neutral-500 text-neutral-50 placeholder-neutral-300 focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 focus:ring-offset-transparent m-2 p-3 rounded-lg hover:bg-neutral-500 checked:text-neutral-500" }}

<!-- <script src="/js/forms.js"></script> -->
<script>
 function validate(data) {
     console.log("validating");
     if (data.get("tetanus-shot") === "") {
         console.warn("NO DATE FOR TETANUS SHOT");
         data.set("tetanus-shot", "1111-11-11");
         console.log(data.get("tetanus-shot"));
     }

     if (document.getElementById("medical-coverage").checked && data.get("insurance-name") == "") {
         document.getElementById('warning-insurance').style.visibility = 'visible';
         document.getElementById('warning-insurance').style.height = '';
         document.getElementById('warning-insurance').style.margin = '';
         return false;
     } else {
         document.getElementById('warning-insurance').style.visibility = 'hidden';
         document.getElementById('warning-insurance').style.height = '0';
         document.getElementById('warning-insurance').style.margin = '0';
     }

     if (document.getElementById("medical-coverage").checked && data.get("policy-number") == "") {
         document.getElementById('warning-policy').style.visibility = 'visible';
         document.getElementById('warning-policy').style.height = '';
         document.getElementById('warning-policy').style.margin = '';
         return false;
     } else {
         document.getElementById('warning-policy').style.visibility = 'hidden';
         document.getElementById('warning-policy').style.height = '0';
         document.getElementById('warning-policy').style.margin = '0';
     }

     if (document.getElementById("medical-coverage").checked && document.getElementById("image").files.length === 0) {
         document.getElementById('warning-image').style.visibility = 'visible';
         document.getElementById('warning-image').style.height = '';
         document.getElementById('warning-image').style.margin = '';
         return false;
     } else {
         console.warn(document.getElementById("image"));
         document.getElementById('warning-image').style.visibility = 'hidden';
         document.getElementById('warning-image').style.height = '0';
         document.getElementById('warning-image').style.margin = '0';
     }

     if (!document.getElementById("agreement").checked) {
         document.getElementById('warning').style.visibility = 'visible';
         document.getElementById('warning').style.height = '';
         document.getElementById('warning').style.margin = '';
     }
 };

 function submitForm(e) {
     e.preventDefault();
     const form = document.getElementById('form');
     const data = new FormData(form);
     
     console.log(data.get("birthdate"));
     const birthdate = new Date(data.get("birthdate"));
     const age = calculate_age(birthdate);
     data.append("age", age);
     /* data.delete("image"); */

     validate(data);
     let obj = {};
     data.forEach((value, key) => obj[key] = value);

     // For use in dev
     fetch("http://localhost:4242/health-form", {
         method: "POST",
         body: data
     }).then((res) => {
         console.log(res);
         if (res.ok) {
             if (mtRegistration === 'now')
                 window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13DM3';
             else if (registration === 'now')
                 window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13JPJ';
             else if (registration === 'full')
                 window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13JQE';
             else
                 window.location.href = '/thankyou/';
         }
     });

     // For use in prod
     /* var xhr = new XMLHttpRequest();
      * xhr.onreadystatechange = function() {
      *     if (this.readyState == 4 && this.status == 200) {
      *         if (mtRegistration === 'now')
      *             window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13DM3';
      *         else if (registration === 'now')
      *             window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13JPJ';
      *         else if (registration === 'full')
      *             window.location.href = 'https://secure.myvanco.com/L-Z772/campaign/C-13JQE';
      *         else
      *             window.location.href = '/thankyou/';
      *     }
      * };
      * xhr.open("POST", "https://n8n.tfcconnection.org/webhook/health-form");
      * xhr.send(data); */

     console.log(data);
     /* window.location.replace("https://tfcconnection.org/thankyou/"); */
 }

 function calculate_age(dob) { 
     var diff_ms = Date.now() - dob.getTime();
     var age_dt = new Date(diff_ms); 
     
     return Math.abs(age_dt.getUTCFullYear() - 1970);
 };

 function process() {
     var covered = document.getElementById("medical-coverage").checked;
     console.log(covered);
     if (covered) {
         document.getElementById('policy').hidden = false;
         console.log(document.getElementById('policy'))
         console.log("WOOHOO");
     }
     else {
         document.getElementById('policy').hidden = true;
         /* console.log(document.getElementById('policy')) */
         console.log("NEGATORY");
     }
     document.getElementById('warning').style.visibility = 'hidden';
     document.getElementById('warning-insurance').style.visibility = 'hidden';
     document.getElementById('warning-policy').style.visibility = 'hidden';
     document.getElementById('warning-image').style.visibility = 'hidden';
     document.getElementById('warning').style.height = '0';
     document.getElementById('warning-insurance').style.height = '0';
     document.getElementById('warning-policy').style.height = '0';
     document.getElementById('warning-image').style.height = '0';
     document.getElementById('warning').style.margin = '0';
     document.getElementById('warning-insurance').style.margin = '0';
     document.getElementById('warning-policy').style.margin = '0';
     document.getElementById('warning-image').style.margin = '0';
 }

 document.addEventListener('DOMContentLoaded', process);

 function dated() {
     function nth(d) {
         if ( d > 3 && d < 21 )
             return 'th';
         
         switch (d % 10) {
             case 1:  return "st";
             case 2:  return "nd";
             case 3:  return "rd";
             default: return "th";
         };
     };

     const dateObj = new Date();
     const date = dateObj.getDate();
     const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][dateObj.getMonth()];
     const year = dateObj.getFullYear();

     let dateString = date+nth(date)+' day of '+month+' '+year;

     document.getElementById("current_date").innerHTML = dateString;
 };

 document.addEventListener('DOMContentLoaded', dated);
 const myUrl = new URL(window.location.toLocaleString());
 const mtRegistration = myUrl.searchParams.get('mtregistration');
 const registration = myUrl.searchParams.get('registration');
 console.log(mtRegistration);

</script>

<div id="health-form" class="form text-lg w-full">
  <form id='form' onsubmit="submitForm(event);" autocomplete="on" method="post" target="_parent" class="w-full items-center flex flex-wrap">
    <h3 class="basis-full">2023-2024 Health Form</h3>
    <div class="basis-full flex flex-wrap my-4">
      <label for="firstname" class="basis-full">What is your first and last name?</label>
      <br/>
      <input type="text" id="firstname" name="firstname" required
             placeholder="First Name" class="flex-1 form-input {{ $formClasses }}">
      <input type="text" id="lastname" name="lastname" required
             placeholder="Last Name" class="flex-1 form-input {{ $formClasses }}">
    </div>
    <div class="basis-full my-8">
      <div class="">
        <label for="birthdate" class="">When were you born?</label>
        <input type="date" id="birthdate" name="birthdate"
               class="form-date {{ $formClasses }}" required>
      </div>
    </div>
    <div class="basis-full flex flex-wrap my-4">
      <label for="parentfirstname" class="basis-full">What is your parent's first and last name?</label>
      <input type="text" id="parentfirstname" name="parentfirstname"
             class="flex-1 form-input {{ $formClasses }}"
             placeholder="First Name" required>
      <input type="text" id="parentlastname" name="parentlastname"
             class="flex-1 form-input {{ $formClasses }}"
             placeholder="Last Name" required>
    </div>
    <div class="basis-full flex flex-wrap my-4">
      <label for="street" class="basis-full">What is your address?</label>
      <input type="text" id="street" name="street"
             class="basis-full form-input {{ $formClasses }}"
             placeholder="Street Address">
      <input type="text" id="city" name="city"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="City">
      <input type="text" id="state" name="state"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="State">
      <input type="text" id="zip" name="zip"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Zip Code">
    </div>
    <div class="basis-full flex flex-wrap items-center my-8">
      <div class="flex-auto flex flex-wrap items-center">
        <label for="cellphone" class="mr-4">Parent Cell phone</label>
        <input type="tel" id="cellphone" name="cellphone"
               class="flex-auto form-input {{ $formClasses }}">
      </div>
      <div class="flex-auto flex flex-wrap items-center">
        <label for="homephone" class="mr-4">Home phone</label>
        <input type="tel" id="homephone" name="homephone"
               class="flex-auto form-input {{ $formClasses }}">
      </div>
    </div>
    <div class="basis-full flex flex-wrap my-4">
      <label for="add-emergency-contact" class="basis-full">Additional Emergency Contact</label>
      <input type="text" id="add-emergency-contact" name="add-emergency-contact"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Full Name">
      <input type="tel" id="add-emergency-contact-phone"
             name="add-emergency-contact-phone"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Phone Number">
    </div>
    <div class="basis-full flex flex-wrap my-4">
      <label for="doctor" class="basis-full">Doctor</label>
      <input type="text" id="doctorname" name="doctorname"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Doctor's Name">
      <input type="text" id="doctorcity" name="doctorcity"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Doctor's City">
      <input type="tel" id="doctorphone"
             name="doctorphone"
             class="flex-auto form-input {{ $formClasses }}"
             placeholder="Phone Number">
    </div>
    <div class="basis-full my-4 flex flex-wrap items-center">
      <label for="medical-coverage" class="basis-full mt-8">Is this participant covered by medical insurance?</label>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="medical-coverage" name="medical-coverage"
               onclick="process()" value="yes"
               class="flex-none form-input {{ $formClasses }} checked">
        <label for="medical-coverage" class="flex-auto">Yes</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="medical-coverage" name="medical-coverage"
               onclick="process()" value="no"
               class="flex-none form-input {{ $formClasses }} ">
        <label for="medical-coverage" class="flex-auto">No</label>
      </div>
    </div>
    <div id="policy" class="basis-full flex flex-wrap my-4">
      <label for="insurance-name" class="basis-full">Insurance Name</label>
      <input type="text" id="insurance-name" name="insurance-name"
             class="flex-1 form-input {{ $formClasses }}"
             placeholder="Insurance Name">
      <label for="policy-number" class="basis-full">Policy Number</label>
      <input type="text" id="policy-number" name="policy-number"
             class="flex-1 form-input {{ $formClasses }}"
             placeholder="Policy Number">
    </div>
    <div class="basis-full my-4 mb-8 flex flex-wrap">
      <label for="image" class="basis-full">
        Please give us a scanned copy of your insurance card.
      </label>
      <input type="file" id="image" name="image"
             class="file:my-4 file:ml-2 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-neutral-500 file:text-neutral-100 hover:file:bg-primary-300 hover:file:ring-offset-2 hover:file:ring-2 hover:file:ring-offset-transparent hover:file:text-primary-500 hover:file:ring-primary-500">
    </div>

    <div class="basis-full flex flex-wrap items-center">
      <h3 class="basis-full">Please read and agree to the following</h3>
      <li>On this <span id="current_date"></span>, I/we the parent(s)/legal guardian(s) of the above-named child ("Participant") do hereby delegate to the TFC Connection Staff a "Power of Attorney" for the above-named child for the purpose of having custody of my/our child and my/our consent to any needed emergency/medical treatment and administration of prescribed medications of my/our child.
        <li>In the event that I cannot be reached in an emergency during the dates specified on this form, I hereby give my permission to the physician or dentist selected by the TFC Connection Staff to hospitalize, to secure proper treatment, and/or order any injection, anesthesia, or surgery for my son or daughter as deemed necessary.
      <li>I understand that every activity sponsored by TFC Connection is carefully planned and adequately supervised by mature adults. However, even with the best planning and precaution, unforeseen events can occur. By signing this form as parent/guardian, I/we agree to assume and accept all risks and hazards inherent in ministry-related activities and events. I/we acknowledge that participation in TFC Connection ministry activities and events involves risk to the participant (and to the participant's parents or guardians, if the participant is a minor), and may result in various types of injury including, but not limited to, the following: sickness, exposure to infectious/communicable disease, bodily injury, death, emotional injury, personal injury, property damage, and financial damage.
      <li>In consideration for the opportunity to participate in TFC Connection activities and events, the participant (or parent/guardian if the participant is a minor) acknowledges and accepts the risks of injury associated with participation in and transportation to and from the activities or events. The participant (or parent/guardian) accepts personal financial responsibility for any injury or other loss sustained during the activity or event, or during transportation to and from the activity or event, as well as for any medical treatment rendered to the participant that is authorized by the sponsor or its agents, employees, volunteers, or any other representatives (collectively referred to as the "activity sponsor"). Further, the participant (or parent/guardian) releases and promises to indemnify, defend, and hold harmless the activity sponsor for any injury arising directly or indirectly out of ministry activities and events, or transportation to and from activities and events, whether such injury arises out of the negligence of the activity sponsor, the participant, or otherwise.
      <li>I/we also agree not to hold TFC Connection, it's employees or volunteer assistants liable for damages, losses, or injuries to the participant or their personal property. As parent/guardian, I understand that I am signing for the minor named on this form and the signatures are to provide for the medical release and the liability release.
      <li>Further, should it be necessary for the participant to return home due to medical reasons, disciplinary action, or otherwise, I/we hereby assume transportation costs for their return.
      <li>I give permission to TFC Connection to use my child's image in photos or videos taken at TFC sponsored activities and events in order to publicize or promote TFC activities, including promotional materials, the TFC website, and social media pages.
    </div>

    <div class="basis-full my-4 flex flex-wrap items-center">
      <label for="agreement" class="basis-full mt-8">Do you agree with the above?</label>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="agreement" name="agreement"
               onclick="process()" value="yes"
               class="flex-none form-input {{ $formClasses }} checked">
        <label for="agreement" class="flex-auto">Yes</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="agreement" name="agreement"
               onclick="process()" value="no"
               class="flex-none form-input {{ $formClasses }} ">
        <label for="agreement" class="flex-auto">No</label>
      </div>
    </div>

    <div class="basis-full my-4 flex flex-wrap items-center">
      <label for="allergies" class="basis-full mt-8">What allergies do we need to be aware of?</label>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="none" class="flex-none form-input {{ $formClasses }}" checked>
        <label for="allergies" class="flex-auto">None</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="insects" class="flex-none form-input {{ $formClasses }}">
        <label for="allergies" class="flex-auto">Insects</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="plants" class="flex-none form-input {{ $formClasses }}">
        <label for="allergies" class="flex-auto">Plants or Weeds</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="animals" class="flex-none form-input {{ $formClasses }}">
        <label for="allergies" class="flex-auto">Animals</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="medication" class="flex-none form-input {{ $formClasses }}">
        <label for="allergies" class="flex-auto">Medication</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="allergies" name="allergies"
               value="other" class="flex-none form-input {{ $formClasses }}">
        <input type="text" id="allergies-other" name="allergies-other"
               class="flex-auto form-input {{ $formClasses }}" placeholder="Other">
      </div>
    </div>

    <div class="basis-full mt-10">
      <label for="specific-allergies" class="p-4">
        Please list specific allergies
      </label>
      <br/>
      <textarea id="specific-allergies" name="specific-allergies"
                class="form-input w-full h-64 {{ $formClasses }}"
                placeholder=""></textarea>
    </div>
    <div class="basis-full mt-10">
      <label for="allergic-treatment" class="p-4">
        Treatment for those allergies
      </label>
      <br/>
      <textarea id="allergic-treatment" name="allergic-treatment"
                class="form-input w-full h-64 {{ $formClasses }}"
                placeholder=""></textarea>
    </div>
    <div class="basis-full mt-10">
      <label for="conditions" class="p-4">
        Physical or mental conditions that we should be aware of
      </label>
      <br/>
      <textarea id="conditions" name="conditions"
                class="form-input w-full h-64 {{ $formClasses }}"
                placeholder=""></textarea>
    </div>
    <div class="basis-full my-8">
      <label for="tetanus-shot" class="">When was your last tetanus shot?</label>
      <input type="date" id="tetanus-shot" name="tetanus-shot"
             class="form-date {{ $formClasses }}">
    </div>
    <div class="basis-full my-4 flex flex-wrap items-center">
      <label for="swimming-ability" class="basis-full mt-8">Swimming ability</label>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="swimming-ability" name="swimming-ability"
               value="good" class="flex-none form-input {{ $formClasses }}" checked>
        <label for="swimming-ability" class="flex-auto">Good</label>
      </div>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="swimming-ability" name="swimming-ability"
               value="fair" class="flex-none form-input {{ $formClasses }}">
        <label for="swimming-ability" class="flex-auto">Fair</label>
      <div class="basis-full flex flex-wrap items-center">
        <input type="radio" id="swimming-ability" name="swimming-ability"
               value="none" class="flex-none form-input {{ $formClasses }}">
        <label for="swimming-ability" class="flex-auto">None</label>
      </div>
    </div>
    <div class="basis-full mt-10">
      <h3 class="pt-4 px-4">What medication schedule do you follow?</h3>
      <h4 class="px-4 pt-2 pb-4">Medication must be in it's original labeled container from the pharmacy</h3>
      <label for="medication-schedule" class="p-4">
        Please write them out in this pattern and a new medication on each line.
        <br>
        <table>
          <tr>
            <th>Medication Name</th>
            <th>Time Given</th>
            <th>How Many</th>
            <th>Purpose of Medication</th>
          </tr>
          <tr>
            <td>(Sample) Tums,</td>
            <td>After each meal,</td>
            <td>1-2,</td>
            <td>Stomach issues</td>
          </tr>
        </table> 
      </label>
      <textarea id="medication-schedule" name="medication-schedule"
                class="form-input w-full h-64 {{ $formClasses }}"
                placeholder=""></textarea>
    </div>
    <div class="basis-full mt-10">
      <label for="other-notes" class="p-4">
        Is there anything you want the TFC staff to know that would help your child have a great experience?
      </label>
      <br/>
      <textarea id="other-notes" name="other-notes"
                class="form-input w-full h-64 {{ $formClasses }}"
                placeholder=""></textarea>
    </div>

    <div class="basis-full mt-8">
      <button type="submit" class="content-right rounded-lg bg-primary-700 h-12 w-24 focus:bg-primary-900 focus:ring focus:ring-primary-700 hover:bg-primary-900 float-right">Submit</button>
    </div>

    <div id="warning" class="basis-full mt-10 flex px-4 py-3 rounded-lg bg-[#ef4444] dark:bg-[#ef4444]">
        <span class="text-[#fca5a5] ltr:pr-3 rtl:pl-3 content-right float-right">
            {{ partial "icon.html" (.Get 0 | default "triangle-exclamation") }}
            You have not agreed to the liability release. Please have a guardian read and agree to it first.
        </span>
    </div>

    <div id="warning-insurance" class="basis-full mt-10 flex px-4 py-3 rounded-lg bg-[#ef4444] dark:bg-[#ef4444]">
        <span class="text-[#fca5a5] ltr:pr-3 rtl:pl-3 content-right float-right">
            {{ partial "icon.html" (.Get 0 | default "triangle-exclamation") }}
            You have not entered in your insurance name.
        </span>
    </div>

    <div id="warning-policy" class="basis-full mt-10 flex px-4 py-3 rounded-lg bg-[#ef4444] dark:bg-[#ef4444]">
        <span class="text-[#fca5a5] ltr:pr-3 rtl:pl-3 content-right float-right">
            {{ partial "icon.html" (.Get 0 | default "triangle-exclamation") }}
            You have not entered in a policy number.
        </span>
    </div>

    <div id="warning-image" class="basis-full mt-10 flex px-4 py-3 rounded-lg bg-[#ef4444] dark:bg-[#ef4444]">
        <span class="text-[#fca5a5] ltr:pr-3 rtl:pl-3 content-right float-right">
            {{ partial "icon.html" (.Get 0 | default "triangle-exclamation") }}
            You have not included a copy of your insurance card.
        </span>
    </div>

  </form>
</div>
