var headContent = "<!-- FORM: HEAD SECTION --><head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <meta name=\"referrer\" content=\"no-referrer-when-downgrade\">\n    <title><\/title>\n                                        <link href=\"https:\/\/nswdpie.tfaforms.net\/dist\/form-builder\/5.0.0\/wforms-layout.css?v=1757580178\" rel=\"stylesheet\" type=\"text\/css\">\n                                                <link href=\"https:\/\/nswdpie.tfaforms.net\/dist\/form-builder\/5.0.0\/wforms-jsonly.css?v=1757580178\" rel=\"stylesheet\" type=\"text\/css\">\n                                                <link href=\"https:\/\/nswdpie.tfaforms.net\/uploads\/themes\/theme-114.css?v=1757580178\" rel=\"stylesheet\" type=\"text\/css\">\n                                                        <script src=\"https:\/\/nswdpie.tfaforms.net\/js\/FA__DOMContentLoadedEventDispatcher.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/wForms\/3.11\/js\/wforms.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/wForms\/3.11\/js\/localization-en_GB.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/wForms\/3.11\/js\/wforms_prefill.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/dist\/jquery\/jquery.0416573c648d279fd758.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/js\/typeahead\/v1.2.0\/typeahead.bundle.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/dist\/analytics\/data-collector.e86d94bd97a6d88cf5db.js?v=1757580178\" type=\"text\/javascript\"><\/script>\n                                                <script src=\"https:\/\/nswdpie.tfaforms.net\/api_v2\/sst\/wf-quick-publish?v=1757580178\" type=\"text\/javascript\"><\/script>\n                            \n    <\/head>";
var bodyContent = "<!-- FORM: BODY SECTION --><body class=\"default wFormWebPage\">\n\n    \n\n<div id=\"tfaContent\">\n\n            <div class=\"wFormContainer\" style=\"max-width: 100%; width: auto;\">\n    <div class=\"wFormHeader\"><\/div>\n\n    \n    <style type=\"text\/css\">\n                #tfa_4,\n                *[id^=\"tfa_4[\"] {\n                    width: 254px !important;\n                }\n                #tfa_4-D,\n                *[id^=\"tfa_4[\"][class~=\"field-container-D\"] {\n                    width: auto !important;\n                }\n            \n                #tfa_8,\n                *[id^=\"tfa_8[\"] {\n                    width: 1034px !important;\n                }\n                #tfa_8-D,\n                *[id^=\"tfa_8[\"][class~=\"field-container-D\"] {\n                    width: auto !important;\n                }\n            <\/style><div class=\"\"><div class=\"wForm\" id=\"1202-WRPR\" data-language=\"en_GB\" dir=\"ltr\">\n<div class=\"codesection\" id=\"code-1202\"><style type=\"text\/css\">\n  .wForm form {\n    background-color: #F2F2F2;\n  }\n  .wFormContainer .wForm form { \n    padding: 0px 12px;\n  }\n  .wFormContainer .wFormHeader {\n    height: 0px;\n  }\n  input#wfPagePreviousId2.wfPagePreviousButton {\n    display: none !important;\n  }\n<\/style>\n<script type=\"text\/javascript\"> \n  wFORMS.behaviors.paging.MESSAGES = \n  { CAPTION_NEXT : 'Check', CAPTION_PREVIOUS : 'Previous' } \n<\/script>\n<div style=\"color:red\">\n<noscript>For full functionality of this tool, we recommend that you <a href=\"http:\/\/www.enable-javascript.com\/\">enable Javascript<\/a> on your browser. Please check your brower's settings.<\/noscript>\n<\/div><\/div>\n<form method=\"post\" action=\"https:\/\/nswdpie.tfaforms.net\/api_v2\/workflow\/processor\" class=\"hintsBelow labelsAbove\" id=\"1202\">\n<div class=\"wfPage\" id=\"wfPgIndex-1\"><div class=\"section pageSection\" id=\"tfa_10\"><fieldset id=\"tfa_1\" class=\"section\">\n<div class=\"htmlSection\" id=\"tfa_16\"><div class=\"htmlContent\" id=\"tfa_16-HTML\">You\u2019ll need your most recent electricity bill to find your electricity provider\u2019s Australian Business Number (ABN).<br><br>\n<b>Enter your electricity provider\u2019s 11-digit ABN. <\/b>Select the ABN from the list and click \u2018Check\u2019. If you\u2019ve entered the correct ABN and no results are found, click \u2018Check\u2019.<\/div><\/div>\n<div class=\"oneField field-container-D  labelsRemoved  \" id=\"tfa_4-D\">\n<div class=\"inputWrapper\">\n<input aria-required=\"true\" type=\"text\" id=\"tfa_4\" name=\"tfa_4\" value=\"\" placeholder=\"00 111 222 333\" maskmaxlength=\"14\" autoformat=\"## ### ### ###\" title=\"ABN\" data-dataset-allow-free-responses=\"1\" data-dataset-clear-cache=\"\" autocomplete=\"off\" data-dataset-timestamp=\"1757037187\" data-dataset-id=\"045053a5-aa39-44b6-ac4f-c606207385e9\" data-dataset-map=\"b=tfa_8,c=tfa_9,\" data-dataset-type=\"csv\" data-dataset-url=\"https:\/\/typeahead.formassembly.com\" data-dataset-action=\"query.php\" class=\"validate-custom \/^[1-9]\\d(\\s?\\d{3}){3}$\/ required wfAutosuggest\"><i class=\"fa fa-spinner fa-pulse fa-fw tt-spinner\"><\/i><i class=\"fa fa-search tt-search\" aria-hidden=\"true\"><\/i><i class=\"fa fa-times-circle tt-clear no-input\" tabindex=\"0\" aria-label=\"Clear field\" role=\"button\"><\/i>\n<\/div>\n<script type=\"text\/javascript\">\n                        if(typeof wFORMS != 'undefined') {\n                            if(wFORMS.behaviors.validation) {\n                                wFORMS.behaviors.validation.rules['customtfa_4'] =  { selector: '*[id=\"tfa_4\"]', check: 'validateCustom'};\n                                wFORMS.behaviors.validation.messages['customtfa_4'] = \"This ABN is invalid. Please enter the correct 11-digit ABN.\";\n                            }\n                        }<\/script>\n<\/div>\n<div class=\"oneField field-container-D  labelsRemoved  \" id=\"tfa_8-D\"><div class=\"inputWrapper\"><input type=\"text\" id=\"tfa_8\" name=\"tfa_8\" value=\"  \" autocomplete=\"off\" default=\"  \" readonly data-wforms-nooverwrite=\"disabled\" data-conditionals=\"#tfa_15,#tfa_12,#tfa_13\" title=\"Energy provider name\" class=\"\"><\/div><\/div>\n<div class=\"oneField field-container-D     wf-acl-hidden\" id=\"tfa_9-D\">\n<label id=\"tfa_9-L\" class=\"label preField \" for=\"tfa_9\">Energy customer type<\/label><br><div class=\"inputWrapper\"><input type=\"text\" id=\"tfa_9\" name=\"tfa_9\" value=\"\" autocomplete=\"off\" data-conditionals=\"#tfa_14,#tfa_12,#tfa_13\" title=\"Energy customer type\" class=\"\"><\/div>\n<\/div>\n<\/fieldset><\/div><\/div>\n<div class=\"wfPage\" id=\"wfPgIndex-2\"><div class=\"section pageSection\" id=\"tfa_11\">\n<fieldset id=\"tfa_12\" class=\"section\" data-condition=\"`#tfa_9,equals,Retail` AND `#tfa_8,notEquals,Locality Planning Energy Pty Ltd`\"><div class=\"htmlSection\" id=\"tfa_18\"><div class=\"htmlContent\" id=\"tfa_18-HTML\">You\u2019re a retail energy customer. <b>You do not need to apply.<\/b> You will receive your Bill Relief payment automatically from your electricity provider in quarterly instalments. Check your latest electricity bill and if you haven\u2019t received your Bill Relief payment, contact your electricity provider directly.<\/div><\/div><\/fieldset>\n<fieldset id=\"tfa_13\" class=\"section\" data-condition=\"`#tfa_9,equals,Embedded network` AND `#tfa_8,notEquals,Locality Planning Energy Pty Ltd`\"><div class=\"htmlSection\" id=\"tfa_19\"><div class=\"htmlContent\" id=\"tfa_19-HTML\">You\u2019re an embedded network energy customer. <b>You might need to apply<\/b> depending on your eligibility for energy rebates. <a href=\"\/households\/rebates-grants-and-schemes\/national-energy-bill-relief#households-embedded-networks\"><u>Find out more information below.<\/u><\/a><\/div><\/div><\/fieldset>\n<fieldset id=\"tfa_14\" class=\"section\" data-condition=\"`#tfa_9,equals,`\"><div class=\"htmlSection\" id=\"tfa_20\"><div class=\"htmlContent\" id=\"tfa_20-HTML\"><p>That ABN is not in our database or might be invalid. You can contact your energy provider directly to find out if you\u2019re a retail or embedded network customer.<\/p><br>\n<p>If you\u2019re a retail customer, <b>you do not need to apply<\/b>. You will receive your Bill Relief payment automatically from your electricity provider in quarterly instalments. Check your latest electricity bill and if you haven\u2019t received your Bill Relief payment, contact your electricity provider directly.<\/p><br> \n<p class=\"custom-cursor-on-hover\">If you\u2019re an embedded network energy customer, <b>you might need to apply<\/b> depending on your eligibility for energy rebates. <a href=\"\/households\/rebates-grants-and-schemes\/national-energy-bill-relief#households-embedded-networks\"><u>Find out more information below.<\/u><\/a><\/p><\/div><\/div><\/fieldset>\n<fieldset id=\"tfa_15\" class=\"section\" data-condition=\"`#tfa_8,equals,Locality Planning Energy Pty Ltd`\">\n<legend id=\"tfa_15-L\"><span class=\"custom-cursor-on-hover\">Locality Planning Energy Pty Ltd customer<\/span><\/legend>\n<div class=\"htmlSection\" id=\"tfa_21\"><div class=\"htmlContent\" id=\"tfa_21-HTML\">If you live at the below addresses, you\u2019re a retail energy customer. <b>You do not need to apply.<\/b> You will receive your Bill Relief payment automatically from your electricity provider in quarterly instalments. Check your latest electricity bill and if you haven\u2019t received your Bill Relief payment, contact your electricity provider directly.\n<ul>\n  <li>Bay Grand South (Tower 1) \u2013 11 Enid Street, Tweed Heads<\/li>\n  <li>Bay Grand East (Tower 2) \u2013 9 Enid Street, Tweed Heads<\/li>\n  <li>Bay Grand North (Tower 3) \u2013 2 Thomas Street, Tweed Heads<\/li>\n<\/ul>\nIf you don\u2019t live at the above addresses, you\u2019re an embedded network energy customer. <b>You might need to apply<\/b> depending on your eligibility for energy rebates. <a href=\"\/households\/rebates-grants-and-schemes\/national-energy-bill-relief#households-embedded-networks\"><u>Find out more information below.<\/u><\/a><\/div><\/div>\n<\/fieldset>\n<\/div><\/div>\n<div class=\"actions\" id=\"1202-A\" data-contentid=\"submit_button\"><input type=\"submit\" data-label=\"Check again\" class=\"primaryAction\" id=\"submit_button\" value=\"Check again\" data-conditional-mode=\"disabled\"><\/div>\n<div style=\"clear:both\"><\/div>\n<input type=\"hidden\" value=\"809-3318fc9890333174119ef911f7cf4666\" name=\"tfa_dbCounters\" id=\"tfa_dbCounters\" autocomplete=\"off\"><input type=\"hidden\" value=\"1202\" name=\"tfa_dbFormId\" id=\"tfa_dbFormId\"><input type=\"hidden\" value=\"\" name=\"tfa_dbResponseId\" id=\"tfa_dbResponseId\"><input type=\"hidden\" value=\"39e613bd9d76c3cb4a8461dd57d1e520\" name=\"tfa_dbControl\" id=\"tfa_dbControl\"><input type=\"hidden\" value=\"\" name=\"tfa_dbWorkflowSessionUuid\" id=\"tfa_dbWorkflowSessionUuid\"><input type=\"hidden\" value=\"126\" name=\"tfa_dbDataflowId\" id=\"tfa_dbDataflowId\"><input type=\"hidden\" value=\"1757580178\" name=\"tfa_dbTimeStarted\" id=\"tfa_dbTimeStarted\" autocomplete=\"off\"><input type=\"hidden\" value=\"78\" name=\"tfa_dbVersionId\" id=\"tfa_dbVersionId\"><input type=\"hidden\" value=\"1\" name=\"startWorkflow\" id=\"startWorkflow\"><input type=\"hidden\" value=\"\" name=\"tfa_switchedoff\" id=\"tfa_switchedoff\">\n<\/form>\n<\/div><\/div><div class=\"wFormFooter\"><p class=\"supportInfo\"><br><\/p><\/div>\n\n<\/div>\n\n\n            <script id=\"analytics-collector-script\" type=\"text\/javascript\" src=\"https:\/\/nswdpie.tfaforms.net\/dist\/analytics\/data-collector.e86d94bd97a6d88cf5db.js\" data-customer-id=\"63602\" data-endpoint=\"https:\/\/analytics.formassembly.com\/v1\/traces\"><\/script>\n\n    \n<script type=\"text\/javascript\" data-for=\"FA__DOMContentLoadedEventDispatch\" src=\"https:\/\/nswdpie.tfaforms.net\/js\/FA__DOMContentLoadedEventDispatcher.js\" defer><\/script>\n\n\n<script type=\"text\/javascript\">\n    document.addEventListener(\"FA__DOMContentLoaded\", function(){\n        const FORM_TIME_START = Math.floor((new Date).getTime()\/1000);\n        let formElement = document.getElementById(\"tfa_0\");\n        if (null === formElement) {\n            formElement = document.getElementById(\"0\");\n        }\n        let appendJsTimerElement = function(){\n            let formTimeDiff = Math.floor((new Date).getTime()\/1000) - FORM_TIME_START;\n            let cumulatedTimeElement = document.getElementById(\"tfa_dbCumulatedTime\");\n            if (null !== cumulatedTimeElement) {\n                let cumulatedTime = parseInt(cumulatedTimeElement.value);\n                if (null !== cumulatedTime && cumulatedTime > 0) {\n                    formTimeDiff += cumulatedTime;\n                }\n            }\n            let jsTimeInput = document.createElement(\"input\");\n            jsTimeInput.setAttribute(\"type\", \"hidden\");\n            jsTimeInput.setAttribute(\"value\", formTimeDiff.toString());\n            jsTimeInput.setAttribute(\"name\", \"tfa_dbElapsedJsTime\");\n            jsTimeInput.setAttribute(\"id\", \"tfa_dbElapsedJsTime\");\n            jsTimeInput.setAttribute(\"autocomplete\", \"off\");\n            if (null !== formElement) {\n                formElement.appendChild(jsTimeInput);\n            }\n        };\n        if (null !== formElement) {\n            if(formElement.addEventListener){\n                formElement.addEventListener('submit', appendJsTimerElement, false);\n            } else if(formElement.attachEvent){\n                formElement.attachEvent('onsubmit', appendJsTimerElement);\n            }\n        }\n    });\n<\/script>\n\n<script type=\"text\/javascript\">\n    if(wFORMS.behaviors.prefill) wFORMS.behaviors.prefill.skip = true;\n<\/script>\n\n\n    <script>\n        var FAoldJQ;\n        if (typeof $ != 'undefined' && $.noConflict) FAoldJQ = $.noConflict(true);\n    <\/script>\n    <script src=\"https:\/\/nswdpie.tfaforms.net\/dist\/jquery\/jquery.0416573c648d279fd758.js\"><\/script>\n    <script src=\"https:\/\/nswdpie.tfaforms.net\/js\/typeahead\/v1.2.0\/typeahead.bundle.js\"><\/script>\n    <script>\n        var FA$ = $.noConflict(true);\n        if (FAoldJQ) $ = FAoldJQ;\n    <\/script>\n\n    <link href=\"https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/font-awesome\/4.4.0\/css\/font-awesome.min.css\" rel=\"stylesheet\" type=\"text\/css\">\n\n    <\/div>\n\n\n    \n\n\n<\/body>";
var resumeUrl = null;
var baseUrl = "https:\/\/nswdpie.tfaforms.net";

/**
 * Main entry point, called when the DOM is loaded.
 */
function loadFormAssemblyFormHeadAndBodyContents() {
    var targetElement = getTargetElement();
    var formBodyWrapper = createFormBodyWrapper();

    injectHeadContent();
    injectBodyContent(formBodyWrapper, targetElement);
    addResumeLink();

    document.addEventListener('FA__DOMContentLoaded', function () {
        executeBodyScripts(formBodyWrapper);
        
        // Set up FA$ for autosuggest behavior (jQuery in noConflict mode)
        if (typeof $ !== 'undefined' && $.noConflict) {
            window.FA$ = $.noConflict(true);
        }
        
        // Apply prefill behavior to enable URL parameter prefilling
        var forms = document.querySelectorAll('form');
        forms.forEach(function(form) {
            if (wFORMS && wFORMS.behaviors && wFORMS.behaviors.prefill) {
                wFORMS.behaviors.prefill.skip = false;
                wFORMS.behaviors.prefill.applyTo(form);
            }
        });
    });
}
window.addEventListener('DOMContentLoaded', loadFormAssemblyFormHeadAndBodyContents);

/**
 * Finds the target DOM element where the form should be injected.
 * @returns {HTMLElement|null} The target element or null if not found.
 */
function getTargetElement() {
    var quickPublishScript = document.querySelector('script[data-qp-target-id]');
    if (quickPublishScript) {
        var elementID = quickPublishScript.getAttribute('data-qp-target-id');
        return document.getElementById(elementID);
    }
    return null;
}

/**
 * Creates the main wrapper div for the form's body content.
 * @returns {HTMLDivElement}
 */
function createFormBodyWrapper() {
    var bodyWrapperDiv = document.createElement('div');
    bodyWrapperDiv.id = "FA__QP__BODYWRAPPERDIV";
    return bodyWrapperDiv;
}

/**
 * Injects the form's header content (styles, scripts) into the main document.
 */
function injectHeadContent() {
    var head = document.createElement('head');
    head.innerHTML = headContent;

    var headElements = Array.from(head.children);
    var scriptElements = headElements.filter(function(el) { return el.nodeName === 'SCRIPT'; });
    var otherElements = headElements.filter(function(el) { return el.nodeName !== 'SCRIPT'; });

    otherElements.forEach(function(el) { document.head.appendChild(el); });
    loadHeadScriptsSequentially(scriptElements);
}

/**
 * Loads header script tags sequentially to maintain order.
 * @param {HTMLScriptElement[]} scriptElements - An array of script elements to load.
 */
function loadHeadScriptsSequentially(scriptElements) {
    var script = scriptElements.shift();
    if (!script) {
        document.dispatchEvent(new Event('FA__DOMContentLoaded'));
        return;
    }

    var newScript = document.createElement('script');
    Array.from(script.attributes).forEach(function(attr) { newScript.setAttribute(attr.name, attr.value); });
    newScript.innerHTML = script.innerHTML;

    if (script.src) {
        newScript.onload = function() { loadHeadScriptsSequentially(scriptElements); };
        document.head.appendChild(newScript);
    } else {
        document.head.appendChild(newScript);
        loadHeadScriptsSequentially(scriptElements);
    }
}

/**
 * Injects the form's body content into the target element.
 * @param {HTMLDivElement} formBodyWrapper - The div that will contain the form.
 * @param {HTMLElement|null} targetElement - The element to inject the form into.
 */
function injectBodyContent(formBodyWrapper, targetElement) {
    var body = document.createElement('body');
    body.innerHTML = bodyContent;

    Array.from(body.children).forEach(function(el) { formBodyWrapper.appendChild(el); });

    if (targetElement) {
        targetElement.appendChild(formBodyWrapper);
    } else {
        document.body.appendChild(formBodyWrapper);
    }
}

/**
 * If a resume URL is provided, it finds the "Save and Resume" containers
 * and injects the resume link.
 */
function addResumeLink() {
    if (!resumeUrl) return;

    var oneFieldContainers = document.querySelectorAll('.wForm .saveAndResume > .oneField');
    oneFieldContainers.forEach(function (container) {
        var separator = document.createTextNode(' | ');

        var resumeLink = document.createElement('a');
        resumeLink.href = baseUrl + resumeUrl;
        resumeLink.innerHTML = 'Resume a previously saved form';
        
        resumeLink.addEventListener('click', function(event) {
            if (!confirm('Are you sure you want to resume a previous response? Any information you just entered on this page will be discarded.')) {
                event.preventDefault();
            }
        });

        container.appendChild(separator);
        container.appendChild(resumeLink);
    });
}

/**
 * Finds and re-executes script tags from the form's body.
 * @param {HTMLDivElement} formBodyWrapper - The wrapper containing the form.
 */
function executeBodyScripts(formBodyWrapper) {
    var scriptTags = formBodyWrapper.querySelectorAll('script');
    scriptTags.forEach(function (scriptTag) {
        // Skip jQuery, Typeahead, Kalendae, and Calendar scripts that are already loaded in the head
        if (scriptTag.src && (
            scriptTag.src.includes('jquery.js') || 
            scriptTag.src.includes('typeahead.bundle.js') ||
            scriptTag.src.includes('/js/kalendae/') ||
            scriptTag.src.includes('wforms_calendar.js')
        )) {
            return;
        }
        
        // Skip noConflict scripts that are meant for jQuery/Typeahead
        if (scriptTag.innerHTML && scriptTag.innerHTML.includes('noConflict')) {
            return;
        }
        
        var script = document.createElement('script');
        Array.from(scriptTag.attributes).forEach(function(attr) { script.setAttribute(attr.name, attr.value); });
        script.innerHTML = scriptTag.innerHTML;
        scriptTag.parentNode.replaceChild(script, scriptTag);
    });
}
