(function () { var f = document.querySelector('form[data-endpoint]'); if (!f) return; var st = document.getElementById('st'), t0 = Date.now(), busy = false, mail = f.getAttribute('data-mail'); function say(msg, ok) { st.textContent = msg; st.className = 'status ' + (ok ? 'ok' : 'err'); } f.addEventListener('submit', function (e) { e.preventDefault(); if (busy) return; var body = { consent: f.consent.checked, t: Date.now() - t0 }; Array.prototype.forEach.call(f.elements, function (el) { if (el.name && el.name !== 'consent') body[el.name] = (el.value || '').trim(); }); if (!body.nombre || !/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(body.email || '') || (body.mensaje || '').length < 10 || !body.consent || (f.empresa && !body.empresa)) { say('Revisa los campos obligatorios, el correo y que el mensaje tenga al menos 10 caracteres, y marca la casilla de privacidad.', false); return; } if (body.sitio && !/^https?:\/\//.test(body.sitio)) { say('La web debe empezar por http:// o https://', false); return; } busy = true; say('Enviando…', true); fetch(f.getAttribute('data-endpoint'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return { ok: r.ok && j.ok, j: j }; }); }) .then(function (x) { if (x.ok) { f.reset(); say(f.getAttribute('data-ok'), true); } else { say((x.j && x.j.error) || 'No se pudo enviar. Escríbenos a ' + mail + '.', false); } }) .catch(function () { say('No se pudo enviar. Escríbenos a ' + mail + '.', false); }) .then(function () { busy = false; }); }); })();