





		let referenceNumber = null;
let memberCheck = false;
let redirectUrl = "/bank/bank-click-to-call";
let callBackSectionShown = false;
let checkBoxesShown = false;
let formName = '';
let validateBankSelection = false;

pageLoad();
clearSelection()

function pageLoad() {
    const url = window.parent.location.href;
    localStorage.setItem('landingPageUrl', url);
}

// function populateLeadFormCsrfToken(){

//     const leadForm = document.getElementById('leadForm');
//     const csrfKey = getCsrfKey();
//     const csrfToken = getCsrfToken();

//     if (csrfKey && csrfToken) {
//         const tokenField = document.createElement('input');
//         tokenField.type = 'hidden';
//         tokenField.name = csrfKey;
//         tokenField.value = csrfToken;
//         leadForm.appendChild(tokenField);
//     }
// }

function checkBoxOptions() {
    // populateLeadFormCsrfToken();
    validateSelection()
    validateBankSelection = true
    document.getElementById('callBackForm').style.display = "none";
    document.getElementById('showCheckBoxOptions').style.display = "block";
    document.getElementById('getStartedButton').style.display = "block";
    checkBoxesShown = true;
    formName = 'bank_quote_tool';
    populateStart();
}

if (checkBoxesShown) {
    document.getElementById("rewardsCheckbox").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("rateCheckbox").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("savingsCheckbox").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("getStartedAltButton").addEventListener("click", (event) => {
        populateSubmit();
    });
}

function showCallMeBackForm() {
    validateBankSelection = false
    validateSelection()
    document.getElementById('callBackForm').style.display = "block";
    document.getElementById('showCheckBoxOptions').style.display = "none";
    document.getElementById('getStartedButton').style.display = "none";
    $.fn.matchHeight._update();
    callBackSectionShown = true;
    formName = 'bank_call_me_back_form';
    populateStart();
}

if (callBackSectionShown) {
    document.getElementById("firstName").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("surname").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("cellNumber").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("email").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("idNumber").addEventListener("click", (event) => {
        populateStart();
    });
    document.getElementById("callBackButtonAlt").addEventListener("click", (event) => {
        populateSubmit();
    });
}

function continueExploring() {
    window.parent.location.href = redirectUrl;
}

// function getCsrfKey(){
//     const metaElement = window.top.document.head.querySelector('meta[name="_csrf_header"]');
//     return metaElement ? metaElement.content : null;
// }

// function getCsrfToken(){
//     const metaElement = window.top.document.head.querySelector('meta[name="_csrf"]');
//     return metaElement ? metaElement.content : null;
// }

function handleErrors () {
    document.getElementById('spinner').classList.remove("spinner");
    document.getElementById('spinner').classList.remove("spinner-action");
    document.getElementById('errorMsg').style.display = 'block';
}

function sendNinjaLead() {
    resetValidation();
    let valid = true;

    if (!document.forms["callBackForm"]["firstName"].value.match(/^[a-zA-Z]+([-\s'][a-zA-Z]+)*$/) || document.forms["callBackForm"]["firstName"].value === "") {
        valid = false;
    }
    if (!document.forms["callBackForm"]["surname"].value.match(/^[a-zA-Z]+([-\s'][a-zA-Z]+)*$/) || document.forms["callBackForm"]["surname"].value === "") {
        valid = false;
    }
    if (document.forms["callBackForm"]["cellNumber"].value === "" || document.forms["callBackForm"]["cellNumber"].value.length < 10 || isNaN(document.forms["callBackForm"]["cellNumber"].value)
        || !document.forms["callBackForm"]["cellNumber"].value.match(/^((?:\+27|27)|0)([^0123459]{1})-?([0-9]{1})-?(\d{3})-?(\d{4})$/)) {
        valid = false;
    }
    if (!document.forms["callBackForm"]["email"].value.match(/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/) || document.forms["callBackForm"]["email"].value === "") {
        valid = false;
    }
    if (document.forms["callBackForm"]["idNumber"].value === "" || document.forms["callBackForm"]["idNumber"].value.length < 13 || isNaN(document.forms["callBackForm"]["idNumber"].value)
        || (!document.forms["callBackForm"]["idNumber"].value.match(/^(([0-9]{2})(0|1)([0-9])([0-3])([0-9]))([ ]?)(([0-9]{4})([ ]?)([0-1][8]([ ]?)[0-9]))$/))) {
        valid = false;
    }

    if (valid) {
        sendNinjaDataAndGA();
    }
}

function sendNinjaDataAndGA() {
    let lead = {
        "firstName": document.forms["callBackForm"]["firstName"].value,
        "surname": document.forms["callBackForm"]["surname"].value,
        "mobileNumber": document.forms["callBackForm"]["cellNumber"].value,
        "idNumber": document.forms["callBackForm"]["idNumber"].value,
        "email": document.forms["callBackForm"]["email"].value,
        "medium": "Call me back",
        "servicePlatformCampaign": "web_lead_3",
        "Comment": getComment(),
    }

    // const csrfKey = getCsrfKey();
    // const csrfToken = getCsrfToken();

    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    // if (csrfKey && csrfToken){
    //     headers[csrfKey] = csrfToken;
    // }

    fetch('/portal/api/bank-leads-msrv/leads/register?' + new URLSearchParams(lead).toString(), {
        method: 'POST',
        headers: headers
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            handleErrors();
        }
    }).then(data => {
        if (data) {
            referenceNumber = data.referenceNumber;
            populateGANinja();
            getActiveProduct();
        }
    })
}

function populateGANinja() {
    dataLayer.push({
        'event': 'generate_lead_ninja',
        'event_parameters': {
            'form_name': 'bank_call_me_back_form',
            'lead_id': referenceNumber,
            'form_action': 'submit_personal_details',
            'form_step': '1',
        }
    })
}

function resetValidation() {
    document.getElementById('errorName').style.display = 'none';
    document.getElementById('errorSurname').style.display = 'none';
    document.getElementById('errorCellphone').style.display = 'none';
    document.getElementById('errorIDNumber').style.display = 'none';
    document.getElementById('errorIDNumberShort').style.display = 'none';
    document.getElementById('errorIDNumberInvalid').style.display = 'none';
    document.getElementById('errorEmail').style.display = 'none';
    document.getElementById('errorEmailInvalid').style.display = 'none'
    document.getElementById('errorCellphoneShort').style.display = 'none';
    document.getElementById('errorCellphoneInvalid').style.display = 'none';
    document.getElementById('errorSurnameText').style.display = 'none';
    document.getElementById('errorNameText').style.display = 'none';
    document.getElementById('firstName').classList.remove("invalid");
    document.getElementById('surname').classList.remove("invalid");
    document.getElementById('cellNumber').classList.remove("invalid");
    document.getElementById('idNumber').classList.remove("invalid");
    document.getElementById('email').classList.remove("invalid");
}

function getActiveProduct() {
    fetch('/portal/api/bank-leads-msrv/leads/getActiveProductStatus?idNumber=' + document.forms["callBackForm"]["idNumber"].value, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
    }).then(data => {
        if (data) {
            memberCheck = data;
        }
    })
}

function checkRefNumber() {
    if (referenceNumber !== null) {
        clearInterval(idTimeout);
        updateLead();
    }
}

function clearSelection() {
    window.addEventListener("pageshow", () => {
        setTimeout(() => {
            const findIdealBankAccount = document.getElementById("findIdealBankAccount");
            if (findIdealBankAccount) findIdealBankAccount.checked = false;
            const callbackToggle = document.getElementById("callback");
            if (callbackToggle) callbackToggle.checked = false;

            jcf.refresh(detailsToggle);
            jcf.refresh(callbackToggle);
        }, 0);
    });
}

function selectOnlyOne(checkbox) {
    const checkboxIds = ["rewardsCheckbox", "savingsCheckbox", "rateCheckbox"];
    setTimeout(() => {

        checkboxIds.forEach(id => {
            if (id !== checkbox.id) {
                const other = document.getElementById(id);
                if (other) {
                    other.checked = false;
                }
            }
        });

        const rewardsCheckbox = document.getElementById("rewardsCheckbox");
        const savingsCheckbox = document.getElementById("savingsCheckbox");
        const rateCheckbox = document.getElementById("rateCheckbox");

        jcf.refresh(rewardsCheckbox);
        jcf.refresh(savingsCheckbox);
        jcf.refresh(rateCheckbox);

        validateSelection()
    }, 0);
}

function validateSelection() {
    const errorSelection = document.getElementById("errorSelection");

    const findIdealBankAccount = document.getElementById("findIdealBankAccount");
    const callback = document.getElementById("callback");

    const findIdealChecked = findIdealBankAccount?.checked === true;
    const callbackChecked = callback?.checked === true;

    let valid = findIdealChecked || callbackChecked;

    if (findIdealChecked) {
        const rewards = document.getElementById("rewardsCheckbox")?.checked === true;
        const savings = document.getElementById("savingsCheckbox")?.checked === true;
        const rate = document.getElementById("rateCheckbox")?.checked === true;

        valid = rewards || savings || rate;
    }

    errorSelection.style.display = valid ? "none" : "block";
    return valid;
}

function validateForm() {
    let valid = true;
    resetValidation();
    if (document.forms["callBackForm"]["firstName"].value === "") {
        document.getElementById('errorName').style.display = 'block';
        document.getElementById('firstName').classList.add("invalid");
        valid = false;
    } else if (!document.forms["callBackForm"]["firstName"].value.match(/^[a-zA-Z]+([-\s'][a-zA-Z]+)*$/)) {
        document.getElementById('errorNameText').style.display = 'block';
        document.getElementById('firstName').classList.add("invalid");
        valid = false;
    }
    if (document.forms["callBackForm"]["surname"].value === "") {
        document.getElementById('errorSurname').style.display = 'block';
        document.getElementById('surname').classList.add("invalid");
        valid = false;
    } else if (!document.forms["callBackForm"]["surname"].value.match(/^[a-zA-Z]+([-\s'][a-zA-Z]+)*$/)) {
        document.getElementById('errorSurnameText').style.display = 'block';
        document.getElementById('surname').classList.add("invalid");
        valid = false;
    }
    if (document.forms["callBackForm"]["cellNumber"].value === "") {
        document.getElementById('cellNumber').classList.add("invalid");
        document.getElementById('errorCellphone').style.display = 'block';
        valid = false;
    } else if (isNaN(document.forms["callBackForm"]["cellNumber"].value) || !document.forms["callBackForm"]["cellNumber"].value.match(/^((?:\+27|27)|0)([^0123459]{1})-?([0-9]{1})-?(\d{3})-?(\d{4})$/)) {
        document.getElementById('cellNumber').classList.add("invalid");
        document.getElementById('errorCellphoneInvalid').style.display = 'block';
        valid = false;
    } else if (document.forms["callBackForm"]["cellNumber"].value.length < 10) {
        document.getElementById('errorCellphoneShort').style.display = 'block';
        document.getElementById('cellNumber').classList.add("invalid");
        valid = false;
    }
    if (document.forms["callBackForm"]["email"].value === "") {
        document.getElementById('errorEmail').style.display = 'block';
        document.getElementById('email').classList.add("invalid");
        valid = false;
    } else if (!document.forms["callBackForm"]["email"].value.match(/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/)) {
        document.getElementById('errorEmailInvalid').style.display = 'block';
        document.getElementById('email').classList.add("invalid");
        valid = false;
    }
    if (document.forms["callBackForm"]["idNumber"].value === "") {
        document.getElementById('idNumber').classList.add("invalid");
        document.getElementById('errorIDNumber').style.display = 'block';
        valid = false;
    } else if (isNaN(document.forms["callBackForm"]["idNumber"].value) || !document.forms["callBackForm"]["idNumber"].value.match(/^(([0-9]{2})(0|1)([0-9])([0-3])([0-9]))([ ]?)(([0-9]{4})([ ]?)([0-1][8]([ ]?)[0-9]))$/)) {
        document.getElementById('idNumber').classList.add("invalid");
        document.getElementById('errorIDNumberInvalid').style.display = 'block';
        valid = false;
    } else if (document.forms["callBackForm"]["idNumber"].value.length < 13) {
        document.getElementById('idNumber').classList.add("invalid");
        document.getElementById('errorIDNumberShort').style.display = 'block';
        valid = false;
    }

    if (valid) {
        document.getElementById('spinner').classList.add("spinner");
        document.getElementById('spinner').classList.add("spinner-action");
        if (referenceNumber === null) {
            idTimeout = setInterval(() => {
                checkRefNumber();
            }, 1000);
        } else {
            updateLead();
        }
    }
    return valid;
}

function updateLead() {
    let lead = {
        "firstName": document.forms["callBackForm"]["firstName"].value,
        "surname": document.forms["callBackForm"]["surname"].value,
        "emailAddress": document.forms["callBackForm"]["email"].value,
        "medium": "Call me back",
        "servicePlatformCampaign": "web_lead_1",
        "consentGranted": "true",
    }

    // const csrfKey = getCsrfKey();
    // const csrfToken = getCsrfToken();

    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    // if (csrfKey && csrfToken){
    //     headers[csrfKey] = csrfToken;
    // }

    fetch('/portal/api/bank-leads-msrv/leads/updateLead?' + new URLSearchParams(lead).toString(), {
        method: 'POST',
        headers: headers
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
    }).then(data => {
        updatePopulateGA();
        updateConsent();
    })
}

function updateConsent() {
    let consent = {
        "consentValue": "true"
    }

    // const csrfKey = getCsrfKey();
    // const csrfToken = getCsrfToken();

    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    // if (csrfKey && csrfToken){
    //     headers[csrfKey] = csrfToken;
    // }

    fetch('/portal/api/bank-leads-msrv/leads/updateConsent?' + new URLSearchParams(consent).toString(), {
        method: 'POST',
        headers: headers
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
    }).then(data => {
        if (memberCheck) {
            document.getElementById("existingClient").style.display = 'block';
            document.getElementById("callBackForm").style.display = 'none';
            document.getElementById("leadForm").style.display = 'none';
        } else {
            document.getElementById("myBtn").click();
        }
    })
}

function updatePopulateGA() {
    dataLayer.push({
        'event': 'generate_lead',
        'event_parameters': {
            'form_name': 'bank_call_me_back_form',
            'lead_id': referenceNumber,
            'form_action': 'submit_personal_details',
            'form_step': '1',
        },
        'user': {
            'first_name': document.forms["callBackForm"]["firstName"].value,
            'last_name': document.forms["callBackForm"]["surname"].value,
            'email': document.forms["callBackForm"]["email"].value,
            'phone': document.forms["callBackForm"]["cellNumber"].value.replace(document.forms["callBackForm"]["cellNumber"].value.charAt(0), '+27'),
        }
    })
}

function getComment() {
    return 'Request a callback';
}

function populateStart() {
    dataLayer.push({
        'event': 'form_start',
        'event_parameters': {
            'form_name': formName,
            'form_action': 'get_started',
            'form_step': '1',
        }
    })
}

function populateSubmit() {
    dataLayer.push({
        'event': 'form_submit',
        'event_parameters': {
            'form_name': formName,
            'form_action': 'get_started',
            'form_step': '1',
        }
    })
}

