';
container.appendChild(sec);
}
}
/* scope section */
function buildScopeSections() {
var container = document.getElementById('scopeSectionsContainer');
if (!container) return;
container.innerHTML = '';
var checked = Array.prototype.slice.call(document.querySelectorAll('.aof-cb:checked'));
if (!checked.length) {
container.innerHTML = '
Please go back to Step 2 and select at least one area of focus.
';
return;
}
checked.forEach(function (cb) {
var area = cb.value;
var safeId = area.replace(/[^a-zA-Z0-9]/g, '_');
var sec = document.createElement('div');
sec.className = 'pchs-scope-section';
sec.innerHTML =
'
' + area + '
' +
(area === 'Other' ?
'
' +
'
' : '') +
'
' +
'
' +
'
' +
'
' +
'
' +
'
';
container.appendChild(sec);
});
}
/* Signature box */
function initSig() {
var c = document.getElementById('pchsSigCanvas');
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 = '#1d2f43'; 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('pchsSigCanvas');
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 payloads */
function collectSites() {
var n = parseInt(gVal('numSites')) || 0, sites = [];
for (var i = 1; i <= n; i++) 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), fteTotal: gVal('siteFteTotal_' + i), fteProviders: gVal('siteFteProviders_' + i), fteAdmin: gVal('siteFteAdmin_' + i) });
return sites;
}
function collectScope() {
var result = [];
Array.prototype.slice.call(document.querySelectorAll('.aof-cb:checked')).forEach(function (cb) {
var sid = cb.value.replace(/[^a-zA-Z0-9]/g, '_');
result.push({ area: cb.value, practitioners: gVal('scope_prac_' + sid), services: gVal('scope_svc_' + sid), otherDetails: cb.value === 'Other' ? gVal('scope_other_details') : '' });
});
return result;
}
function buildWebResponseHtml() {
var postalDiff = document.getElementById('postalDiffYes') && document.getElementById('postalDiffYes').checked;
var sites = collectSites();
var scope = collectScope();
var now = new Date().toLocaleString('en-AU', { timeZone: 'Australia/Sydney', dateStyle: 'medium', timeStyle: 'short' });
function row(label, value) {
if (!value && value !== 0) value = '\u2014';
return '
'
+ '
' + label + '
'
+ '
' + value + '
'
+ '
';
}
function section(title) {
return '
' + title + '
';
}
var html = '
'
+ '
';
/* Header */
html += '
'
+ 'PCHS Registration — Scope of Service
';
html += '
'
+ 'Submitted: ' + now + '
';
/* 1. Contact Details */
html += section('1. Contact Details');
html += row('QIP Client ID', gVal('clientId'));
html += row('Healthcare Service Name', gVal('healthcareServiceName'));
html += row('Contact Name', gVal('contactFirst') + ' ' + gVal('contactLast'));
html += row('Email', gVal('email'));
html += row('Phone', gVal('phone'));
html += row('Website', gVal('website'));
html += row('Business / Trading Name', gVal('businessName'));
html += row('ABN', gVal('abn'));
html += row('ACN', gVal('acn'));
/* Street address */
var streetAddr = [gVal('streetAddress1'), gVal('streetAddress2'), gVal('streetSuburb'),
gVal('streetState'), gVal('streetPostcode'), 'Australia'].filter(Boolean).join(', ');
html += row('Street Address', streetAddr);
/* Postal address */
if (postalDiff) {
var postalAddr = [gVal('postalAddress1'), gVal('postalSuburb'),
gVal('postalState'), gVal('postalPostcode'), 'Australia'].filter(Boolean).join(', ');
html += row('Postal Address', postalAddr);
} else {
html += row('Postal Address', 'Same as street address');
}
/* 2. Scope */
html += section('2. Scope of Service');
html += row('Governance Structure', radioVal('governance') === 'Other'
? 'Other: ' + gVal('governanceOther') : radioVal('governance'));
html += row('Location Type', radioVal('locationType'));
html += row('Discipline', radioVal('discipline'));
var aofChecked = getChecked('.aof-cb');
var aofDisplay = aofChecked.length ? aofChecked.join(', ') : '\u2014';
if (aofChecked.indexOf('Other') !== -1 && gVal('aofOtherText')) aofDisplay += ' (' + gVal('aofOtherText') + ')';
html += row('Area(s) of Focus', aofDisplay);
html += row('Corporate Entity', radioVal('corporateEntity') === 'Yes'
? 'Yes \u2014 ' + gVal('corporateName') : radioVal('corporateEntity'));
html += row('Previously Accredited', radioVal('prevAccredited'));
if (radioVal('prevAccredited') === 'Yes') {
var stds = getChecked('.std-cb');
html += row('Current Standards', stds.length ? stds.join(', ') : '\u2014');
html += row('Current Provider', gVal('currentProvider'));
html += row('Voluntary Basis', radioVal('voluntaryBasis'));
html += row('Funding / Licensing', radioVal('fundingLicensing'));
html += row('Accreditation Expiry', gVal('accreditationExpiry'));
}
/* 3. Sites */
html += section('3. 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, s.postcode].filter(Boolean).join(', ') || '—';
/* Per-site divider header */
html += '
'
+ '
'
+ '📍 Site ' + num + (siteName ? ' — ' + siteName : '')
+ '
';
html += row('Site Name', siteName);
html += row('Address', siteAddr);
html += row('Total FTE Staff', s.fteTotal || '—');
html += row('FTE Healthcare Providers', s.fteProviders || '—');
html += row('FTE Mgmt & Admin', s.fteAdmin || '—');
if (i < sites.length - 1) {
html += '
';
}
});
} else {
html += '
No sites entered.
';
}
/* Scope detail — grouped per area (sub-header + Practitioners + Services) */
if (scope.length) {
html += section('3b. Scope Detail');
scope.forEach(function (sc, i) {
/* Area group sub-header */
html += '
'
+ '
'
+ sc.area
+ '
';
/* Practitioners row */
html += '
'
+ '
Practitioners
'
+ '
' + (sc.practitioners || '—') + '
'
+ '
';
/* Services row */
html += '
'
+ '
Services
'
+ '
' + (sc.services || '—') + '
'
+ '
';
/* Other details */
if (sc.otherDetails) {
html += '
'
+ '
Details
'
+ '
' + sc.otherDetails + '
'
+ '
';
}
/* spacer between groups */
if (i < scope.length - 1) {
html += '
';
}
});
}
/* 4. Additional Information */
html += section('4. Additional Information');
html += row('Physical Examinations', radioVal('physicalExams'));
html += row('Further Information', gVal('furtherInfo'));
/* 5. Assessment Preferences */
html += section('5. Assessment Preferences');
html += row('Assessment Process', radioVal('assessmentProcess'));
if (radioVal('assessmentProcess').indexOf('virtual') !== -1) {
html += row('Commission Permission', radioVal('commissionPermission'));
if (radioVal('commissionPermission') === 'Yes') html += row('IT Infrastructure', radioVal('itInfra'));
}
html += row('Other Frameworks', gVal('otherFrameworks'));
/* 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 += '
';
return html;
}
function buildLeadPayload(acctId) {
var org = gVal('healthcareServiceName') || gVal('businessName');
var postalDiff = document.getElementById('postalDiffYes') && document.getElementById('postalDiffYes').checked;
var p = strip({
subject: 'National Safety and Quality Primary and Community Healthcare Standards \u2013 ' + org,
firstname: gVal('contactFirst'), lastname: gVal('contactLast') || org,
emailaddress1: gVal('email'), telephone1: gVal('phone'),
companyname: org, websiteurl: gVal('website'), leadsourcecode: 8,
address1_line1: gVal('streetAddress1'), address1_line2: gVal('streetAddress2'),
address1_city: gVal('streetSuburb'), address1_stateorprovince: gVal('streetState'),
address1_postalcode: gVal('streetPostcode'), 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: 5, ongc_practicename: org,
ongc_practiceabn: gVal('abn'), ongc_practicephone: gVal('phone'),
ongc_clientid: gVal('clientId'), ongc_postalsameasstreet: !postalDiff,
ongc_webresponse: buildWebResponseHtml()
//description: JSON.stringify({
// clientId: gVal('clientId'), businessName: gVal('businessName'), acn: gVal('acn'),
// governance: radioVal('governance'), governanceOther: gVal('governanceOther'),
// locationType: radioVal('locationType'), discipline: radioVal('discipline'),
// areaOfFocus: getChecked('.aof-cb'), aofOther: gVal('aofOtherText'),
// corporateEntity: radioVal('corporateEntity'), corporateName: gVal('corporateName'),
// prevAccredited: radioVal('prevAccredited'), currentStandards: getChecked('.std-cb'),
// currentProvider: gVal('currentProvider'), voluntaryBasis: radioVal('voluntaryBasis'),
// fundingLicensing: radioVal('fundingLicensing'), expiryDate: gVal('accreditationExpiry'),
// numSites: gVal('numSites'), sites: collectSites(), scope: collectScope(),
// physicalExams: radioVal('physicalExams'), furtherInfo: gVal('furtherInfo'),
// assessmentProcess: radioVal('assessmentProcess'), commissionPermission: radioVal('commissionPermission'),
// itInfra: radioVal('itInfra'), otherFrameworks: gVal('otherFrameworks'),
// authRepName: gVal('authRepName'), authRepPosition: gVal('authRepPosition')
//})
});
if (config.businessId)
p['ongc_Business@odata.bind'] = '/ongc_businesses(' + config.businessId + ')';
if (acctId) p['parentaccountid@odata.bind'] = '/accounts(' + acctId + ')';
return p;
}
function buildContactPayload() {
var p = { firstname: gVal('contactFirst'), lastname: gVal('contactLast') || gVal('healthcareServiceName'), emailaddress1: gVal('email'), telephone1: gVal('phone') };
if (accountId) p['parentcustomerid_account@odata.bind'] = '/accounts(' + accountId + ')';
if (leadId) p['originatingleadid@odata.bind'] = '/leads(' + leadId + ')';
if (config.contactTypeId) p['ongc_ContactType@odata.bind'] = '/ongc_contacttypes(' + config.contactTypeId + ')';
return strip(p);
}
function buildEvidencePayload() {
var fees = calcFees();
var p = { ongc_payername: (gVal('contactFirst') + ' ' + gVal('contactLast')).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 PCHS Stripe credit-card checkout initiated' };
if (leadId) p['ongc_Lead@odata.bind'] = '/leads(' + leadId + ')';
return strip(p);
}
/* RECORD CREATION */
async function createAllRecords() {
///* Step 1: Create Account from healthcareServiceName */
//setBusy(true, 'Creating account record\u2026');
//var acct = await dataversePost('accounts', buildAccountPayload());
//accountId = acct.id;
//if (!accountId) throw new Error('Account GUID not returned. Check Dataverse Web API permissions.');
//console.log('[PCHS] Account:', accountId);
var accountId = null;
/* Step 2: Create 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('[PCHS] Lead:', leadId);
/* Step 3: Fetch reference number */
setBusy(true, 'Fetching registration reference\u2026');
leadRef = await fetchLeadRef(leadId);
saveSession();
///* Step 4: Create Contact */
//setBusy(true, 'Creating contact record\u2026');
//try {
// var cr = await Promise.allSettled([dataversePost('contacts', buildContactPayload())]);
// if (cr[0].status === 'rejected') console.warn('[PCHS] Contact failed:', cr[0].reason && cr[0].reason.message);
// else console.log('[PCHS] Contact:', cr[0].value && cr[0].value.id);
//} catch (e) { console.warn('[PCHS] Contact error:', e.message); }
///* Step 5: Create ongc_site records (one per site and linked to Account) */
//var siteCnt = parseInt(gVal('numSites')) || 0;
//if (siteCnt > 0) {
// setBusy(true, 'Creating site records\u2026');
// var sitesData = collectSites();
// for (var s = 0; s < sitesData.length; s++) {
// try {
// var sr = await dataversePost('ongc_sites', buildSitePayload(sitesData[s], accountId));
// console.log('[PCHS] Site ' + (s + 1) + ':', sr.id);
// } catch (e) { console.warn('[PCHS] Site ' + (s + 1) + ' failed:', e.message); }
// }
//}
/* STRIPE PAYMENT EVIDENCE
setBusy(true, 'Creating payment record\u2026');
var ev = await dataversePost('ongc_paymentevidences', buildEvidencePayload());
if (ev && ev.id) { evidenceId = ev.id; console.log('[PCHS] Evidence:', evidenceId); }
else console.warn('[PCHS] Evidence GUID not returned');
saveSession();
── END STRIPE PAYMENT EVIDENCE ── */
}
/* STRIPE REDIRECT
function initiateStripePayment() {
var fees = calcFees(), org = gVal('healthcareServiceName') || 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('email'), name: (gVal('contactFirst') + ' ' + gVal('contactLast')).trim(), ref: 'National Safety and Quality Primary and Community Healthcare 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 */
function showResult(success, ref, errMsg) {
var wrap = document.querySelector('.pchs-wrap');
if (!wrap) return;
var shell = wrap.querySelector('.pchs-form-shell');
if (shell) shell.style.display = 'none';
var progress = wrap.querySelector('.pchs-progress-wrap');
if (progress) progress.style.display = 'none';
var hero = wrap.querySelector('.pchs-hero');
if (hero) hero.style.display = 'none';
var resultDiv = document.getElementById('pchsResultPage');
if (!resultDiv) { resultDiv = document.createElement('div'); resultDiv.id = 'pchsResultPage'; wrap.appendChild(resultDiv); }
if (success) {
resultDiv.innerHTML =
'
' +
'
✓
' +
'
Registration Submitted Successfully
' +
'
Thank you for submitting your NSQPCH accreditation scope of service. A QIP team member will be in touch shortly.
' +
'
Your Reference Number' + (ref || '\u2014') + '
' +
'
Please keep this reference number for your records.
' +
'
';
} else {
resultDiv.innerHTML =
'
' +
'
⚠
' +
'
Submission Failed
' +
'
We were unable to complete your registration. Please try again or contact QIP for assistance.
' +
(errMsg ? '
' + errMsg + '
' : '') +
'' +
'
';
}
resultDiv.style.display = 'block';
window.scrollTo({ top: 0, behavior: 'smooth' });
}
/* INIT */
function bindNav() {
/* Bind individual Next/Prev buttons by ID */
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 on step 2 goes to step 1 */
var p2 = document.getElementById('prev2');
if (p2) p2.addEventListener('click', function () { if (!isBusy) showStep(1); });
/* Submit */
var sub = document.getElementById('finalSubmitBtn');
if (sub) sub.addEventListener('click', async function () {
if (isBusy) return;
if (!validateStep(6)) return;
var errEl = document.getElementById('pchsSubmitError');
if (errEl) errEl.classList.remove('show');
try {
await createAllRecords();
setBusy(false);
showResult(true, leadRef || leadId || '\u2014');
/* STRIPE REDIRECT
setBusy(true, 'Redirecting to payment\u2026');
initiateStripePayment();
*/
} catch (err) {
console.error('[PCHS] Submit failed:', err);
setBusy(false);
showResult(false, null, err.message || 'Could not submit. Please try again.');
}
});
/* Postal toggle */
document.querySelectorAll('input[name="postalDiff"]').forEach(function (el) { el.addEventListener('change', pchs.togglePostal); });
/* Governance Other */
document.querySelectorAll('input[name="governance"]').forEach(function (el) { el.addEventListener('change', pchs.toggleGovernanceOther); });
}
function bindFieldClearError() {
document.addEventListener('input', function (e) { var fg = e.target.closest('.pchs-field-group'); if (fg) { var et = fg.querySelector('.pchs-error-text'); if (et) et.classList.remove('show'); } });
document.addEventListener('change', function (e) { var fg = e.target.closest('.pchs-field-group'); if (fg) { var et = fg.querySelector('.pchs-error-text'); if (et) et.classList.remove('show'); } });
}
function ready(fn) { if (document.readyState !== 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }
ready(function () {
injectSpinner();
clearSession();
bindFieldClearError();
bindNav();
showStep(1);
});
window.addEventListener('resize', function () { if (sigCtx) initSig(); });
}());