jQuery.noConflict(); (function ($) { $(function () { let googleMapsLoaded = false; // Map variables var selectedLat = '0'; var selectedLng = '0'; var selectedAddress = ''; var selectedAddressValue = ''; var schoolPlaceId = ''; var abortSignals = []; window.addEventListener("message", (e) => { if (e.data.type === "hsFormCallback" && e.data.eventName === "onFormReady") { // Google Maps API deferred loading once if(!googleMapsLoaded){ loadGoogleMaps(); } // Modify each form $("form.hs-form").each(function(index) { if($(this).find("#schools-search-"+index).length === 0){ if($(this).hasClass( 'plugin-modified' )){ return; } // Get inputs references $(this).attr("autocomplete", "off"); $(this).addClass("plugin-identifier-"+index); $(this).addClass("plugin-modified"); const schoolInput = $(this).find("[name='company']"); const placeIDInput = $(this).find("[name='place_id']"); const addressInput = $(this).find("[name='address']"); const newSchoolInput = $(this).find("[name='colegio_nuevo']"); $(this).data('case','selected-school' ) // only these cases: 'selected-school' | 'add-school' // Kill if inputs are not complete if ( !schoolInput || schoolInput.length === 0 || !placeIDInput || placeIDInput.length === 0 || !addressInput || addressInput.length === 0 || !newSchoolInput || newSchoolInput.length === 0 ) { return; } console.log('Form is beign modified', index) // Initial setup schoolInput.prop('readonly',true); schoolInput.attr('style', 'display:none'); addressInput.attr('style', 'display:none'); const schoolParent = schoolInput.parent("div.input"); const searchIcon = ` `; schoolParent.prepend( `` ); if (schoolParent.find("#schools-search-"+index).length === 0) { schoolInput.before( '' ); } else { $("#schools-search-"+index+" .schools-search__list li").remove(); $("#schools-search-"+index).attr( "style", "overflow:hidden;max-height:0;width:100%;visibility:hidden;opacity:0;margin-bottom:18px" ); $(this).find(".container-search .spinner").remove(); } schoolInput.before( `` ) schoolInput.after( `` ) // End initial setup // Flag to avoid duplicate searches $(this).data('search-executed',false) const debouncedSearch = debounce((e, formRef, index) => { if (!$(`.plugin-identifier-${index}`).data('search-executed')) { //revisar performSearch(e, formRef, index); } $(`.plugin-identifier-${index}`).data('search-executed', false) }, 1500); // Keyboard event actions /* Key up */ $(this).find(".only-search-input").keyup(createKeyupHandler( $(this), index)); function createKeyupHandler( formRef, index) { return function(e) { keyupHandler(e, formRef, index); }; } function keyupHandler(e, formRef, index){ if (e.key !== "Enter") { debouncedSearch(e, formRef, index); } } /* Key down */ $(this).find(".only-search-input").keydown(createKeydownHandler( $(this), index)); function createKeydownHandler( formRef, index) { return function(e) { keydownHandler(e, formRef, index); }; } function keydownHandler(e, formRef, index){ if (e.key === "Enter") { e.preventDefault(); $(`.plugin-identifier-${index}`).data('search-executed', true) performSearch(e, formRef, index); } } // Logic to open dropdown options $(this).find(".only-search-input").focusin((e) => { const searchList = $("#schools-search-"+index+" .schools-search__list"); if ($(".result-item").length > 0 && $(e.target).val() !== "") { $("#schools-search-"+index).attr("style", "visibility:visible; max-height:250px; overflow-y:scroll;margin-bottom:18px"); } else if ($(e.target).val() && $(e.target).val().length > 3) { $("#schools-search-"+index+" .schools-search__list li").remove(); searchList.append( `
  • Añadir escuela: "${$(e.target).val()}"
  • ` ); $("#schools-search-"+index).attr("style", "visibility:visible; max-height:100px; overflow-y:scroll;margin-bottom:18px"); $(this).find(".add_my_school").on("click", () => { const newSchoolTitle = $(this).find(".only-search-input").val(); if (newSchoolTitle !== "") { const ref = $(this).find("input[name='company']"); ref.val(newSchoolTitle); ref.trigger("change"); $("#schools-search-"+index+" .schools-search__list li").remove(); $("#schools-search-"+index).attr( "style", "overflow:hidden;max-height:0;width:100%;visibility:hidden;opacity:0;margin-bottom:18px" ); $(this).find(".only-search-input").val(""); } }); } }); // Check if the map container exists if (isMapLoaded(schoolParent,index)) { schoolParent.append( `
    ` ); } const confirmLocationContainer = $("#confirmContainer-"+index)[0]; const addressContainer = $("#addressContainer-"+index)[0]; const mapContainer = $("#map-"+index)[0]; // Check everytime school was changed schoolInput.on("change", schoolChangeHandler .bind(null,confirmLocationContainer,addressContainer,mapContainer,index)) function schoolChangeHandler(confirmLocationContainer,addressContainer,mapContainer,index){ showMap(confirmLocationContainer,addressContainer,mapContainer,index); const companyInputRef = $(`.plugin-identifier-${index} [name='company']`) if (selectedLat !== "0" && selectedLng !== "0") { // Display School Map in View initMap(selectedLat, selectedLng,false,index); } else { // Default Position in Europe if(companyInputRef.val() === ""){ let latDefault = 40.41; let lngDefault = -3.70; initMap(latDefault, lngDefault, true, index); } } } $("#confirmLocationBtn-"+index).click(()=>confirmLocation(index, schoolPlaceId, selectedAddress,$(this).data('case'), selectedAddressValue)) } // Map functions function isMapLoaded(parent, index) { return parent.find("#map-"+index).length === 0; } function showMap(confirmLocationContainer,addressContainer,mapContainer,index) { mapContainer.style.height = "400px"; confirmLocationContainer.style.display = "flex"; addressContainer.style.display = "flex"; toggleConfirmBtn(true,index); toggleShowAddress(false,index, addressContainer); $('#addressText-'+index).attr('style', 'display:none'); } async function initMap(lat, lng, selectable = false, index) { if (!lat || !lng) return; // Toggle input texts if (selectable) { toggleAddSchoolTextVisibility(true, index); toggleSelectSchoolLocationTextVisibility(true, index); } else { toggleAddSchoolTextVisibility(false, index); toggleSelectSchoolLocationTextVisibility(false, index); } let selector = '#map-'+index; const mapContainer = $(selector)[0]; const position = { lat: lat, lng: lng }; const map = new google.maps.Map(mapContainer, { zoom: selectable ? 5 : 18, center: position, mapId: '4504f8b57377c3d0' }); // School Marker const marker = new google.maps.Marker({ map: map, position: position, draggable: selectable, animation: google.maps.Animation.DROP, }); if (selectable) { const infoWindow = new google.maps.InfoWindow(); marker.addListener('dragend', (e) => { const position = marker.getPosition(); infoWindow.close(); getPlaceIdNearestToSchool(position.lat(), position.lng()); toggleConfirmBtn(true,index); infoWindow.setContent(`Ubicación: ${position.lat().toFixed(2)}, ${position.lng().toFixed(2)}`); infoWindow.open(marker.map, marker); }); } } function confirmLocation(index, schoolPlaceId, selectedAddress, flowCase, selectedAddressValue) { /* Get input references */ const placeIdInputRef = $(`.plugin-identifier-${index} [name="place_id"]`); const addressRef = $(`.plugin-identifier-${index} [name='address']`); if (!!placeIdInputRef && selectedAddress) { // Show confirmed location info toggleConfirmBtn(false, index); if (flowCase === 'selected-school') { const addressItems = $('#addressItems-'+index); addressItems.html(`

    Ubicación confirmada:

    Dirección: ${selectedAddress}

    `); placeIdInputRef.val(schoolPlaceId); placeIdInputRef.trigger('change') $('#addressText-'+index).html("Dirección: " + selectedAddress); $('#addressText-'+index).attr('style', 'display:block;'); toggleShowSchoolConfirmed(true,index); } if (flowCase === 'add-school') { addressRef.val(selectedAddressValue) addressRef.trigger('change') } $("#schools-search-"+index).attr( "style", "overflow:hidden;max-height:0;width:100%;visibility:hidden;opacity:0;margin-bottom:18px" ); } } // Search functions function performSearch(e, formRef, index) { abortSignals.map((controller) => { controller.abort(); abortSignals.splice(0, 1); }); if (e.target.value.length > 3) { if ($(formRef).find(".container-search .spinner").length === 0) { $(formRef).find(".container-search").append( '
    ' ); } const schoolInput = $(formRef).find("[name='company']"); const addressInput = $(formRef).find("[name='address']"); const newCompanyInput = $(formRef).find("[name='colegio_nuevo']"); schoolInput.attr('style', 'display:none'); schoolInput.prop('readonly',true); addressInput.attr('style', 'display:none'); addressInput.val(""); addressInput.trigger("change"); // Set new value for adding school field newCompanyInput.prop('checked', false); newCompanyInput.val(false); newCompanyInput.trigger('change'); ajaxCallToAPI.apply(this, [schoolInput, e.target.value, formRef]); } else { $("#schools-search-"+index+" .schools-search__list li").remove(); $("#schools-search-"+index).attr( "style", "overflow:hidden;max-height:0;width:100%;visibility:hidden;opacity:0;margin-bottom:18px" ); $(formRef).find(".container-search .spinner").remove(); } } async function ajaxCallToAPI(schoolInput, query, formRef) { const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); const controller = new AbortController(); const signal = controller.signal; abortSignals.push(controller); let countryInput = $(formRef).find("[name='country']"); //Before dev //const searchURL = `https://getschoolsbyaddress-ktovd4eqpq-uc.a.run.app`; //After pre //const searchURL = `https://mj3lz4ddkb.execute-api.eu-west-1.amazonaws.com/getPlacesByAddress`; //After prod const searchURL = `https://zbmd37v663.execute-api.eu-west-1.amazonaws.com/getPlacesByAddress`; if (!!countryInput.val()) { query += ", " + countryInput.val(); } const raw = JSON.stringify({ address: query, }); const requestOptions = { method: "POST", headers: { ...myHeaders, Accept: "application/json", "Content-Type": "application/json" }, body: raw, mode: "cors", signal: signal, redirect: "follow", }; try { const response = await fetch(searchURL, requestOptions); if (response.ok) { const results = JSON.parse(await response.text()).results; handleSchoolsFound(results, query, index, formRef); } else { throw new Error('Error while calling API on server'); } } catch (error) { console.log(error); if (error.message !== "The user aborted a request.") { $(".container-search .spinner").remove(); } } } function handleSchoolsFound(res, query, index, formRef) { // Display School List $("#schools-search-"+index+" .schools-search__list li").remove(); const searchList = $("#schools-search-"+index+" .schools-search__list"); if (!!res) { // Add address to school object for (let school of res) { let country = school.addressComponents.find(component => component.types.includes("country")); let city = school.addressComponents.find(component => component.types.includes("locality")); let bothExists = !!country?.longText && !!city?.longText; let countryText = !!country ? country.longText : ''; let cityText = !!city ? city?.longText : ''; let separator = bothExists ? ', ' : ''; let addressExtra = (!!country || !!city) ? `(${cityText}${separator}${countryText})` : ''; school.addressExtra = addressExtra; } // Sort response by address res.sort((a, b) => { if (a.addressExtra < b.addressExtra) return -1; if (a.addressExtra > b.addressExtra) return 1; return 0; }); // Add items to dropdown for (let school of res) { searchList.append( `
  • ${school.displayName.text} ${school.addressExtra}
  • ` ); } searchList.append( `
  • Añadir escuela: "${query}"
  • ` ); } // Select School Item $(".result-item").on("click", (e) => { if (!e.currentTarget.classList.contains('add_my_school')) { const formRef = $(`.plugin-identifier-${index}`) formRef.data('case','selected-school'); selectedLat = $(e.target).data("lat"); selectedLng = $(e.target).data("lng"); selectedAddress = $(e.target).data("address"); schoolPlaceId = $(e.target).data("place-id"); toggleShowSchoolConfirmed(false, index); const ref = $(formRef).find("input[name='company']"); ref.attr('style', 'display:block'); ref.val($(e.target).data("school")); ref.trigger("change"); } else { addMySchoolClick(index); } }) // Hide spinner $(".container-search .spinner").remove(); if (!!res && res.length > 0) { // Show school list $("#schools-search-"+index).attr("style", "visibility:visible; max-height:250px; overflow-y:scroll;margin-bottom:18px"); toggleAddSchoolTextVisibility(false, index); } else { // No Schools Found $("#schools-search-"+index).attr("style", "visibility:visible; max-height:100px; overflow-y:scroll;margin-bottom:18px"); $(formRef).find(".add_my_school").on("click", () => { addMySchoolClick(); }); } } async function getPlaceIdNearestToSchool(lat, lng) { const projectHeaders = new Headers(); const controller = new AbortController(); abortSignals.push(controller); const raw = JSON.stringify({ latitude: lat, longitude: lng, }); //Dev //const schoolsByLatLngURL = `https://getschoolsbylatlong-ktovd4eqpq-uc.a.run.app`; //Pre //const schoolsByLatLngURL = `https://mj3lz4ddkb.execute-api.eu-west-1.amazonaws.com/getPlacesByLatAndLong`; //Prod const schoolsByLatLngURL = `https://zbmd37v663.execute-api.eu-west-1.amazonaws.com/getPlacesByLatAndLong`; const requestOptions = { method: "POST", maxBodyLength: Infinity, headers: { ...projectHeaders, "Content-Type": "application/json" }, body: raw }; try { const response = await fetch(schoolsByLatLngURL, requestOptions); if (response.ok) { const responseParsed = JSON.parse(await response.text()); const result = responseParsed?.result; if (!!result && result.length > 0) { selectedAddress = result[0].adrFormatAddress; selectedAddressValue = result[0].addressComponents.reduce((accumulator, currentValue) => { return accumulator + currentValue.longText+", "; }, "").slice(0, -2); } } else { throw new Error('Error ' + response.status + ' on API call: ' + response.statusText); } } catch (error) { console.warn("Couldn't obtain nearest place id to school\n", error); schoolPlaceId = ''; } } // Helper functions function debounce(callback, ms) { let timerId = 0; return (...args) => { clearTimeout(timerId); timerId = setTimeout(() => { callback(...args); }, ms || 0); }; } function clearSelectedLocation(index) { selectedLat = "0"; selectedLng = "0"; selectedAddress = ""; toggleShowSchoolConfirmed(false, index); } function addMySchoolClick(index) { clearSelectedLocation(index); const formRef = $(`.plugin-identifier-${index}`) formRef.data('case','add-school'); const schoolInputRef = $(`.plugin-identifier-${index} [name='company']`); const addressRef = $(`.plugin-identifier-${index} [name='address']`); const newCompanyRef = $(`.plugin-identifier-${index} [name='colegio_nuevo']`); // Show editable inputs for manual entry schoolInputRef.attr('style', 'display:block'); schoolInputRef.prop('readonly', false); addressRef.attr('style', 'display:block'); $('#addressText-'+index).attr('style', 'display:none'); //Clear any input values schoolInputRef.val(''); schoolInputRef.trigger('change'); addressRef.val(''); addressRef.trigger('change'); // Set new value for adding school field newCompanyRef.prop('checked', true); newCompanyRef.val(true); newCompanyRef.trigger('change'); schoolInputRef.focus(); const addSchoolNameExists = $('#addSchoolNameText-'+index); // Check if text exists if (!addSchoolNameExists || addSchoolNameExists.length === 0) { // if it doesnt exists, add element insertSchoolNameText(index); } toggleAddSchoolTextVisibility(true, index); $(`#schools-search-${index} .schools-search__list li`).remove(); $(`#schools-search-${index}`).attr( "style", "overflow:hidden;max-height:0;width:100%;visibility:hidden;opacity:0;margin-bottom:18px" ); $(".only-search-input").val(""); } function insertSchoolNameText(index) { var addSchoolNameElDiv = document.createElement("div"); addSchoolNameElDiv.id = "addSchoolNameText-"+index; addSchoolNameElDiv.classList.add("addSchoolNameText", "legal-consent-container", "hs-richtext"); addSchoolNameElDiv.style.visibility = "hidden"; addSchoolNameElDiv.style.opacity = "0"; addSchoolNameElDiv.style.transition = "visibility 0s, opacity 0.5s linear"; addSchoolNameElDiv.innerHTML = `

    Añade el nombre del colegio

    `; const schoolInputRef = $(`.plugin-identifier-${index} [name='company']`); const schoolParentRef = schoolInputRef.parent("div.input"); schoolParentRef[0].insertBefore(addSchoolNameElDiv, schoolInputRef[0]); } // Toogle functions function toggleAddSchoolTextVisibility(visible = false,index) { let addSchoolNameEl = $('#addSchoolNameText-'+index)[0]; if (!!addSchoolNameEl) { if (!visible) { addSchoolNameEl.style.display = 'none'; addSchoolNameEl.style.visibility = 'hidden'; addSchoolNameEl.style.opacity = '0'; } else { addSchoolNameEl.style.display = 'block'; addSchoolNameEl.style.visibility = 'visible'; addSchoolNameEl.style.opacity = '1'; } } } function toggleSelectSchoolLocationTextVisibility(visible = false,index) { let selectSchoolLocationEl = $('#selectSchoolLocationText-'+index)[0]; if (!!selectSchoolLocationEl) { if (!visible) { selectSchoolLocationEl.style.display = 'none'; selectSchoolLocationEl.style.visibility = 'hidden'; selectSchoolLocationEl.style.opacity = '0'; } else { selectSchoolLocationEl.style.display = 'block'; selectSchoolLocationEl.style.visibility = 'visible'; selectSchoolLocationEl.style.opacity = '1'; } } } function toggleConfirmBtn(visible = false,index) { const confirmLocationBtn = $("#confirmLocationBtn-"+index)[0]; const confirmLocationText = $("#confirmLocationText-"+index)[0]; if (!!confirmLocationBtn && !!confirmLocationText) { if (!visible) { confirmLocationBtn.style.display = "none"; confirmLocationText.style.visibility = "visible"; confirmLocationText.style.opacity = "1"; } else { confirmLocationBtn.style.display = "block"; confirmLocationText.style.visibility = "hidden"; confirmLocationText.style.opacity = "0"; } } } function toggleShowAddress(visible = false, index, addressContainer) { const addressItems = $("#addressItems-"+index)[0]; if (!!addressContainer && !!addressItems) { if (!visible) { if (addressItems.classList.contains('visible')) { addressItems.classList.remove('visible'); } } else { if (!addressItems.classList.contains('visible')) { addressItems.classList.add('visible'); } } } } function toggleShowSchoolConfirmed(visible = false, index) { const addressConfirmed = $("#addressConfirmed-"+index)[0]; if (!!addressConfirmed) { if (!visible) { addressConfirmed.style.display = 'none'; } else { addressConfirmed.style.display = 'block'; } } } }) // ----Script Functions---- function loadGoogleMaps() { var apiKey = 'AIzaSyDo_NiA2rfp6hUsAssFFBWtTKgnJUtS68s'; var script = document.createElement('script'); script.src = 'https://maps.googleapis.com/maps/api/js?key=' + apiKey+'&loading=async'; script.async = true; document.head.appendChild(script); googleMapsLoaded = true; } } }); }); })(jQuery);