import {normalizePhone, registrationErrors} from './registration-validation.mjs'; import {gpmPerM3h, sizeFilters, sizeHeaters, sizeIonizers, sizeSofteners, sizeTanks} from './sizing-calculations.mjs?v=6'; import {sizingFailureReason} from './sizing-feedback.mjs?v=6'; import {downloadTechnicalSheet, printArabicTechnicalSheet} from './sizing-technical-sheet.mjs?v=5'; import {sizingArabic, sizingEnglishFields, sizingEnglishOptions, sizingEnglishTitles} from './sizing-arabic.mjs?v=6'; const arabic = /^ar(?:-|$)/i.test(document.documentElement.lang); const englishWording = text => window.almCustomerText && Object.hasOwn(window.almCustomerText, text) ? window.almCustomerText[text] : text; const wording = (text, values) => { const label = arabic && Object.hasOwn(sizingArabic, text) ? sizingArabic[text] : englishWording(text); return values ? label.replace(/\{(\w+)\}/g, (token, key) => Object.hasOwn(values, key) ? values[key] : token) : label; }; const root = document.getElementById('equipment-calculator'); const access = document.getElementById('sizing-access'); const accessForm = document.getElementById('sizing-access-form'); const accessStatus = document.getElementById('sizing-access-status'); const salesEmail = document.querySelector('meta[name="alm-public-email"]')?.content || 'info@maymanah.com.sa'; const accessKey = 'almaymanah-sizing-access-v1-session'; const draftKey = 'almaymanah-sizing-draft-v1'; const editDetails = document.getElementById('sizing-edit-details'); const emailDetails = editDetails.closest('.sizing-session'); function stored(key) { try { return JSON.parse(sessionStorage.getItem(key)) || {}; } catch { return {}; } } function store(key, value) { try { sessionStorage.setItem(key, JSON.stringify(value)); } catch { /* The calculator also works without storage. */ } } let visitor = stored(accessKey); const savedDraft = stored(draftKey); const draft = {equipment: savedDraft.equipment, forms: {...savedDraft.forms}}; function showAccessErrors(errors) { for (const key of ['name','company','email','phone']) { const input = accessForm.elements[key]; const error = wording(errors[key] || ''); document.getElementById(input.id + '-error').textContent = error; input.setCustomValidity(error); input.setAttribute('aria-invalid', String(Boolean(errors[key]))); } } // The contact form belongs to the optional email action. All five calculators open immediately. function closeDetails() { access.hidden = true; editDetails.setAttribute('aria-expanded', 'false'); editDetails.focus(); } root.hidden = false; document.querySelector('.sizing-review').hidden = false; access.hidden = true; editDetails.setAttribute('aria-controls', access.id); editDetails.setAttribute('aria-expanded', 'false'); root.querySelector('#sizing-options').before(emailDetails, access); for (const input of accessForm.querySelectorAll('input[required]')) input.required = false; editDetails.addEventListener('click', () => { if (!access.hidden) { closeDetails(); return; } for (const key of ['name', 'email', 'phone', 'company']) accessForm.elements[key].value = visitor[key] || ''; access.hidden = false; editDetails.setAttribute('aria-expanded', 'true'); accessForm.elements.name.focus(); }); accessForm.addEventListener('input', event => { event.target.setCustomValidity?.(''); event.target.removeAttribute('aria-invalid'); const error = document.getElementById(event.target.id + '-error'); if (error) error.textContent = ''; accessStatus.textContent = ''; }); accessForm.addEventListener('submit', event => { event.preventDefault(); const data = Object.fromEntries([...new FormData(accessForm)].map(([key, value]) => [key, value.trim()])); data.phone = normalizePhone(data.phone); const errors = Object.fromEntries(Object.entries(registrationErrors(data)).filter(([name]) => data[name])); showAccessErrors(errors); if (Object.keys(errors).length) { accessForm.elements[Object.keys(errors)[0]].focus(); return; } visitor = data; store(accessKey, visitor); closeDetails(); const selected = forms.find(form => !form.hidden); if (selected && draft.forms[selected.dataset.calculator]?.calculated) calculate(selected, false); }); const status = root.querySelector('#sizing-status'); const results = root.querySelector('#sizing-options'); const emptyState = root.querySelector('#sizing-empty'); const resultPanel = root.querySelector('.sizing-results'); const forms = [...root.querySelectorAll('form[data-calculator]')]; const choices = [...root.querySelectorAll('[data-equipment]')]; const mobileChoice = document.createElement('select'); mobileChoice.className = 'sizing-mobile-choice'; mobileChoice.setAttribute('aria-labelledby', 'sizing-select-title'); for (const button of choices) { mobileChoice.add(new Option(button.querySelector('strong').textContent.trim(), button.dataset.equipment)); } root.querySelector('.sizing-choices').before(mobileChoice); mobileChoice.addEventListener('change', () => selectEquipment(mobileChoice.value)); const languageLink = document.querySelector('a.alm-language-switch'); const tankMode = root.querySelector('form[data-calculator="tanks"] select[name="mode"]'); const flowUnits = ['m³/h', 'L/s', 'GPM', 'L/min', 'm³/day']; const units = { flow: flowUnits, heater: ['L', 'm³', 'US gal', 'Imp gal'], ionizer: ['m³/h', 'L/s', 'L/min', 'GPM'], }; const format = new Intl.NumberFormat('en', {maximumFractionDigits: 2}); const num = value => value !== 0 && Math.abs(value) < 0.001 ? value.toPrecision(3) : format.format(value); const mmPerInch = 25.4; const litresPerCubicFoot = 28.316846592; const squareMetresPerSquareFoot = 0.09290304; const kilogramsPerPound = 0.45359237; const kilogramsPerGrain = 0.00006479891; const dual = (metric, catalogue) => metric + ' (' + catalogue + ')'; // Nominal pipe connections use DN designations instead of physical diameters. const nominalPipeSizes = new Map([[0.5, 15], [0.75, 20], [1, 25], [1.25, 32], [1.5, 40], [2, 50], [2.5, 65], [3, 80], [4, 100], [5, 125], [6, 150], [8, 200], [10, 250], [12, 300]]); const precise = value => new Intl.NumberFormat('en', {maximumFractionDigits: 3}).format(value); function quantityFormats(localized) { const unitName = unit => localized ? wording(unit) : unit; const measure = (value, unit, format = num) => format(value) + ' ' + unitName(unit); // Keep engineering sequences in length/width/height order in RTL sentences and exported sheets. const sequence = text => localized ? '\u2066' + text + '\u2069' : text; const dimensions = values => sequence(values.map(precise).join(' × ')) + ' ' + unitName('m'); const flow = gpm => dual(measure(gpm / gpmPerM3h, 'm³/h'), measure(gpm, 'GPM')); const volume = cubicFeet => dual(measure(cubicFeet * litresPerCubicFoot, 'L'), measure(cubicFeet, 'ft³')); const loading = rate => dual(measure(rate / gpmPerM3h / squareMetresPerSquareFoot, 'm³/h/m²'), measure(rate, 'GPM/ft²')); const vesselDimensions = (diameter, height) => dual( sequence('Ø' + num(diameter * mmPerInch) + ' × ' + num(height * mmPerInch)) + ' ' + unitName('mm'), sequence('Ø' + num(diameter) + ' × ' + num(height)) + ' ' + unitName('in') ); const pipeSize = inches => { const dn = nominalPipeSizes.get(inches); return dn ? dual('DN ' + dn, measure(inches, 'in')) : measure(inches, 'in'); }; const pair = (first, second, unit, format = num) => sequence(format(first) + ' / ' + format(second)) + ' ' + unitName(unit); const range = (low, high, unit) => sequence(num(low) + '–' + num(high)) + ' ' + unitName(unit); return {measure, dimensions, flow, volume, loading, vesselDimensions, pipeSize, pair, range}; } const calculators = { filters: { size: sizeFilters, empty: 'No listed filter matches this combination of flow, material and filter count. Check the flow unit and advanced settings, or ask our team to size a different arrangement.', card(c, index, inputs, arabicCard = false) { const {measure, flow, vesselDimensions, loading, volume, pipeSize} = quantityFormats(arabicCard); const count = `${c.duty} operating ${c.duty === 1 ? 'filter' : 'filters'}`; const totalFlow = measure(c.perVessel * c.duty / gpmPerM3h, 'm³/h'); const treatment = arabicCard ? wording(c.duty === 1 ? 'One filter handles your total flow of {flow}.' : 'These filters share your total flow of {flow}.', {flow: totalFlow}) : ''; const backup = arabicCard && c.standby ? wording('Backup filters included: {count}.', {count: num(c.standby)}) : wording('No backup filter is included.'); const notes = [c.closest ? 'This option is closest to the comparison target of 5 GPM/ft².' : '', c.backwashReview ? 'Confirm cleaning flow against the selected media and site water conditions.' : ''].filter(Boolean); return { title: c.code, tag: index === 0 ? 'Compact option' : 'Alternative arrangement', headline: arabicCard ? wording('Operating filters: {count}', {count: num(c.duty)}) : count, explanation: arabicCard ? treatment + ' ' + backup : `${c.duty === 1 ? 'One filter handles' : 'These filters share'} your total flow of ${totalFlow}. ${c.standby ? `${c.standby} backup ${c.standby === 1 ? 'filter is' : 'filters are'} included.` : 'No backup filter is included.'}`, specs: [ ['Total flow treated', flow(c.perVessel * c.duty)], ['Size of each filter (diameter × height)', vesselDimensions(c.diameter_in, c.tank_height_in)], ['Flow through each filter', flow(c.perVessel)], ['Filter material', c.construction], ], technical: [ ['Operating / backup filters', `${c.duty} / ${c.standby}`], ['Service loading', loading(c.loading)], ['Cleaning flow (backwash) per filter', flow(c.backwash)], ['Control valve', c.control], ['Media per filter', c.media.map(m => `${m.name}: ${volume(m.volume)}`).join(' · ')], ['Nominal connection', pipeSize(c.pipe_size_in)], ], note: c.duty > 1 ? 'This arrangement spreads the flow across several filters. Allow space and connections for every unit.' : 'This arrangement uses one operating filter. Compare alternatives if you need a different filter size or configuration.', technicalNote: (arabicCard ? notes.map(note => wording(note)) : notes).join(' '), }; }, }, softeners: { size: sizeSofteners, empty: 'No listed softener meets this combination of flow and softening capacity. Check your flow unit, daily water use and hardness unit. Our team can review larger or different arrangements.', card(c, index, inputs, arabicCard = false) { const {flow, measure, vesselDimensions, pair, volume} = quantityFormats(arabicCard); return { title: c.code, tag: index === 0 ? 'Matching option' : 'Alternative arrangement', headline: c.count === 1 ? '1 softener vessel' : '2 softener vessels', explanation: c.count === 1 ? 'One vessel treats your water. Service pauses while it regenerates (cleans).' : c.paired ? 'One vessel operates and one is available as backup. Each is sized for the full operating flow.' : 'Two vessels alternate service. Each is sized for the full operating flow.', specs: [ ['Rated operating flow', flow(c.continuous_gpm)], ['Estimated time between cleaning cycles', measure(c.regenerationDays, 'days')], ['Size of each vessel (diameter × height)', vesselDimensions(c.tank_diameter_in, c.tank_height_in)], ['Salt per cleaning cycle', measure(c.saltPerRegen * kilogramsPerPound, 'kg')], ], technical: [ ['Rated continuous / peak flow', dual(pair(c.continuous_gpm / gpmPerM3h, c.peak_gpm / gpmPerM3h, 'm³/h'), pair(c.continuous_gpm, c.peak_gpm, 'GPM'))], ['Softening capacity / required per vessel', dual(pair(c.capacity * kilogramsPerGrain, c.required * kilogramsPerGrain, 'kg CaCO₃'), pair(c.capacity, c.required, 'grains'))], ['Resin per vessel', volume(c.resin_per_vessel_ft3)], ['Salt per regeneration', dual(measure(c.saltPerRegen * kilogramsPerPound, 'kg'), measure(c.saltPerRegen, 'lb'))], ['Cleaning flow (backwash) per vessel', flow(c.backwash_gpm)], ], note: 'The time between cleaning cycles is a capacity-based estimate. Our team can confirm the operating schedule for your application.', }; }, }, tanks: { size: sizeTanks, empty: 'Check your tank dimensions and water-level allowances, or ask our team for help.', card(c, index, inputs, arabicCard = false) { const {dimensions, measure, pair} = quantityFormats(arabicCard); const size = dimensions([c.length, c.width, c.height]); const litres = precise(c.usable * 1000); const byVolume = inputs.mode === 'volume'; const alternativeTag = c.length === c.width ? 'Square option (L × W × H)' : 'Alternative dimensions (L × W × H)'; return { title: arabicCard ? wording('GRP tank · {dimensions}', {dimensions: size}) : `GRP tank · ${size}`, tag: byVolume ? (index === 0 ? 'Closest capacity match (L × W × H)' : alternativeTag) : 'Effective water volume', headline: byVolume ? size : measure(c.usable, 'm³', precise), headlineIsTitle: byVolume, explanation: arabicCard ? wording('{litres} litres available between your highest and lowest operating water levels.', {litres}) : `${litres} litres available between your highest and lowest operating water levels.`, warning: !c.fits ? 'This tank needs more installation space than the room dimensions you entered.' : '', specs: [ ...(byVolume ? [ ['Target effective water volume', measure(c.required, 'm³', precise)], ['Effective water volume', measure(c.usable, 'm³', precise)], ] : []), ['Total tank capacity (nominal)', dual(measure(c.gross, 'm³', precise), measure(c.gross * 1000, 'L', precise))], ['Usable water depth', measure(c.depth, 'm', precise)], ], technical: [ ['Minimum installation space (L × W × H)', dimensions(c.installation)], ['Minimum foundation footprint (L × W)', dimensions([c.length + 0.4, c.width + 0.4])], ['Space above water / low-level allowance', pair(inputs.freeboard, inputs.lowLevel, 'm', precise)], ['Foundation + base frame', measure(inputs.base, 'm')], ], technicalTitle: 'Installation and capacity details', technicalNote: 'Effective water volume = internal length × internal width × usable water depth. Usable depth equals tank height minus headroom and the water left in the tank.', }; }, status(matches, inputs) { if (!matches[0].fits) return 'Capacity calculated. Please review the installation-space warning below.'; const checkedSpace = ['roomLength', 'roomWidth', 'roomHeight'].some(key => inputs[key] !== null); if (inputs.mode === 'volume') { return checkedSpace ? 'These dimensions meet your target and fit the installation limits you entered.' : 'These dimensions meet your target. Enter your available installation space to check the fit.'; } return checkedSpace ? 'Your tank capacity is below. The installation fits the room dimensions you entered.' : 'Your tank capacity is below. Installation space has not been checked.'; }, }, heaters: { size: sizeHeaters, empty: 'Your storage requirement exceeds the listed heater sizes. Check the volume and unit, or ask our team about a different arrangement.', card(c, index, inputs, arabicCard = false) { const {measure} = quantityFormats(arabicCard); return { title: c.model, tag: 'Smallest listed storage match', headline: measure(c.litres, 'L'), explanation: 'Rated hot-water storage capacity.', specs: [['Electrical power', measure(c.kw, 'kW')], ['Installation orientation', c.type]], technical: [['Catalogue capacity', arabicCard ? c.capacity.replace('Gallons', wording('US gal')) : c.capacity.replace('Gallons', 'US gal')]], note: 'This is a storage match. Heating recovery time, peak demand and electrical supply still need to suit your project.', }; }, }, ionizers: { size: sizeIonizers, empty: 'No published operating range covers this flow. Check the flow unit or ask our team to review your application.', card(c, index, inputs, arabicCard = false) { const {measure, range, pipeSize} = quantityFormats(arabicCard); const band = c.bands[0]; const sharedSpecs = c.bands.every(row => row.pipe_size_in === band.pipe_size_in && row.electrode_weight_kg === band.electrode_weight_kg); const specs = [['Your flow', `${measure(c.lps * 3.6, 'm³/h')} (${measure(c.lps, 'L/s')})`]]; const technical = []; for (const row of c.bands) { technical.push(['Operating range', range(row.min_flow_lps, row.max_flow_lps, 'L/s')]); if (!sharedSpecs) technical.push(['Pipe connection', pipeSize(row.pipe_size_in)], ['Electrode weight', measure(row.electrode_weight_kg, 'kg')]); } if (sharedSpecs) { specs.push(['Pipe connection', pipeSize(band.pipe_size_in)]); technical.push(['Electrode weight', measure(band.electrode_weight_kg, 'kg')]); } return { title: c.model, tag: 'Flow-range match', headline: c.bands.length === 1 ? range(band.min_flow_lps * 3.6, band.max_flow_lps * 3.6, 'm³/h') : measure(c.lps * 3.6, 'm³/h'), explanation: c.bands.length === 1 ? 'Model operating range. Your entered flow is within this range.' : 'Your flow matches multiple published operating ranges for this model. See the specifications below.', specs, technical, note: 'A flow match does not confirm treatment suitability. Our team will review your water quality and application.', }; }, }, }; function element(tag, value, className) { const node = document.createElement(tag); if (value) node.textContent = wording(value); if (className) node.className = className; return node; } function specificationList(specs) { const list = element('dl'); for (const [name, value] of specs) { const item = element('div'); const detail = element('dd', value); if (arabic) detail.dir = 'auto'; item.append(element('dt', name), detail); list.append(item); } return list; } function requirementsSummary(form, forEnglishSheet = false) { return [...form.elements].filter(field => field.name && !field.disabled && field.type !== 'hidden' && (field.type !== 'checkbox' || field.checked) && field.value !== '').map(field => { if (forEnglishSheet) { const label = form.dataset.calculator === 'tanks' && field.name === 'volume' ? 'Target effective water volume (m³)' : sizingEnglishFields[field.name] || field.name; const selected = field.hasAttribute('data-sizing-number') ? canonicalNumber(field.value) : sizingEnglishOptions[field.name]?.[field.value] || field.value; return [label, selected]; } const labelNode = field.closest('label'); const name = labelNode ? [...labelNode.childNodes].filter(node => node.nodeType === 3).map(node => node.textContent).join(' ').trim() || field.name : field.name; if (field.type === 'checkbox') return [wording('Filter medium'), name]; if (field.hasAttribute('data-sizing-number')) return [name, canonicalNumber(field.value)]; const value = field.tagName === 'SELECT' ? field.selectedOptions[0].textContent : field.value; return [name, value]; }); } function displayCard(result, requirements, calculatorName, englishSheet) { const {title, tag, headline, headlineIsTitle, explanation, specs, technical = [], technicalTitle = 'Technical details', note, technicalNote, warning} = result; const card = element('article', null, 'sizing-option'); const answer = element(headlineIsTitle ? 'h4' : 'p', headline, 'sizing-answer'); if (headlineIsTitle) answer.dir = 'ltr'; card.append(element('p', tag, 'sizing-tag'), answer, element('p', explanation, 'sizing-answer-explanation')); if (!headlineIsTitle) card.append(element('h4', title)); if (warning) card.append(element('p', warning, 'sizing-warning')); card.append(specificationList(specs)); if (note) card.append(element('p', note, 'sizing-note')); if (technical.length) { const details = element('details', null, 'sizing-technical'); details.append(element('summary', technicalTitle), specificationList(technical)); if (technicalNote) details.append(element('p', technicalNote)); card.append(details); } const summary = [...specs, ...technical].map(([name, value]) => `${wording(name)}: ${wording(value)}`); const resultText = [title, `${wording(tag)}: ${wording(headline)}`, wording(explanation), ...summary, wording(warning), wording(note), wording(technicalNote)].filter(Boolean); const requirementLines = requirements.map(([name, value]) => `${name}: ${value}`); const selection = [wording('AlMaymanah · Preliminary sizing'), '', wording('Your requirements'), ...requirementLines, '', wording('Calculated result'), ...resultText].join('\n'); const contact = visitor ? Object.entries(visitor).filter(([, value]) => value).map(([key,value]) => `${wording(key[0].toUpperCase() + key.slice(1))}: ${value}`) : []; const body = [wording('Hello AlMaymanah, please review my sizing enquiry.'), '', selection, '', ...contact].join('\n'); const actions = element('div', null, 'sizing-result-actions'); const enquiry = element('a', 'Email this result ↗', 'link'); enquiry.href = 'mailto:' + salesEmail + '?subject=' + encodeURIComponent(wording('Equipment sizing enquiry: {title}', {title})) + '&body=' + encodeURIComponent(body); const copy = element('button', 'Copy summary', 'link'); copy.type = 'button'; copy.setAttribute('aria-label', wording('Copy sizing summary for {title}', {title})); const feedback = element('p', '', 'sizing-copy-status'); feedback.setAttribute('role', 'status'); const download = element('button', 'Download technical sheet (PDF)', 'sizing-sheet-download'); download.type = 'button'; download.addEventListener('click', async () => { download.disabled = true; feedback.textContent = wording('Preparing your technical sheet…'); try { const sheet = englishSheet || {result, requirements, calculatorName}; await downloadTechnicalSheet({technical: [], technicalTitle: 'Technical details', ...sheet.result}, sheet.requirements, sheet.calculatorName, salesEmail, englishWording); feedback.textContent = wording('Your PDF download has started.'); } catch { feedback.textContent = wording('The technical sheet could not be downloaded. Please try again.'); } finally { download.disabled = false; } }); copy.addEventListener('click', async () => { try { await navigator.clipboard.writeText(selection); feedback.textContent = wording('Summary copied.'); } catch { feedback.textContent = wording('Select and copy the summary below.'); let fallback = card.querySelector('.sizing-copy-fallback'); if (!fallback) { fallback = element('textarea', null, 'sizing-copy-fallback'); fallback.readOnly = true; fallback.setAttribute('aria-label', wording('Sizing summary for {title}', {title})); card.append(fallback); } fallback.value = selection; fallback.focus(); fallback.select(); } }); if (arabic) { const print = element('button', 'Print or save the Arabic technical sheet (PDF)', 'sizing-sheet-download'); print.type = 'button'; print.addEventListener('click', () => printArabicTechnicalSheet(result, requirements, calculatorName, salesEmail, wording)); actions.append(print); } actions.append(download, enquiry, copy); card.append(actions, element('p', 'Email opens a draft with this result and any contact details you added.', 'sizing-help'), feedback); return card; } function revealResults() { resultPanel.focus({preventScroll: true}); resultPanel.scrollIntoView({block: 'start', behavior: 'auto'}); } function clearResults(message = 'Enter your requirements to see matching options.') { results.replaceChildren(); emailDetails.hidden = true; access.hidden = true; editDetails.setAttribute('aria-expanded', 'false'); emptyState.hidden = false; resultPanel.classList.remove("has-results"); status.textContent = wording(message); } function selectEquipment(name) { for (const form of forms) form.hidden = form.dataset.calculator !== name; for (const button of choices) button.setAttribute('aria-pressed', String(button.dataset.equipment === name)); mobileChoice.value = name; document.getElementById('sizing-results-title').textContent = wording(name === 'tanks' ? tankResultsTitle() : name === 'ionizers' ? 'Matching ionizer models' : 'Your equipment options'); clearResults(); draft.equipment = name; store(draftKey, draft); const selected = forms.find(form => form.dataset.calculator === name); if (draft.forms[name]?.calculated && selected.checkValidity()) calculate(selected, false); const url = new URL(location.href); url.searchParams.set('equipment', name); history.replaceState(history.state, '', url); if (languageLink) { const translated = new URL(languageLink.href); translated.searchParams.set('equipment', name); languageLink.href = translated.href; } } // Native number controls discard Arabic digits before an input listener can read them. function canonicalNumber(raw) { const value = raw.trim().replace(/[٠-٩۰-۹]/g, digit => String(digit.charCodeAt(0) - (digit <= '٩' ? 0x660 : 0x6f0))); if (!value) return ''; if (!/^[+-]?(?:(?:[0-9]{1,3}(?:[٬,][0-9]{3})+|[0-9]+)(?:[.٫][0-9]*)?|[.٫][0-9]+)(?:[eE][+-]?[0-9]+)?$/.test(value)) return null; const parsed = Number(value.replace(/[٬,]/g, '').replace('٫', '.')); return Number.isFinite(parsed) ? String(parsed) : null; } function validateArabicField(field) { if (field.matches('select[required]')) { field.setCustomValidity(field.value ? '' : wording('Select an option.')); return; } if (!field.hasAttribute('data-sizing-number')) return; const value = canonicalNumber(field.value); let message = ''; if (value === null) message = wording('Enter a valid number, for example 10.5.'); else if (value === '' && field.required) message = wording('Enter a value in this field.'); else if (value !== '') { // The browser applies the same min, max and step rules used by the English controls. const probe = document.createElement('input'); probe.type = 'number'; for (const key of ['min', 'max', 'step', 'value']) { if (field.hasAttribute(key)) probe.setAttribute(key, field.getAttribute(key)); } probe.value = value; if (probe.validity.rangeUnderflow) message = wording('Enter a value of at least {limit}.', {limit: field.min}); else if (probe.validity.rangeOverflow) message = wording('Enter a value up to {limit}.', {limit: field.max}); else if (probe.validity.stepMismatch) message = wording('Use increments of {step}.', {step: field.step}); } field.setCustomValidity(message); } function valuesFrom(form) { const values = Object.fromEntries(new FormData(form)); for (const input of form.querySelectorAll(':is(input[type="number"],input[data-sizing-number]):enabled')) { values[input.name] = input.value === '' ? null : input.hasAttribute('data-sizing-number') ? Number(canonicalNumber(input.value)) : input.valueAsNumber; } if (form.dataset.calculator === 'tanks' && values.mode === 'volume') { values.height = values.targetHeight; values.unit = 'm³'; } values.media = new FormData(form).getAll('media'); return values; } function tankResultsTitle() { return tankMode?.value === 'volume' ? 'Suggested tank dimensions' : 'Your tank capacity'; } function updateTankMode() { for (const group of tankMode.form.querySelectorAll('[data-tank-mode]')) { group.hidden = group.dataset.tankMode !== tankMode.value; for (const field of group.querySelectorAll('input, select')) field.disabled = group.hidden; } document.getElementById('sizing-results-title').textContent = wording(tankResultsTitle()); } if (tankMode) { tankMode.addEventListener('change', updateTankMode); updateTankMode(); } for (const select of root.querySelectorAll('[data-units]')) { select.replaceChildren(...units[select.dataset.units].map(unit => new Option(arabic ? wording(unit) : unit, unit))); } function remember(form, calculated) { const fields = {}; for (const field of form.elements) { if (!field.name) continue; if (field.type === 'checkbox' || field.type === 'radio') { if (!fields[field.name]) fields[field.name] = []; if (field.checked) fields[field.name].push(field.value); } else if (field.hasAttribute('data-sizing-number') && field.validity.valid) { fields[field.name] = canonicalNumber(field.value); } else fields[field.name] = field.value; } draft.forms[form.dataset.calculator] = {fields, calculated}; store(draftKey, draft); } function calculate(form, moveFocus = true) { const calculator = calculators[form.dataset.calculator]; try { const inputs = valuesFrom(form); const matches = calculator.size(inputs); if (!matches.length) { clearResults(sizingFailureReason(form.dataset.calculator, inputs) || calculator.empty); emptyState.hidden = true; const help = element('a', 'Get help with this requirement →', 'link sizing-no-match'); const contact = new URL('contact.html', document.baseURI); if (arabic) contact.searchParams.set('lang', 'ar'); help.href = contact.href; results.append(help); if (moveFocus) revealResults(); return; } emptyState.hidden = true; emailDetails.hidden = false; resultPanel.classList.add("has-results"); const equipment = form.dataset.calculator; const requirements = requirementsSummary(form); const englishRequirements = arabic ? requirementsSummary(form, true) : null; const choice = choices.find(button => button.dataset.equipment === equipment); const calculatorName = choice.querySelector('strong').textContent.trim(); results.replaceChildren(...matches.map((match, index) => { const englishSheet = arabic ? { result: calculator.card(match, index, inputs), requirements: englishRequirements, calculatorName: sizingEnglishTitles[equipment], } : null; return displayCard(calculator.card(match, index, inputs, arabic), requirements, calculatorName, englishSheet); })); status.textContent = calculator.status ? wording(calculator.status(matches, inputs)) : arabic ? wording('Catalogue options matching your requirements: {count}.', {count: num(matches.length)}) : `${matches.length} ${matches.length === 1 ? 'catalogue option matches' : 'catalogue options match'} your requirements.`; if (moveFocus) revealResults(); } catch (error) { clearResults(error.message); emptyState.hidden = true; if (moveFocus) revealResults(); } } for (const button of choices) button.addEventListener('click', () => selectEquipment(button.dataset.equipment)); for (const form of forms) { const fields = draft.forms[form.dataset.calculator]?.fields || {}; for (const field of form.elements) { if (!field.name || !Object.hasOwn(fields, field.name)) continue; const value = fields[field.name]; if (field.type === 'checkbox' || field.type === 'radio') field.checked = Array.isArray(value) && value.includes(field.value); else if (typeof value === 'string') field.value = value; } if (arabic) { for (const field of form.querySelectorAll('input[type="number"]')) { field.dataset.sizingNumber = ''; field.inputMode = field.step === '1' ? 'numeric' : 'decimal'; field.type = 'text'; field.dir = 'ltr'; } for (const field of form.querySelectorAll('[data-sizing-number], select[required]')) validateArabicField(field); } form.addEventListener('input', event => { if (arabic) validateArabicField(event.target); remember(form, false); clearResults('Calculate again to see results for your current inputs.'); }); form.addEventListener('invalid', event => { const details = event.target.closest('details'); if (details) details.open = true; }, true); form.addEventListener('submit', event => { event.preventDefault(); remember(form, true); calculate(form); }); } if (tankMode) updateTankMode(); const requested = new URLSearchParams(location.search).get('equipment') || draft.equipment; selectEquipment(choices.some(button => button.dataset.equipment === requested) ? requested : 'filters');