/* ════════════════════════════════════════════════════════════════ NSQHS — National Safety and Quality Health Service (NSQHS) Standards ════════════════════════════════════════════════════════════════ */ (function () { 'use strict'; var PC = window.portalContext || {}; var config = { fee: parseFloat(PC.nsqhsFee) || 0, surchargeRate: parseFloat(PC.nsqhsSurchargeRate) || 0.01927, gstRate: parseFloat(PC.nsqhsGSTRate) || 0.10, contactTypeId: PC.contactTypeId || '', businessId: PC.businessId || '' }; var TOTAL_STEPS = 6; var currentStep = 1; var isBusy = false; var sigCtx = null; var sigDrawing = false; var leadId = null; var leadRef = null; var evidenceId = null; var SK = { leadId: 'nsqhs_registration_lead_id', leadRef: 'nsqhs_registration_lead_ref', evidence: 'nsqhs_registration_evidence_id', inProgress: 'nsqhs_payment_in_progress' }; /* SPINNER */ function injectSpinner() { if (document.getElementById('nsqhs-spinner-overlay')) return; var style = document.createElement('style'); style.textContent = '@keyframes nsqhs-spin{to{transform:rotate(360deg)}}#nsqhs-spinner-overlay{display:none;position:fixed;inset:0;background:rgba(29,45,68,.65);z-index:99999;align-items:center;justify-content:center;flex-direction:column;gap:18px;}'; document.head.appendChild(style); var o = document.createElement('div'); o.id = 'nsqhs-spinner-overlay'; o.innerHTML = '
Please wait\u2026
'; document.body.appendChild(o); } function setBusy(busy, msg) { isBusy = busy; var o = document.getElementById('nsqhs-spinner-overlay'); var m = document.getElementById('nsqhs-spinner-msg'); if (o) o.style.display = busy ? 'flex' : 'none'; if (m && msg) m.textContent = msg; if (m && !busy) m.textContent = 'Please wait\u2026'; document.querySelectorAll('button').forEach(function (btn) { if (busy) { btn.setAttribute('data-wd', btn.disabled ? '1' : '0'); btn.disabled = true; } else { btn.disabled = btn.getAttribute('data-wd') === '1'; } }); } /* CSRF */ function waitForToken() { return new Promise(function (resolve, reject) { var pc = window.portalContext || {}; var c = pc.csrfToken || pc.requestVerificationToken; if (c && c.length > 20) { resolve(c); return; } var d = document.querySelector('input[name="__RequestVerificationToken"]'); if (d && d.value) { resolve(d.value); return; } var e = document.getElementById('csrf-token-value'); if (e && e.value && e.value.length > 20) { resolve(e.value); return; } var n = 0; var poll = setInterval(function () { n++; var pv = (window.portalContext || {}).csrfToken; if (pv && pv.length > 20) { clearInterval(poll); resolve(pv); return; } var el = document.getElementById('csrf-token-value'); if (el && el.value && el.value.length > 20) { clearInterval(poll); resolve(el.value); return; } if (n >= 30) { clearInterval(poll); fetch('/Account/Login', { credentials: 'same-origin', headers: { 'Accept': 'text/html' } }) .then(function (r) { return r.text(); }) .then(function (html) { var m = html.match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/); if (!m) m = html.match(/value="([^"]{40,})"[^>]*name="__RequestVerificationToken"/); if (m && m[1]) resolve(m[1]); else reject(new Error('CSRF not found')); }).catch(reject); } }, 150); }); } /* Dataverse Post Request */ function extractId(data, resp) { if (data && typeof data === 'object') { /* accountid added so account GUIDs are captured; ongc_siteid for site records */ var b = data.accountid || data.leadid || data.contactid || data.ongc_paymentevidenceid || data.ongc_siteid; if (!b && data['@odata.id']) { var mo = data['@odata.id'].match(/\(([0-9a-f-]{36})\)/i); if (mo) b = mo[1]; } if (b) return b; } var hv = resp && typeof resp.headers.get === 'function' ? (resp.headers.get('OData-EntityId') || '') : ''; var m = hv.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i); return m ? m[0] : null; } async function dataversePost(entitySet, payload) { var token = await waitForToken(); var resp = await fetch('/_api/' + entitySet, { method: 'POST', headers: { 'Content-Type': 'application/json', '__RequestVerificationToken': token, 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Prefer': 'return=representation' }, body: JSON.stringify(payload) }); if (!resp.ok) { var em = 'API error ' + resp.status; try { var ej = await resp.json(); em = (ej && ej.error && ej.error.message) || em; } catch (e) { } throw new Error(em); } var data = {}; try { data = await resp.json(); } catch (e) { } return { id: extractId(data, resp), data: data }; } async function fetchLeadRef(lid) { try { var token = await waitForToken(); var r = await fetch('/_api/leads(' + lid + ')?$select=ongc_leadrefid,ongc_clientid', { method: 'GET', headers: { '__RequestVerificationToken': token, 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Accept': 'application/json' } }); if (!r.ok) return null; var d = await r.json(); return (d && (d.ongc_leadrefid || d.ongc_clientid)) || null; } catch (e) { return null; } } /* SESSION */ function clearSession() { [SK.leadId, SK.leadRef, SK.evidence, SK.inProgress].forEach(function (k) { try { sessionStorage.removeItem(k); } catch (e) { } }); leadId = null; leadRef = null; evidenceId = null; } function saveSession() { try { if (leadId) sessionStorage.setItem(SK.leadId, leadId); if (leadRef) sessionStorage.setItem(SK.leadRef, leadRef); if (evidenceId) sessionStorage.setItem(SK.evidence, evidenceId); } catch (e) { } } /* HELPERS */ function round2(n) { return Math.round(n * 100) / 100; } function gVal(id) { var e = document.getElementById(id); return e ? e.value.trim() : ''; } function radioVal(name) { var e = document.querySelector('input[name="' + name + '"]:checked'); return e ? e.value : ''; } function getChecked(sel) { return Array.prototype.slice.call(document.querySelectorAll(sel + ':checked')).map(function (e) { return e.value; }); } function strip(p) { Object.keys(p).forEach(function (k) { if (p[k] === '' || p[k] === null || p[k] === undefined) delete p[k]; }); return p; } /* FEE */ function calcFees() { var base = config.fee, sur = round2(base * config.surchargeRate), gst = round2((base + sur) * config.gstRate); return { base: base, surcharge: sur, gst: gst, total: round2(base + sur + gst) }; } function renderFee() { var el = document.getElementById('nsqhsFeeAmount'); if (el) el.textContent = config.fee > 0 ? config.fee.toLocaleString('en-AU', { minimumFractionDigits: 2 }) : 'TBC'; } /* STEP NAVIGATION */ function showStep(step) { if (isBusy && typeof step === 'number') return; currentStep = step; document.querySelectorAll('.form-step').forEach(function (el) { el.classList.remove('active'); }); var target = document.querySelector('.form-step[data-step="' + step + '"]'); if (target) { target.classList.add('active'); window.scrollTo({ top: 0, behavior: 'smooth' }); } var lbl = document.getElementById('currentStepLabel'); if (lbl) lbl.textContent = 'Step ' + step + ' of ' + TOTAL_STEPS; if (step === 6) { /* initSig(); — signature commented out */ renderFee(); } } /* VALIDATION */ function showErr(id, msg) { var el = document.getElementById(id); if (el) { el.textContent = msg || ''; el.style.display = msg ? 'block' : 'none'; } } function clearErr(id) { showErr(id, ''); } function validateStep(step) { var ok = true; function req(id, errId, label) { var el = document.getElementById(id); var val = el ? (el.type === 'checkbox' ? el.checked : (el.value !== undefined ? el.value.trim() : '')) : false; var valid = el && (el.type === 'checkbox' ? el.checked : el.value.trim() !== ''); showErr(errId, valid ? '' : (label || 'This field is required.')); return valid; } function reqRadio(name, errId) { var checked = document.querySelector('input[name="' + name + '"]:checked'); showErr(errId, checked ? '' : 'This field is required.'); return !!checked; } if (step === 1) { ok = req('serviceName', 'err_serviceName') && ok; /* preferred */ var fOk = gVal('preferredFirstName') !== ''; showErr('err_preferredFirstName', fOk ? '' : 'Required.'); if (!fOk) ok = false; var lOk = gVal('preferredLastName') !== ''; showErr('err_preferredLastName', lOk ? '' : 'Required.'); if (!lOk) ok = false; var phOk = gVal('preferredPhone') !== ''; showErr('err_preferredPhone', phOk ? '' : 'Required.'); if (!phOk) ok = false; var emOk = gVal('preferredEmail') !== '' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(gVal('preferredEmail')); showErr('err_preferredEmail', emOk ? '' : 'Please enter a valid email.'); if (!emOk) ok = false; /* alternate */ var afOk = gVal('alternateFirstName') !== ''; showErr('err_alternateFirstName', afOk ? '' : 'Required.'); if (!afOk) ok = false; var alOk = gVal('alternateLastName') !== ''; showErr('err_alternateLastName', alOk ? '' : 'Required.'); if (!alOk) ok = false; var aphOk = gVal('alternatePhone') !== ''; showErr('err_alternatePhone', aphOk ? '' : 'Required.'); if (!aphOk) ok = false; var aemOk = gVal('alternateEmail') !== '' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(gVal('alternateEmail')); showErr('err_alternateEmail', aemOk ? '' : 'Please enter a valid email.'); if (!aemOk) ok = false; ok = req('businessName', 'err_businessName') && ok; ok = req('abn', 'err_abn') && ok; /* Street address */ var a1 = document.getElementById('streetAddress1'), sbEl = document.getElementById('suburb'), stEl = document.getElementById('state'), pcEl = document.getElementById('postcode'); var addrOk = (a1 && a1.value.trim() !== '') && (sbEl && sbEl.value.trim() !== '') && (stEl && stEl.value !== '') && (pcEl && pcEl.value.trim() !== ''); showErr('err_streetAddress', addrOk ? '' : 'Street address, suburb, state and postcode are required.'); if (!addrOk) ok = false; } if (step === 2) { ok = reqRadio('facilitySector', 'err_facilitySector') && ok; var streamOk = document.querySelectorAll('.stream-cb:checked').length > 0; showErr('err_serviceStream', streamOk ? '' : 'Please select at least one service stream.'); if (!streamOk) ok = false; var streamOtherCb = document.querySelector('.stream-other-cb'); if (streamOtherCb && streamOtherCb.checked) { var soOk = gVal('serviceStreamOther') !== ''; showErr('err_serviceStreamOther', soOk ? '' : 'Required.'); if (!soOk) ok = false; } ok = reqRadio('governance', 'err_governance') && ok; ok = reqRadio('corporateEntity', 'err_corporateEntity') && ok; if (radioVal('corporateEntity') === 'Yes') { var cnOk = gVal('corporateName') !== ''; showErr('err_corporateName', cnOk ? '' : 'Required.'); if (!cnOk) ok = false; } ok = reqRadio('currentlyAccredited', 'err_currentlyAccredited') && ok; ok = req('accreditationExpiryDate', 'err_accreditationExpiryDate') && ok; } if (step === 4) { var nsOk = gVal('numSites') !== ''; showErr('err_numSites', nsOk ? '' : 'This field is required.'); if (!nsOk) ok = false; var sc = parseInt(gVal('numSites')) || 0; for (var s = 1; s <= sc; s++) { var snOk = gVal('siteName_' + s) !== ''; showErr('err_siteName_' + s, snOk ? '' : 'Site name is required.'); if (!snOk) ok = false; var fteOk = gVal('siteFte_' + s) !== ''; showErr('err_siteFte_' + s, fteOk ? '' : 'FTE is required.'); if (!fteOk) ok = false; if (s > 1) { var sfOk = document.querySelectorAll('.site-facility-cb-' + s + ':checked').length > 0; showErr('err_siteFacility_' + s, sfOk ? '' : 'Please select at least one facility type.'); if (!sfOk) ok = false; } } } if (step === 6) { var dcOk = document.getElementById('declarationCheck') && document.getElementById('declarationCheck').checked; showErr('err_declarationCheck', dcOk ? '' : 'This declaration is required.'); if (!dcOk) ok = false; var ccOk = document.getElementById('consentCheck') && document.getElementById('consentCheck').checked; showErr('err_consentCheck', ccOk ? '' : 'This consent is required.'); if (!ccOk) ok = false; ok = req('authRepName', 'err_authRepName') && ok; ok = req('authRepPosition', 'err_authRepPosition') && ok; /* Signature validation commented out — not required yet var sigEmpty = isSigEmpty(); showErr('err_signature', sigEmpty ? 'A signature is required.' : ''); if (sigEmpty) ok = false; */ } if (!ok) { var first = document.querySelector('.form-step.active .field-error:not(:empty)'); if (first) first.scrollIntoView({ behavior: 'smooth', block: 'center' }); } return ok; } /* CONDITIONALS */ window.nsqhs = { togglePostal: function () { var yes = document.getElementById('postalYes'); document.getElementById('postalAddressSection').classList.toggle('hidden', !(yes && yes.checked)); }, toggleStreamOther: function () { var cb = document.querySelector('.stream-other-cb'); document.getElementById('streamOtherWrap').classList.toggle('hidden', !(cb && cb.checked)); }, toggleCorporate: function () { document.getElementById('corporateNameWrap').classList.toggle('hidden', radioVal('corporateEntity') !== 'Yes'); }, toggleCurrentAccreditation: function () { document.getElementById('currentAccreditationWrap').classList.toggle('hidden', radioVal('currentlyAccredited') !== 'Yes'); }, toggleFrameworks: function () { var map = { fw_mps: 'fw_mps_section', fw_pchs: 'fw_pchs_section', fw_cosmetic: 'fw_cosmetic_section', fw_clinical: 'fw_clinical_section', fw_other: 'fw_other_section' }; Object.keys(map).forEach(function (cbId) { var cb = document.getElementById(cbId); var sec = document.getElementById(map[cbId]); if (sec) sec.classList.toggle('hidden', !(cb && cb.checked)); }); }, onSiteCountChange: function () { var v = gVal('numSites'); buildSiteSections(parseInt(v) || 0); document.getElementById('over10Advisory').classList.toggle('hidden', v !== 'over10'); }, clearSig: function () { var c = document.getElementById('nsqhsSigCanvas'); if (sigCtx && c) sigCtx.clearRect(0, 0, c.width, c.height); }, save: function () { alert('Your progress has been saved. Use the link sent to your registered email to resume.'); } }; /* SITE SECTIONS */ var FACILITY_TYPES = [ 'Hospital', 'Day procedure service', 'Ambulance and transport service', 'Bush nursing centre', 'Bush nursing hospital', 'Community health service', 'Corporate', 'Correctional service', 'Dental or oral health service', 'Drug and alcohol service', 'Mental health service', 'Primary health centre', 'Other', 'Aged care', 'Clinical trial site', 'Satellite hospital', 'Cosmetic surgery (for CS2.1 version - NSQCS Standards)' ]; function buildSiteSections(count) { var container = document.getElementById('siteSectionsContainer'); if (!container) return; Array.prototype.slice.call(container.querySelectorAll('.nsqhs-site-section')).forEach(function (el, i) { if (i >= count) el.remove(); }); for (var i = 1; i <= count; i++) { if (container.querySelector('[data-site="' + i + '"]')) continue; var sec = document.createElement('div'); sec.className = 'nsqhs-site-section'; sec.setAttribute('data-site', i); var ftCbs = ''; FACILITY_TYPES.forEach(function (ft) { ftCbs += ''; }); var facilityBlock = i > 1 ? '
' + ftCbs + '
' : ''; sec.innerHTML = '
Main/Site ' + i + (i === 1 ? ' (Main site)' : '') + ' Details
' + '
' + '' + '' + '
' + '
Main/Site ' + i + ' Address
' + '' + 'Street Address' + '' + 'Address Line 2' + '
' + '
Suburb
' + '
State' + '
' + '
' + '
' + '
Postcode
' + '
Country
' + '
' + '
' + '
' + '
' + '
' + facilityBlock; container.appendChild(sec); } } /* SIGNATURE Box */ function initSig() { var c = document.getElementById('nsqhsSigCanvas'); if (!c) return; var fresh = c.cloneNode(true); c.parentNode.replaceChild(fresh, c); c = fresh; c.width = c.parentElement.clientWidth || 680; c.height = 130; sigCtx = c.getContext('2d'); sigCtx.strokeStyle = '#1d2d44'; sigCtx.lineWidth = 2.2; sigCtx.lineCap = 'round'; sigCtx.lineJoin = 'round'; var ctx = sigCtx; function pos(e) { var r = c.getBoundingClientRect(); var pt = e.touches ? e.touches[0] : e; return { x: pt.clientX - r.left, y: pt.clientY - r.top }; } c.addEventListener('mousedown', function (e) { sigDrawing = true; ctx.beginPath(); var p = pos(e); ctx.moveTo(p.x, p.y); }); c.addEventListener('mousemove', function (e) { if (!sigDrawing) return; var p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); }); c.addEventListener('mouseup', function () { sigDrawing = false; }); c.addEventListener('mouseleave', function () { sigDrawing = false; }); c.addEventListener('touchstart', function (e) { e.preventDefault(); sigDrawing = true; ctx.beginPath(); var p = pos(e); ctx.moveTo(p.x, p.y); }, { passive: false }); c.addEventListener('touchmove', function (e) { e.preventDefault(); if (!sigDrawing) return; var p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); }, { passive: false }); c.addEventListener('touchend', function () { sigDrawing = false; }); } function isSigEmpty() { var c = document.getElementById('nsqhsSigCanvas'); if (!c || !sigCtx) return true; var d = sigCtx.getImageData(0, 0, c.width, c.height).data; for (var i = 3; i < d.length; i += 4) { if (d[i] > 0) return false; } return true; } /* COLLECT SITE DATA */ function collectSites() { var n = parseInt(gVal('numSites')) || 0, sites = []; for (var i = 1; i <= n; i++) { var fts = Array.prototype.slice.call(document.querySelectorAll('.site-facility-cb-' + i + ':checked')).map(function (e) { return e.value; }); sites.push({ name: gVal('siteName_' + i), addr1: gVal('siteAddr1_' + i), addr2: gVal('siteAddr2_' + i), suburb: gVal('siteSuburb_' + i), state: gVal('siteState_' + i), postcode: gVal('sitePostcode_' + i), fte: gVal('siteFte_' + i), beds: gVal('siteBeds_' + i), facilityTypes: fts }); } return sites; } /* PAYLOADS */ function buildLeadPayload(acctId) { function buildNsqhsWebResponseHtml() { var postalDiff = document.getElementById('postalYes') && document.getElementById('postalYes').checked; var sites = collectSites(); var now = new Date().toLocaleString('en-AU', { timeZone: 'Australia/Sydney', dateStyle: 'medium', timeStyle: 'short' }); var STATE_LABELS = { '107150000': 'ACT', '107150001': 'NSW', '107150002': 'NT', '107150003': 'QLD', '107150004': 'SA', '107150005': 'TAS', '107150006': 'VIC', '107150007': 'National' }; function stateLabel(v) { return STATE_LABELS[v] || v || '—'; } function row(label, value) { if (!value && value !== 0) value = '—'; return '' + '' + label + '' + '' + value + '' + ''; } function section(title) { return '' + title + ''; } var html = '
' + ''; /* Header */ html += ''; html += ''; /* 1. Contact Details */ html += section('1. Contact Details'); html += row('QIP Client ID', gVal('qipClientId')); html += row('Healthcare Service Name', gVal('serviceName')); html += row('Preferred Contact Name', (gVal('preferredFirstName') + ' ' + gVal('preferredLastName')).trim()); html += row('Preferred Email', gVal('preferredEmail')); html += row('Preferred Phone', gVal('preferredPhone')); html += row('Alternate Contact Name', (gVal('alternateFirstName') + ' ' + gVal('alternateLastName')).trim()); html += row('Alternate Email', gVal('alternateEmail')); html += row('Alternate Phone', gVal('alternatePhone')); html += row('Website', gVal('website')); html += row('Business / Trading Name', gVal('businessName')); html += row('ABN', gVal('abn')); html += row('ACN', gVal('acn')); var streetAddr = [gVal('streetAddress1'), gVal('streetAddress2'), gVal('suburb'), stateLabel(gVal('state')), gVal('postcode'), 'Australia'].filter(Boolean).join(', '); html += row('Street Address', streetAddr); if (postalDiff) { var postalAddr = [gVal('postalAddress1'), gVal('postalSuburb'), stateLabel(gVal('postalState')), gVal('postalPostcode'), 'Australia'].filter(Boolean).join(', '); html += row('Postal Address', postalAddr); } else { html += row('Postal Address', 'Same as street address'); } /* 2. Scope of Service */ html += section('2. Scope of Service'); html += row('Facility Sector', radioVal('facilitySector')); var streams = getChecked('.stream-cb'); var streamDisplay = streams.length ? streams.join(', ') : '—'; if (streams.indexOf('Other') !== -1 && gVal('serviceStreamOther')) streamDisplay += ' (' + gVal('serviceStreamOther') + ')'; html += row('Service Stream(s)', streamDisplay); html += row('Governance Structure', radioVal('governance')); html += row('Corporate Entity', radioVal('corporateEntity') === 'Yes' ? 'Yes — ' + gVal('corporateName') : radioVal('corporateEntity')); html += row('Currently Accredited', radioVal('currentlyAccredited')); if (radioVal('currentlyAccredited') === 'Yes') { html += row('Current Accreditation Provider', gVal('currentAccreditationProvider')); var accStds = getChecked('.accred-std-cb'); html += row('Accredited Standards', accStds.length ? accStds.join(', ') : '—'); html += row('Accreditation Expiry Date', gVal('accreditationExpiryDate')); html += row('Accreditation Other Info', gVal('accreditationOtherInfo')); } /* 3. Frameworks */ var fws = getChecked('.fw-cb'); if (fws.length) { html += section('3. Additional Frameworks'); html += row('Frameworks', fws.join(', ')); if (gVal('fwMpsSites')) html += row('MPS Sites', gVal('fwMpsSites')); if (gVal('fwPchsSites')) html += row('PCHS Sites', gVal('fwPchsSites')); if (gVal('fwCosmeticSites')) html += row('Cosmetic Surgery Sites', gVal('fwCosmeticSites')); if (gVal('fwClinicalTrials')) html += row('Clinical Trials', gVal('fwClinicalTrials')); if (gVal('fwOtherDetails')) html += row('Other Framework Details', gVal('fwOtherDetails')); } /* 4. Sites — each site gets its own numbered sub-header */ html += section('4. Service Locations (' + (sites.length || 0) + ' site(s))'); if (sites.length) { sites.forEach(function (s, i) { var num = i + 1; var siteName = s.name || ('Site ' + num); var siteAddr = [s.addr1, s.addr2, s.suburb, stateLabel(s.state), s.postcode].filter(Boolean).join(', ') || '—'; /* Per-site divider header */ html += '' + ''; html += row('Site Name', siteName); html += row('Address', siteAddr); html += row('Total FTE', s.fte || '—'); html += row('Total Beds', s.beds || '—'); if (s.facilityTypes && s.facilityTypes.length) { html += row('Facility Type(s)', s.facilityTypes.join(', ')); } /* Spacer between sites (skip after last) */ if (i < sites.length - 1) { html += ''; } }); } else { html += ''; } /* 5. Additional Information */ html += section('5. Additional Information'); html += row('Additional Operations', gVal('additionalOperations')); html += row('Additional Support Services', gVal('additionalSupportServices')); /* 6. Authorisation */ html += section('6. Authorisation'); html += row('Authorised Representative', gVal('authRepName')); html += row('Position', gVal('authRepPosition')); html += row('Declaration Accepted', document.getElementById('declarationCheck') && document.getElementById('declarationCheck').checked ? 'Yes' : 'No'); html += row('Consent to Disclosure', document.getElementById('consentCheck') && document.getElementById('consentCheck').checked ? 'Yes' : 'No'); html += '
' + 'NSQHS Registration — Scope of Service
' + 'Submitted: ' + now + '
' + '📍 Site ' + num + ' — ' + siteName + '
No sites entered.
'; return html; } var org = gVal('serviceName') || gVal('businessName'); var postalDiff = document.getElementById('postalYes') && document.getElementById('postalYes').checked; var p = strip({ subject: 'National Safety and Quality Health Service (NSQHS) Standards \u2013 ' + org, firstname: gVal('preferredFirstName'), lastname: gVal('preferredLastName') || org, emailaddress1: gVal('preferredEmail'), telephone1: gVal('preferredPhone'), companyname: org, websiteurl: gVal('website'), leadsourcecode: 8, address1_line1: gVal('streetAddress1'), address1_line2: gVal('streetAddress2'), address1_city: gVal('suburb'), address1_stateorprovince: gVal('state'), address1_postalcode: gVal('postcode'), address1_country: 'Australia', address2_line1: postalDiff ? gVal('postalAddress1') : '', address2_city: postalDiff ? gVal('postalSuburb') : '', address2_stateorprovince: postalDiff ? gVal('postalState') : '', address2_postalcode: postalDiff ? gVal('postalPostcode') : '', address2_country: postalDiff ? 'Australia' : '', ongc_enquirytype: 6, ongc_practicename: org, ongc_practiceabn: gVal('abn'), ongc_practicephone: gVal('preferredPhone'), ongc_clientid: gVal('qipClientId'), ongc_postalsameasstreet: !postalDiff, ongc_state: (function () { var m = { '107150000': 107150000, '107150001': 107150001, '107150002': 107150002, '107150003': 107150003, '107150004': 107150004, '107150005': 107150005, '107150006': 107150006, '107150007': 107150007 }; var v = gVal('state'); return v && m[v] ? m[v] : undefined; })(), ongc_webresponse: buildNsqhsWebResponseHtml() //description: JSON.stringify({ // qipClientId: gVal('qipClientId'), alternateFirst: gVal('alternateFirstName'), alternateLast: gVal('alternateLastName'), // alternatePhone: gVal('alternatePhone'), alternateEmail: gVal('alternateEmail'), // businessName: gVal('businessName'), acn: gVal('acn'), // facilitySector: radioVal('facilitySector'), // serviceStreams: getChecked('.stream-cb'), serviceStreamOther: gVal('serviceStreamOther'), // governance: radioVal('governance'), // corporateEntity: radioVal('corporateEntity'), corporateName: gVal('corporateName'), // currentlyAccredited: radioVal('currentlyAccredited'), // currentAccreditationProvider: gVal('currentAccreditationProvider'), // accreditedStandards: getChecked('.accred-std-cb'), // accreditationExpiryDate: gVal('accreditationExpiryDate'), // accreditationOtherInfo: gVal('accreditationOtherInfo'), // frameworks: getChecked('.fw-cb'), // fwMpsSites: gVal('fwMpsSites'), fwPchsSites: gVal('fwPchsSites'), fwCosmeticSites: gVal('fwCosmeticSites'), fwClinicalTrials: gVal('fwClinicalTrials'), fwOtherDetails: gVal('fwOtherDetails'), // numSites: gVal('numSites'), sites: collectSites(), // additionalOperations: gVal('additionalOperations'), additionalSupportServices: gVal('additionalSupportServices'), // authRepName: gVal('authRepName'), authRepPosition: gVal('authRepPosition') //}) }); debugger; if (config.businessId) p['ongc_Business@odata.bind'] = '/ongc_businesses(' + config.businessId + ')'; if (acctId) p['parentaccountid@odata.bind'] = '/accounts(' + acctId + ')'; return p; } function buildContactPayload(acctId) { /* companyname is lead-only; contacts link to account via parentcustomerid (customer lookup) */ var p = { firstname: gVal('preferredFirstName'), lastname: gVal('preferredLastName'), emailaddress1: gVal('preferredEmail'), telephone1: gVal('preferredPhone') }; if (acctId) p['parentcustomerid_account@odata.bind'] = '/accounts(' + acctId + ')'; if (leadId) p['originatingleadid@odata.bind'] = '/leads(' + leadId + ')'; if (config.contactTypeId) p['ongc_ContactType@odata.bind'] = '/ongc_contacttypes(' + config.contactTypeId + ')'; return strip(p); } /* ── STRIPE PAYMENT — commented out, not required yet ────────────────── function buildEvidencePayload() { var fees = calcFees(); var p = { ongc_payername: (gVal('preferredFirstName') + ' ' + gVal('preferredLastName')).trim(), ongc_paymentamount: fees.base, ongc_surchargefee: fees.surcharge, ongc_gst: fees.gst, ongc_totalamount: fees.total, ongc_paymentstatus: 'pending-cc', ongc_transactionstatus: 'pending', ongc_paymentdate: new Date().toISOString(), ongc_responsemessage: 'Pending \u2013 NSQHS Stripe credit-card checkout initiated' }; if (leadId) p['ongc_Lead@odata.bind'] = '/leads(' + leadId + ')'; return strip(p); } ── END STRIPE PAYMENT ─────────────────────────────────────────────────── */ /* ════════ ACCOUNT PAYLOAD ══════════════════════ */ function buildAccountPayload() { var org = gVal('serviceName') || gVal('businessName'); return strip({ name: org, telephone1: gVal('preferredPhone'), emailaddress1: gVal('preferredEmail'), websiteurl: gVal('website'), address1_line1: gVal('streetAddress1'), address1_line2: gVal('streetAddress2'), address1_city: gVal('suburb'), address1_stateorprovince: gVal('state'), address1_postalcode: gVal('postcode'), address1_country: 'Australia' }); } /* ════════ SITE PAYLOADS (ongc_site) ═════════════ One record per site entered in Step 4. Fields: ongc_locationna, ongc_street1, ongc_street2, ongc_suburb, ongc_state (choice int), ongc_postcode, ongc_country (107150000 = Australia) Relationship: ongc_Account@odata.bind -> /accounts(accountId) ════════════════════════════════════════════════ */ function buildSitePayloads(accountId) { var n = parseInt(gVal('numSites')) || 0; var payloads = []; for (var i = 1; i <= n; i++) { var stateRaw = gVal('siteState_' + i); var stateVal = stateRaw ? parseInt(stateRaw, 10) : null; var payload = strip({ ongc_locationname: gVal('siteName_' + i), ongc_street1: gVal('siteAddr1_' + i), ongc_street2: gVal('siteAddr2_' + i), ongc_suburb: gVal('siteSuburb_' + i), ongc_state: stateVal, ongc_postcode: gVal('sitePostcode_' + i), ongc_country: 107150000 /* Australia */ }); if (accountId) payload['ongc_Account@odata.bind'] = '/accounts(' + accountId + ')'; payloads.push(payload); } return payloads; } /* ════════ RECORD CREATION ════════════════════ */ async function createAllRecords() { /* 1 — Account (healthcare service name) */ //setBusy(true, 'Creating healthcare service account\u2026'); var accountId = null; //try { // var acct = await dataversePost('accounts', buildAccountPayload()); // accountId = acct.id; // console.log('[NSQHS] Account:', accountId); //} catch (e) { console.warn('[NSQHS] Account creation failed:', e.message); } /* 2 — Sites linked to the account */ //var siteCount = parseInt(gVal('numSites')) || 0; //if (accountId && siteCount > 0) { // setBusy(true, 'Creating site record(s)\u2026'); // var sitePayloads = buildSitePayloads(accountId); // var siteResults = await Promise.allSettled( // sitePayloads.map(function (p) { return dataversePost('ongc_sites', p); }) // ); // siteResults.forEach(function (r, idx) { // if (r.status === 'fulfilled') console.log('[NSQHS] Site ' + (idx + 1) + ':', r.value && r.value.id); // else console.warn('[NSQHS] Site ' + (idx + 1) + ' failed:', r.reason && r.reason.message); // }); //} /* 3 — Lead (linked to Account) */ setBusy(true, 'Creating registration record\u2026'); var lead = await dataversePost('leads', buildLeadPayload(accountId)); leadId = lead.id; if (!leadId) throw new Error('Lead GUID not returned. Check Dataverse Web API permissions.'); console.log('[NSQHS] Lead:', leadId); /* 4 — Lead reference */ setBusy(true, 'Fetching registration reference\u2026'); leadRef = await fetchLeadRef(leadId); saveSession(); /* 5 — Contact */ //setBusy(true, 'Creating contact record\u2026'); //try { // var cr = await Promise.allSettled([dataversePost('contacts', buildContactPayload(accountId))]); // if (cr[0].status === 'rejected') console.warn('[NSQHS] Contact failed:', cr[0].reason && cr[0].reason.message); // else console.log('[NSQHS] Contact:', cr[0].value && cr[0].value.id); //} catch (e) { console.warn('[NSQHS] Contact error:', e.message); } /* 6 — Payment evidence — STRIPE COMMENTED OUT (not required yet) */ /* setBusy(true, 'Creating payment record\u2026'); var ev = await dataversePost('ongc_paymentevidences', buildEvidencePayload()); if (ev && ev.id) { evidenceId = ev.id; console.log('[NSQHS] Evidence:', evidenceId); } else console.warn('[NSQHS] Evidence GUID not returned'); saveSession(); */ } /* ════════ STRIPE REDIRECT — commented out, not required yet ════════════ function initiateStripePayment() { var fees = calcFees(), org = gVal('serviceName') || gVal('businessName'); var params = new URLSearchParams({ leadId: leadId || '', leadRef: leadRef || '', paymentEvidenceId: evidenceId || '', amount: fees.total.toFixed(2), base: fees.base.toFixed(2), surcharge: fees.surcharge.toFixed(2), gst: fees.gst.toFixed(2), email: gVal('preferredEmail'), name: (gVal('preferredFirstName') + ' ' + gVal('preferredLastName')).trim(), ref: 'National Safety and Quality Health Service (NSQHS) Standards \u2013 ' + org, returnUrl: window.location.href.split('?')[0] }); try { sessionStorage.setItem(SK.inProgress, '1'); if (leadId) sessionStorage.setItem(SK.leadId, leadId); if (leadRef) sessionStorage.setItem(SK.leadRef, leadRef); if (evidenceId) sessionStorage.setItem(SK.evidence, evidenceId); } catch (e) { } window.location.replace('/agpal-stripe-checkout?' + params.toString()); } ════════ END STRIPE REDIRECT ════════════════════════════════════════════ */ /* ════════ RESULT PAGE ══════════════════════════ Hides the form card and displays a success or failure panel with the registration reference number. ════════════════════════════════════════════════ */ function showResult(success, ref, errMsg) { setBusy(false); /* Hide the entire form card */ var card = document.querySelector('.nsqhs-card'); if (card) card.style.display = 'none'; /* Build result panel */ var panel = document.createElement('div'); panel.className = 'nsqhs-card'; panel.style.cssText = 'text-align:center;padding:48px 32px;'; if (success) { panel.innerHTML = '
' + '

Registration Submitted Successfully

' + '

Thank you for submitting your NSQHS scope of service. ' + 'A member of the QIP team will be in touch shortly.

' + (ref ? '
' + '
Reference Number
' + '
' + ref + '
' + '
' : '') + '

Please keep your reference number for future correspondence.

'; } else { panel.innerHTML = '
' + '

Submission Failed

' + '

' + (errMsg || 'We were unable to submit your registration. Please try again or contact QIP for assistance.') + '

' + ''; } /* Insert panel after the header */ var header = document.querySelector('.nsqhs-header'); var container = document.querySelector('.nsqhs-container'); if (header && header.nextSibling) { container.insertBefore(panel, header.nextSibling); } else if (container) { container.appendChild(panel); } else { document.body.appendChild(panel); } window.scrollTo({ top: 0, behavior: 'smooth' }); clearSession(); } /* ════════ BIND NAV ═══════════════════════════ */ function bindNav() { var navMap = [[1, 'next1', 'prev2'], [2, 'next2', 'prev3'], [3, 'next3', 'prev4'], [4, 'next4', 'prev5'], [5, 'next5', 'prev6']]; navMap.forEach(function (item) { var step = item[0], nextId = item[1], prevId = item[2]; var nextBtn = document.getElementById(nextId); var prevBtn = document.getElementById(prevId); if (nextBtn) nextBtn.addEventListener('click', function () { if (!isBusy && validateStep(step)) showStep(step + 1); }); if (prevBtn) prevBtn.addEventListener('click', function () { if (!isBusy) showStep(step); }); }); /* Prev buttons bound in navMap above */ /* Submit */ var sub = document.getElementById('finalSubmitBtn'); if (sub) sub.addEventListener('click', async function () { if (isBusy) return; if (!validateStep(6)) return; var errEl = document.getElementById('nsqhsSubmitError'); if (errEl) errEl.classList.add('hidden'); try { await createAllRecords(); setBusy(false); /* Stripe redirect commented out — show result page instead */ /* initiateStripePayment(); */ showResult(true, leadRef || leadId || ''); } catch (err) { console.error('[NSQHS] Submit failed:', err); setBusy(false); showResult(false, null, err.message || 'Could not submit. Please try again.'); } }); } /* ════════ FIELD CLEAR ERROR ══════════════════ */ function bindFieldClearError() { document.addEventListener('input', function (e) { var fe = e.target.closest('.form-group') && e.target.closest('.form-group').querySelector('.field-error'); if (fe) fe.textContent = ''; }); document.addEventListener('change', function (e) { var fe = e.target.closest('.form-group') && e.target.closest('.form-group').querySelector('.field-error'); if (fe) fe.textContent = ''; }); } /* ════════ INIT ═══════════════════════════════ */ function ready(fn) { if (document.readyState !== 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function () { injectSpinner(); clearSession(); bindFieldClearError(); bindNav(); showStep(1); }); /* window.addEventListener('resize', ...) — signature commented out */ /* window.addEventListener('resize', function () { if (sigCtx) initSig(); }); */ }());