const menu = document.querySelector('.menu-toggle'); const nav = document.querySelector('#navigation'); function closeMenu() {menu.setAttribute('aria-expanded','false'); nav.classList.remove('open'); menu.setAttribute('aria-label',document.documentElement.lang==='es'?'Abrir navegación':'Open navigation');} menu.addEventListener('click',()=>{const open=menu.getAttribute('aria-expanded')!=='true';menu.setAttribute('aria-expanded',String(open));menu.setAttribute('aria-label',open?(document.documentElement.lang==='es'?'Cerrar navegación':'Close navigation'):(document.documentElement.lang==='es'?'Abrir navegación':'Open navigation'));nav.classList.toggle('open',open);}); nav.querySelectorAll('a').forEach(a=>a.addEventListener('click',closeMenu)); document.addEventListener('keydown',e=>{if(e.key==='Escape')closeMenu();}); const tabs=[...document.querySelectorAll('[role="tab"]')]; function selectTab(tab,focus=false){tabs.forEach(t=>{const selected=t===tab;t.setAttribute('aria-selected',String(selected));t.tabIndex=selected?0:-1;document.getElementById(t.getAttribute('aria-controls')).hidden=!selected;});if(focus)tab.focus();} tabs.forEach((tab,index)=>{tab.addEventListener('click',()=>selectTab(tab));tab.addEventListener('keydown',e=>{let target;if(e.key==='ArrowRight')target=tabs[(index+1)%tabs.length];if(e.key==='ArrowLeft')target=tabs[(index+tabs.length-1)%tabs.length];if(e.key==='Home')target=tabs[0];if(e.key==='End')target=tabs[tabs.length-1];if(target){e.preventDefault();selectTab(target,true);}});}); document.querySelectorAll('[data-interest]').forEach(link=>link.addEventListener('click',()=>{const area=document.getElementById('interest');area.value=link.dataset.interest;area.dispatchEvent(new Event('change'));})); const form=document.getElementById('inquiry-form'); const spanish=document.documentElement.lang==='es'; const ui=spanish?{open:'Abrir navegación',close:'Cerrar navegación',send:'Enviar consulta',sending:'Enviando…',invalid:'Revise los campos indicados antes de enviar.',retry:'No pudimos confirmar la recepción. Intente nuevamente; sus datos se conservan.',limited:'Se alcanzó el límite de consultas. Intente más tarde o escríbanos por correo.',field:'Revise este campo.',consent:'Confirme el uso de sus datos para responder la consulta.'}:{open:'Open navigation',close:'Close navigation',send:'Send inquiry',sending:'Sending…',invalid:'Please check the highlighted fields before submitting.',retry:'We could not confirm receipt. Please try again; your entries have been preserved.',limited:'The submission limit has been reached. Please try later or email us directly.',field:'Please check this field.',consent:'Please agree to the use of your details to respond to this inquiry.'}; function makeRequestId(){if(typeof crypto.randomUUID==='function')return crypto.randomUUID();const b=crypto.getRandomValues(new Uint8Array(16));b[6]=(b[6]&15)|64;b[8]=(b[8]&63)|128;const h=[...b].map(x=>x.toString(16).padStart(2,'0')).join('');return h.slice(0,8)+'-'+h.slice(8,12)+'-'+h.slice(12,16)+'-'+h.slice(16,20)+'-'+h.slice(20);} let sending=false,requestId=null,signature=null; const submit=document.getElementById('submit-inquiry'),status=document.getElementById('form-status'); const message=form.elements.namedItem('message'); const interest=form.elements.namedItem('interest'),interestGuidance=document.getElementById('interest-guidance'); const inquiryPrompts={ consulting:{guidance:'What decision or operating challenge do you need to address?',placeholder:'Describe the asset, technical question, or decision you need to address.'}, training:{guidance:'What should your team learn or be able to do?',placeholder:'Include the topic, audience, approximate group size, and preferred delivery format.'}, technology:{guidance:'What operating need or opportunity should the technology address?',placeholder:'Describe the technology need, evaluation, adoption, or transfer challenge.'}, other:{guidance:'What would you like to achieve, and which areas are involved?',placeholder:'Describe your needs and the areas you would like to discuss.'} }; function updateInquiryPrompt(){const prompt=inquiryPrompts[interest.value];interestGuidance.textContent=prompt?.guidance||'Tell us what you would like to achieve.';message.placeholder=prompt?.placeholder||'Describe your project, training needs, or technology challenge.';} interest.addEventListener('change',updateInquiryPrompt);updateInquiryPrompt(); message.addEventListener('input',()=>{document.getElementById('message-count').textContent=message.value.length.toLocaleString(spanish?'es':'en')+' / '+(spanish?'4.000':'4,000');}); function clearErrors(){form.querySelectorAll('[aria-invalid]').forEach(el=>{el.removeAttribute('aria-invalid');const help=(el.getAttribute('aria-describedby')||'').split(' ').filter(x=>x&&!x.startsWith('error-')).join(' ');if(help)el.setAttribute('aria-describedby',help);else el.removeAttribute('aria-describedby');});form.querySelectorAll('.field-error').forEach(el=>el.textContent='');} form.addEventListener('submit',async e=>{ e.preventDefault();if(sending)return;if(!form.reportValidity())return;clearErrors(); const values=new FormData(form); const payload={name:document.getElementById("inquiry-name").value,email:values.get('email'),organization:values.get('organization'),interest:values.get('interest'),message:values.get('message'),consent:values.get('consent')==='on',website:values.get('website'),locale:spanish?'es':'en'}; const nextSignature=JSON.stringify(payload);if(signature!==nextSignature||!requestId){requestId=makeRequestId();signature=nextSignature;}payload.requestId=requestId; sending=true;submit.disabled=true;form.setAttribute('aria-busy','true');submit.textContent=ui.sending;status.textContent=''; const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),20000); const formData = new FormData(); Object.entries(payload).forEach(([key, value]) => { formData.append(key, value); }); try{ /*const response=await fetch('enviar.php',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',body:JSON.stringify(payload),signal:controller.signal});*/ const response = await fetch('enviar.php', { method: 'POST', credentials: 'same-origin', body: formData, signal: controller.signal }); const result=await response.json(); if(!response.ok||!result.ok){ if(response.status===422){status.textContent=ui.invalid;let first=null;for(const key of Object.keys(result.fields||{})){const field=form.elements.namedItem(key),error=document.getElementById('error-'+key);if(field&&error){field.setAttribute('aria-invalid','true');field.setAttribute('aria-describedby',((field.getAttribute('aria-describedby')||'')+' '+error.id).trim());error.textContent=key==='consent'?ui.consent:ui.field;if(!first)first=field;}}first?.focus();} else status.textContent=response.status===429?ui.limited:ui.retry; return; } if(typeof result.reference!=='string')throw new Error('invalid response'); document.getElementById('inquiry-reference').textContent=result.reference; document.getElementById('form-fields').hidden=true;const success=document.getElementById('form-success');success.hidden=false;success.focus(); }catch{status.textContent=ui.retry;} finally{clearTimeout(timer);sending=false;submit.disabled=false;submit.textContent=ui.send;form.removeAttribute('aria-busy');} }); document.getElementById('new-inquiry').addEventListener('click',()=>{form.reset();updateInquiryPrompt();clearErrors();signature=null;requestId=null;status.textContent='';document.getElementById('message-count').textContent=spanish?'0 / 4.000':'0 / 4,000';document.getElementById('form-success').hidden=true;document.getElementById('form-fields').hidden=false;form.elements.namedItem('name').focus();}); document.getElementById('year').textContent=new Date().getFullYear(); const links=[...nav.querySelectorAll('a')]; const observer=new IntersectionObserver(entries=>{entries.forEach(entry=>{if(entry.isIntersecting){links.forEach(a=>a.classList.toggle('active',a.getAttribute('href')==='#'+entry.target.id));}});},{rootMargin:'-15% 0px -55% 0px',threshold:0}); document.querySelectorAll('main section[id]').forEach(s=>observer.observe(s)); const languageSwitch=document.querySelector('.language-switch');languageSwitch?.addEventListener('click',()=>{languageSwitch.href=(spanish?'/':'/es')+location.hash;});