/**
 * invoiceFields.js
 *
 * @author     alfiopiccione <alfio.piccione@gmail.com>
 * @copyright  Copyright (c) 2018, alfiopiccione
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2018 alfiopiccione <alfio.piccione@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

;(
    function ($, wc_el_inv_invoice) {

        /**
         * Init Select2
         *
         * @since 1.0.0
         *
         * @returns {boolean}
         */
        function initSelect2()
        {
            var invoiceType = document.getElementById('billing_invoice_type');
            if (!invoiceType) {
                return false;
            }

            if ($(invoiceType).data('select2')) {
                return false;
            }

            if (typeof $(invoiceType).select2 !== "undefined") {
                $(invoiceType).select2(
                    {
                        minimumResultsForSearch: 3
                    }
                );
            }

            var choiceType = document.getElementById('billing_choice_type');
            if (!choiceType) {
                return false;
            }

            if ($(choiceType).data('select2')) {
                return false;
            }

            if (typeof $(choiceType).select2 !== "undefined") {
                $(choiceType).select2(
                    {
                        minimumResultsForSearch: 3
                    }
                );
            }
        }

        /**
         * Clone Vat in tax code for only company
         * @returns {boolean}
         */
        function cloneValueVat()
        {
            var invoiceType = document.getElementById('billing_invoice_type');
            var invoiceVat = document.getElementById('billing_vat_number');
            var invoiceTax = document.getElementById('billing_tax_code');

            // Return if tax code is disabled
            if ('on' === wc_el_inv_invoice.disable_cf) {
                return false;
            }

            if (!invoiceVat && !invoiceTax) {
                return false;
            }

            if (invoiceVat) {
                invoiceVat.addEventListener('keyup', function (evt) {
                    if (invoiceType && 'company' !== invoiceType.value) {
                        return false;
                    }
                    invoiceTax.value = this.value;
                })
            }
        }

        /**
         * Set Required
         *
         * @since 1.0.0
         *
         * @returns {boolean}
         */
        function setRequired()
        {
            var invoiceType = document.getElementById('billing_invoice_type');
            var country = document.getElementById('bcountry');

            if (!invoiceType || !country) {
                return false;
            }

            document.addEventListener('DOMContentLoaded', function () {
                invoiceType.onchange = changeInvoiceTypeEventHandler;
            }, false);

            document.addEventListener('DOMContentLoaded', function () {
                country.onchange = changeCountryEventHandler;
            }, false);
        }

        function clearTaxCodeValidationState(taxCode)
        {
            if (!taxCode) {
                return;
            }

            taxCode.setCustomValidity('');
            taxCode.classList.remove('pmpro_form_input-error');

            var cfMessage = taxCode.nextElementSibling;
            if (cfMessage && cfMessage.classList.contains('no-valid-cf')) {
                cfMessage.remove();
            }
        }

        /**
         * Change Country Handler
         *
         * @since 1.0.0
         *
         * @param event
         */
        function changeCountryEventHandler(event)
        {
            var country = event.target.value;
            var invoiceType = document.getElementById('billing_invoice_type');
            var choiceType = document.getElementById('billing_choice_type');

            if (choiceType) {
                toggleFieldsDisplay(choiceType.value, event);
            }

            if (!invoiceType) {
                console.log('[POP-PMPRO] changeCountryEventHandler: missing invoiceType, aborting.');
                return false;
            }

            if ('IT' !== country) {
                switchTypeNoIT(invoiceType.value, event);
            } else {
                switchType(invoiceType.value, event);
            }
        }

        /**
         * Change Invoice Type Handler
         *
         * @since 1.0.0
         *
         * @param event
         */
        function changeInvoiceTypeEventHandler(event)
        {
            var country = document.getElementById('bcountry');
            var type = event.target.value;

            // IT country and not required fields and country is in UE
            if (country && 'IT' === country.value &&
                -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
            ) {
                switchType(type, event);
            } else {
                switchTypeNoIT(type, event)
            }
        }

        /**
         * Switch Country
         *
         * @param country
         * @param type
         * @param event
         */
        function switchCountry(country, type, event)
        {
            if ('IT' !== country) {
                switchTypeNoIT(type, event);
            } else {
                switchType(type, event);
            }
        }

        /**
         * Switch No IT type
         * @param type
         * @param ev
         */
        function switchTypeNoIT(type, ev)
        {
            var country = document.getElementById('bcountry');
            var choiceTypeField = document.getElementById('billing_choice_type_div');
            var invoiceTypeField = document.getElementById('billing_invoice_type_div');
            var choiceTypeFieldLabel = document.querySelector('#billing_choice_type_div label[for*="billing_choice_type"]');
            var invoiceTypeFieldLabel = document.querySelector('#billing_invoice_type_div label[for*="billing_invoice_type"]');
            var sdi = document.getElementById('billing_sdi_type');
            var sdiField = document.getElementById('billing_sdi_type_div');
            var sdiLabel = document.querySelector('#billing_sdi_type_div label[for*="billing_sdi_type"]');
            if (sdiLabel) {
                var sdiAbbr = sdiLabel.querySelector('.pmpro_asterisk');
            }

            var vat = document.getElementById('billing_vat_number');
            var vatField = document.getElementById('billing_vat_number_div');
            var vatLabel = document.querySelector('#billing_vat_number_div label[for="billing_vat_number"]');
            if (vatLabel) {
                var vatAbbr = vatLabel.querySelector('.pmpro_asterisk');
            }

            var taxCode = document.getElementById('billing_tax_code');
            var taxCodeField = document.getElementById('billing_tax_code_div');
            var taxCodeLabel = document.querySelector('#billing_tax_code_div label[for="billing_tax_code"]');
            if (taxCode) {
                if (taxCodeLabel) {
                    var taxCodeAbbr = taxCodeLabel.querySelector('.pmpro_asterisk');
                }
                clearTaxCodeValidationState(taxCode);
            }

            var choiceType = document.getElementById('billing_choice_type');
            // Sdi not required for no IT country
            if (sdiField && sdiLabel) {
                // SDI
                sdiField.style.display = 'none';
                if (sdiAbbr) {
                    sdiAbbr.classList.remove('required');
                    sdiAbbr.classList.add('optional');
                    sdiField.classList.remove('validate-required');
                    sdiAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                }
                sdi.removeAttribute('required');
                sdi.value = '';
            }

            // Reset value on change
            if ('change' === ev.type) {
                if (sdi) {
                    sdi.value = '';
                }
                if (vat) {
                    vat.value = '';
                }
                if (taxCode) {
                    taxCode.value = '';
                }
            }

            // No UE not required VAT and TAX
            if (country &&
                'show' !== wc_el_inv_invoice.hide_outside_ue &&
                -1 === wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
            ) {
                // Remove required billing_company
                toggleBillingCompany('private');

                if (choiceTypeField) {
                    choiceTypeField.style.display = 'none';
                    if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild) {
                        choiceTypeFieldLabel.firstElementChild.remove();
                    }
                }
                if (invoiceTypeField) {
                    invoiceTypeField.style.display = 'none';
                    if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild) {
                        invoiceTypeFieldLabel.firstElementChild.remove();
                    }
                }

                // TAX
                if (taxCodeField) {
                    taxCodeField.style.display = 'none';
                    taxCode.value = ''; // reset value
                    if (taxCodeAbbr) {
                        taxCodeAbbr.classList.remove('required');
                    }
                    taxCodeField.classList.remove('validate-required');
                    taxCode.removeAttribute('required');
                }

                // VAT
                if (vatField) {
                    vatField.style.display = 'none';
                    vat.value = ''; // reset value
                    vatField.classList.remove('validate-required');
                    vat.removeAttribute('required');
                }
                return;
            } else {
                if (choiceTypeField) {
                    if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild) {
                        choiceTypeFieldLabel.firstElementChild.remove();
                    }
                    choiceTypeField.style.display = 'block';
                }
                if (invoiceTypeField) {
                    if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild) {
                        invoiceTypeFieldLabel.firstElementChild.remove();
                    }
                    invoiceTypeField.style.display = 'block';
                }
            }

            if ('1' === wc_el_inv_invoice.invoice_required) {
                // Initialize display fields
                if (choiceTypeField) {
                    choiceTypeField.style.display = 'block';
                    if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild &&
                        'ABBR' !== choiceTypeFieldLabel.firstElementChild.nodeName &&
                        !choiceTypeFieldLabel.querySelector('.pmpro_asterisk')
                    ) {
                        $(choiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    } else {
                        if (choiceTypeFieldLabel && null === choiceTypeFieldLabel.firstElementChild) {
                            $(choiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                        }
                    }
                }
                if (invoiceTypeField) {
                    invoiceTypeField.style.display = 'block';
                    if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild &&
                        'ABBR' !== invoiceTypeFieldLabel.firstElementChild.nodeName &&
                        !invoiceTypeFieldLabel.querySelector('.pmpro_asterisk')
                    ) {
                        $(invoiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    } else {
                        if (invoiceTypeFieldLabel && null === invoiceTypeFieldLabel.firstElementChild) {
                            $(invoiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                        }
                    }
                }

                // TAX
                if (taxCodeField) {
                    taxCodeField.style.display = 'block';
                    taxCodeField.classList.add('validate-required');
                    if (taxCodeAbbr) {
                        taxCodeAbbr.classList.remove('optional');
                        taxCodeAbbr.classList.add('required');
                        taxCodeAbbr.innerText = '*';
                        taxCodeAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                    }
                    if (taxCode) {
                        taxCode.setAttribute('required', 'required');
                    }
                }

                // VAT
                if (vatField) {
                    vatField.style.display = 'block';
                    vatField.classList.add('validate-required');
                    if (vatLabel && ! vatAbbr) {
                        $(vatLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    }
                    if (vat) {
                        vat.setAttribute('required', 'required');
                    }
                }
            } else {

                // TAX
                if (taxCodeField) {
                    taxCodeField.classList.remove('validate-required');
                    if (taxCodeAbbr) {
                        taxCodeAbbr.classList.remove('required');
                        taxCodeAbbr.classList.add('optional');
                        taxCodeAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                    }
                    if (taxCode) {
                        taxCode.removeAttribute('required');
                    }
                }

                // VAT
                if (vatField) {
                    vatField.classList.remove('validate-required');
                    if (vatLabel && ! vatAbbr) {
                        $(vatLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    }
                    if (vat) {
                        vat.removeAttribute('required');
                    }
                }
            }

            if (invoiceTypeField) {
                invoiceTypeField.style.display = 'block';
            }

            if (choiceType && 'receipt' === choiceType.value) {
                invoiceTypeField.style.display = 'none';
            }

            if (choiceType && 'receipt' === choiceType.value) {
                type = '';
            }

            switch (type) {
                default:
                case 'private':
                    if (vat) {
                        // VAT
                        vatField.style.display = 'none';
                        if (vatAbbr) {
                            vatAbbr.classList.remove('required');
                            vatAbbr.classList.add('optional');
                        }
                        vatField.classList.remove('validate-required');
                        if (vatAbbr) {
                            vatAbbr.remove();
                        }
                        vat.removeAttribute('required');
                    }
                    if (taxCode) {
                        taxCodeField.style.display = 'block';
                    }
                    break;
                case 'company':
                case 'freelance':
                    if (vat) {
                        vatField.style.display = 'block';
                    }
                    if (taxCode && type !== 'private' && 'on' === wc_el_inv_invoice.disable_cf) {
                        // TAX
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                        }
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('required');
                            taxCodeAbbr.classList.add('optional');
                        }
                        if (taxCodeField) {
                            taxCodeField.classList.remove('validate-required');
                        }
                        if (taxCodeAbbr) {
                            taxCodeAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                        }
                        if (vatAbbr) {
                            vatAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                        }
                        if (taxCode) {
                            taxCode.removeAttribute('required');
                            clearTaxCodeValidationState(taxCode);
                        }
                    }
                    break;
                case '':
                    if (taxCodeField) {
                        taxCodeField.style.display = 'none';
                    }
                    if (sdiField) {
                        sdiField.style.display = 'none';
                    }
                    if (vatField) {
                        vatField.style.display = 'none';
                    }
                    break;
            }

            if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                var cfMessage = taxCode.nextElementSibling;
                if (cfMessage && cfMessage.classList.contains('no-valid-cf')) {
                    cfMessage.remove();
                }
            }

            // Toggle billing company by custom type
            toggleBillingCompany(type);
        }

        /**
         * toggleBillingCompany
         * Toggle billing company by custom type
         *
         * @since 4.4.0
         */
        function toggleBillingCompany(type)
        {
            var companyFiled = document.getElementById('billing_company_div');
            if (companyFiled) {
                var input = document.getElementById('billing_company');
                var companyLabel = companyFiled.querySelector('label');
                var companyLabelAbbr = companyLabel.querySelector('.pmpro_asterisk');

                if ('company' === type) {
                    if (companyFiled && !companyLabelAbbr) {
                        $(companyLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    }
                    companyFiled.style.display = 'block';
                    input.setAttribute('required', 'required')
                } else {
                    if (companyLabelAbbr) {
                        companyLabelAbbr.remove();
                    }
                    input.removeAttribute('required');
                    companyFiled.style.display = 'none';
                }
            }
        }

        /**
         * Switch Type and set args in input
         *
         * @since 1.0.0
         *
         * @param type
         * @param ev
         */
        function switchType(type, ev)
        {
            var country = document.getElementById('bcountry');
            var choiceTypeField = document.getElementById('billing_choice_type_div');
            var invoiceTypeField = document.getElementById('billing_invoice_type_div');
            var choiceTypeFieldLabel = document.querySelector('#billing_choice_type_div label[for*="billing_choice_type"]');
            var invoiceTypeFieldLabel = document.querySelector('#billing_invoice_type_div label[for*="billing_invoice_type"]');
            var choiceType = document.getElementById('billing_choice_type');
            var sdi = document.getElementById('billing_sdi_type');
            var sdiField = document.getElementById('billing_sdi_type_div');
            var sdiInput = document.getElementById('billing_sdi_type');
            var sdiLabel = document.querySelector('#billing_sdi_type_div label[for="billing_sdi_type"]');
            var sdiDesc = document.querySelector('#billing_sdi_type_div #billing_sdi_type-description');

            if (sdi && sdiLabel) {
                var sdiAbbr = sdiLabel.querySelector('.pmpro_asterisk');
            }

            var vat = document.getElementById('billing_vat_number');
            var vatField = document.getElementById('billing_vat_number_div');
            var vatLabel = document.querySelector('#billing_vat_number_div label[for="billing_vat_number"]');
            if (vatLabel) {
                var vatAbbr = vatLabel.querySelector('.pmpro_asterisk');
            }

            var taxCode = document.getElementById('billing_tax_code');
            var taxCodeField = document.getElementById('billing_tax_code_div');
            var taxCodeLabel = document.querySelector('#billing_tax_code_div label[for="billing_tax_code"]');

            if (taxCode && taxCodeLabel) {
                var taxCodeAbbr = taxCodeLabel.querySelector('.pmpro_asterisk');;
            }

            // No UE check
            if (-1 === wc_el_inv_invoice.eu_vat_country.indexOf(country.value)) {
                return;
            }

            // No IT check
            if ('IT' !== country.value) {
                return;
            }

            // Reset value on change
            if ('change' === ev.type) {
                if (sdi) {
                    sdi.value = '';
                }
                if (vat) {
                    vat.value = '';
                }
                if (taxCode) {
                    taxCode.value = '';
                }
            }

            // Initialize display fields
            if (choiceTypeField) {
                choiceTypeField.style.display = 'block';
                if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild &&
                    'ABBR' !== choiceTypeFieldLabel.firstElementChild.nodeName &&
                    !choiceTypeFieldLabel.querySelector('.pmpro_asterisk')
                ) {
                    $(choiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                } else {
                    if (choiceTypeFieldLabel && null === choiceTypeFieldLabel.firstElementChild) {
                        $(choiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    }
                }
            }

            if (invoiceTypeField) {
                invoiceTypeField.style.display = 'block';
                if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild &&
                    'ABBR' !== invoiceTypeFieldLabel.firstElementChild.nodeName &&
                    !invoiceTypeFieldLabel.querySelector('.pmpro_asterisk')
                ) {
                    $(invoiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                } else {
                    if (invoiceTypeFieldLabel && null === invoiceTypeFieldLabel.firstElementChild) {
                        $(invoiceTypeFieldLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                    }
                }
            }

            if (taxCodeField) {
                taxCodeField.style.display = 'block';
            }
            if (vatField) {
                vatField.style.display = 'block';
            }

            switch (type) {
                default:
                case 'private':
                    var billingCompany = document.getElementById('billing_company');
                    if (billingCompany && Number(wc_el_inv_invoice.is_peppol_context) === 1) {
                        billingCompany.value = '';
                    }
                    // TAX-CODE
                    if (taxCode) {
                        if (country &&
                            'IT' === country.value &&
                            taxCode &&
                            'on' === wc_el_inv_invoice.active_js_cf_check
                        ) {
                            cfCheck();
                            taxCode.dispatchEvent(new Event('change'));
                        }

                        taxCodeField.style.display = 'block';
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('optional');
                            taxCodeAbbr.classList.add('required');
                        }
                        taxCodeField.classList.add('validate-required');
                        if (taxCodeAbbr) {
                            taxCodeAbbr.innerText = '*';
                        }
                        taxCode.setAttribute('required', 'required');
                    }
                    // SDI check
                    if (sdiField) {
                        // SDI
                        sdiField.style.display = 'none';
                        sdi.value = ''; // reset value
                        if (sdiAbbr) {
                            sdiAbbr.classList.remove('required');
                            sdiAbbr.classList.add('optional');
                        }
                        sdiField.classList.remove('validate-required');
                        if (sdiAbbr) {
                            sdiAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                        }
                        sdi.removeAttribute('required');
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'none';
                        if (vatAbbr) {
                            vatAbbr.classList.remove('required');
                            vatAbbr.classList.add('optional');
                        }
                        vatField.classList.remove('validate-required');
                        if (vatAbbr) {
                            vatAbbr.remove()
                        }
                        if (vat) {
                            vat.removeAttribute('required');
                        }
                    }

                    break;
                case 'company':
                case 'freelance':
                    // SDI check
                    if (sdiField) {
                        if ('on' !== wc_el_inv_invoice.disable_pec_sdi) {
                            // SDI
                            sdiField.style.display = 'block';
                            sdiField.classList.add('validate-required');
                            if (sdiAbbr) {
                                sdiAbbr.classList.remove('optional');
                                sdiAbbr.classList.add('required');
                                sdiAbbr.innerText = '*';
                                sdiAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                            }
                            sdi.setAttribute('required', 'required');
                            if (sdiDesc) {
                                sdiDesc.innerText = wc_el_inv_invoice.sdi_description;
                            }
                            sdiInput.placeholder = wc_el_inv_invoice.sdi_placeholder;
                        } else {
                            sdiField.style.display = 'none';
                            sdi.removeAttribute('required');
                        }
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'block';
                        vatField.classList.add('validate-required');
                        if (vatLabel && ! vatAbbr) {
                            $(vatLabel).append('<abbr class="pmpro_asterisk required">*</abbr>');
                        }
                        if (vat) {
                            vat.setAttribute('required', 'required');
                        }
                    }

                    // TAX-CODE
                    if (taxCode && !('on' === wc_el_inv_invoice.disable_cf && type !== 'private')) {
                        taxCodeField.style.display = 'block';
                        taxCodeField.classList.add('validate-required');

                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('optional');
                            taxCodeAbbr.classList.add('required');
                            taxCodeAbbr.innerText = '*';
                            taxCodeAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                        }
                        taxCode.setAttribute('required', 'required');
                    } else if (taxCode && type !== 'private' && 'on' === wc_el_inv_invoice.disable_cf) {
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                            taxCode.removeAttribute('required');
                        }
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('required');
                            taxCodeAbbr.classList.add('optional');
                            taxCodeAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                        }
                        clearTaxCodeValidationState(taxCode);
                    }

                    if (taxCode) {
                        clearTaxCodeValidationState(taxCode);
                    }
                    break;
                case '':
                    if (taxCodeField) {
                        taxCodeField.style.display = 'none';
                    }
                    if (sdiField) {
                        sdiField.style.display = 'none';
                    }
                    if (vatField) {
                        vatField.style.display = 'none';
                    }
                    break;
            }

            if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                var cfMessage = taxCode.nextElementSibling;
                if (cfMessage && cfMessage.classList.contains('no-valid-cf')) {
                    cfMessage.remove();
                }
            }

            // Logic for displaying the fields if set to "receipt" at the change of state.
            var currentChoiceType = null;
            if (choiceTypeField && choiceType) {
                currentChoiceType = choiceType.options[choiceType.selectedIndex];
            }
            if (currentChoiceType && 'receipt' === currentChoiceType.value) {
                toggleFieldsDisplay(currentChoiceType.value, ev);
            }

            // Toggle billing company by custom type
            toggleBillingCompany(type);
        }

        /**
         * Choice type
         * @param ev
         */
        function choiceType(ev)
        {
            var choiceType = document.getElementById('billing_choice_type');
            initSelect2();

            // Remove optional text
            var choiceTypeLabel = document.querySelector('#billing_choice_type label[for="billing_choice_type"] span.optional');
            if (choiceTypeLabel) {
                choiceTypeLabel.remove();
            }

            if (choiceType && 'load' === ev.type) {
                toggleFieldsDisplay(choiceType.options[choiceType.selectedIndex].value, ev);
            }

            if (choiceType) {
                $(choiceType).on('change', function (evt) {
                    toggleFieldsDisplay(this.value, evt);
                });
            }
        }

        /**
         * Toggle Display fields
         *
         * @param type
         * @param ev
         */
        function toggleFieldsDisplay(type, ev)
        {
            var invoiceTypeField = document.getElementById('billing_invoice_type_div');
            var sdiField = document.getElementById('billing_sdi_type_div');
            var vatField = document.getElementById('billing_vat_number_div');
            var taxCodeField = document.getElementById('billing_tax_code_div');
            var invoiceType = document.getElementById('billing_invoice_type');
            var sdi = document.getElementById('billing_sdi_type');
            var company = document.getElementById('billing_company');
            var vat = document.getElementById('billing_vat_number');
            var taxCode = document.getElementById('billing_tax_code');

            if (!invoiceType) {
                console.log('[POP-PMPRO] toggleFieldsDisplay: missing invoiceType, aborting.');
                return;
            }

            console.log('[POP-PMPRO] toggle:', type, 'event:', ev.type);

            switch (type) {
                case'invoice':
                    var country = document.getElementById('bcountry');
                    // Check condition for display fields based on country and invoice type selected
                    if ('' === invoiceType.options[invoiceType.selectedIndex].value) {
                        invoiceTypeField.style.display = 'block';
                    } else {
                        invoiceTypeField.style.display = 'block';

                        if ('private' === invoiceType.options[invoiceType.selectedIndex].value) {
                            if (taxCodeField) {
                                taxCodeField.style.display = 'block';
                            }
                            if (type === 'load' || taxCode.value === 'XXXXXX00L00L000X') {
                                taxCode.value = '';
                            }

                        } else if ('company' === invoiceType.options[invoiceType.selectedIndex].value ||
                                   'freelance' === invoiceType.options[invoiceType.selectedIndex].value
                        ) {
                            // Display and reset value
                            if (vat) {
                                vatField.style.display = 'block';
                                if ('load' !== ev.type) {
                                    vat.value = '';
                                }
                            }
                            // Display Only IT
                            if ('IT' === country.value) {
                                if (sdi) {
                                    sdiField.style.display = 'block';
                                    if ('load' !== ev.type) {
                                        sdi.value = '';
                                    }
                                }
                            }
                            if (taxCode) {
                                taxCodeField.style.display = 'block';
                                if ('load' !== ev.type) {
                                    taxCode.value = '';
                                }
                            }
                        }

                        switchType(invoiceType.options[invoiceType.selectedIndex].value, ev);
                    }
                    break;
                case'receipt':
                    // Reset billing company required
                    toggleBillingCompany(null);
                    // It serves as a discriminant to generate the receipt
                    // fake data to validate the fields
                    if (company) {
                        company.value = '';
                    }
                    if (vat) {
                        vat.value = '11111111111';
                        vatField.style.display = 'none';
                    }
                    if (sdi) {
                        sdi.value = '1111111';
                        sdiField.style.display = 'none';
                    }
                    if (taxCode) {
                        taxCode.value = 'XXXXXX00L00L000X';
                        taxCodeField.style.display = 'none';
                    }
                    invoiceTypeField.style.display = 'none';
                    break;
                // Reset fields
                case'reset':
                    // Reset billing company required
                    toggleBillingCompany(null);
                    if (company) {
                        company.value = '';
                    }
                    if (vat) {
                        vat.value = '';
                    }
                    if (sdi) {
                        sdi.value = '';
                    }
                    if (taxCode) {
                        taxCode.value = '';
                    }
                    break;
                default:
                    break;
            }
        }

        // Set required fields
        setRequired();

        /**
         * getLevelId
         */
        function getLevelId()
        {
            var level_id = jQuery('#pmpro_level').val();
            if (!level_id) {
                // If the level ID is not set, try to get it from the #level field for outdated checkout templates.
                level_id = jQuery('#level').val();
            }

            return level_id;
        }

        /**
         * Vies check via ajax
         */
        function viesCheckActions()
        {
            (function ($) {
                let lastVat = '';
                let lastCountry = '';
                let debounceTimer;

                $('#billing_vat_number, #billing_tax_code, #billing_choice_type, #billing_invoice_type').on('change blur', function () {

                    var viesSpan = $('#billing_vat_number_div .pmpro_form_label .valid_vies');

                    clearTimeout(debounceTimer);

                    debounceTimer = setTimeout(function () {
                        const levelId = getLevelId();
                        const invoiceType = $('#billing_invoice_type').val().trim();
                        const vatNumber = $('#billing_vat_number').val().trim();
                        const country = $('#bcountry').val().trim();

                        if (vatNumber === lastVat && country === lastCountry) {
                            return;
                        }

                        if (viesSpan) {
                            viesSpan.remove()
                        }

                        lastVat = vatNumber;
                        lastCountry = country;

                        fetch(wc_el_inv_invoice.ajax_url, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: new URLSearchParams({
                                action: 'pmProViesCheck',
                                vat_number: vatNumber,
                                invoice_type: invoiceType,
                                level: levelId,
                                country: country,
                            })
                        }).then(response => response.json())
                          .then(data => {
                              console.log('[POP-PMPRO] vies response:', data);

                              if (data.data.price) {
                                  var cost = document.querySelector('#pmpro_level_cost .pmpro_level_cost_text strong')
                                  cost.innerHTML = data.data.price;
                              }

                              const label = $('#billing_vat_number_div label');
                              const message = $('<small class="valid_vies" style="margin-left:10px;"></small>');

                              message.text(data.data.message);
                              message.css('color', data.success ? 'green' : 'red');
                              label.append(message);
                          })
                          .catch(err => {
                              console.log('[POP-PMPRO] vies error:', err);
                          });

                    }, 300); // Debounce: 300ms
                });
            })(jQuery);
        }

        /**
         * CF check
         */
        function cfCheck()
        {
            var name = document.getElementById('billing_first_name');
            var lastName = document.getElementById('billing_last_name');
            var taxCode = document.getElementById('billing_tax_code');
            var invoiceType = document.getElementById('billing_invoice_type');
            var checkCodeFinal = false;
            var computeInverse = {};

            // Reset on change name and last name
            $(name).on('change', function () {
                taxCode.value = ''
            });
            $(lastName).on('change', function () {
                taxCode.value = ''
            });

            // Tax code change
            $(taxCode).on('change', function () {
                taxCode.setCustomValidity("");
                taxCode.classList.remove('pmpro_form_input-error');
                var CF = this.value.toUpperCase();
                var checkCode = CodiceFiscale.check(CF);

                if ('private' === invoiceType.options[invoiceType.selectedIndex].value) {
                    // Final check
                    if (this.value.length <= 16 && true === checkCode) {
                        computeInverse = CodiceFiscale.computeInverse(CF);
                        var args = {
                            name: document.getElementById('bfirstname').value,
                            surname: document.getElementById('blastname').value,
                            gender: computeInverse.gender,
                            birthday: computeInverse.birthday,
                            birthplace: computeInverse.birthplace
                        };
                        var cfDataFinal = new CodiceFiscale(args);
                        console.log('[POP-PMPRO] CodiceFiscale di ' + args.name + ' ' + args.surname, cfDataFinal);
                        checkCodeFinal = (0 === cfDataFinal.code.indexOf(computeInverse.surname + computeInverse.name));
                    } else {
                        checkCodeFinal = false;
                    }
                    console.log('[POP-PMPRO] Check CF:', checkCodeFinal);
                    if (!checkCodeFinal) {
                        setTimeout(function () {
                            var cfMessage = taxCode.nextElementSibling;
                            if (cfMessage) {
                                cfMessage.remove();
                            }

                            //taxCode.value = '';
                            taxCode.insertAdjacentHTML('afterend',
                                "<p class='no-valid-cf'><small>(*) <b>" + CF + "</b> " + wc_el_inv_invoice.invalid_tax_code + "</small></p>"
                            );
                            taxCode.classList.add('pmpro_form_input-error');
                            taxCode.setCustomValidity(wc_el_inv_invoice.invalid_tax_code);
                        }, 200);
                        return false;
                    } else {
                        var cfMessage = taxCode.nextElementSibling;
                        if (cfMessage && cfMessage.classList.contains('no-valid-cf')) {
                            cfMessage.remove();
                        }
                        return true;
                    }
                }
            })
        }

        // Load listener
        window.addEventListener('load', function (ev) {

            // Default
            var invoiceType = document.getElementById('billing_invoice_type');
            var country = document.getElementById('bcountry');
            var taxCode = document.getElementById('billing_tax_code');

            if (!invoiceType) {
                invoiceType = document.querySelectorAll('#billing_invoice_type.form-radios input[type=radio]');
            }

            if (!invoiceType || (invoiceType.length !== undefined && !invoiceType.length)) {
                console.log('[POP-PMPRO] window.load: missing invoiceType, aborting.');
                return false;
            }

            if (!country) {
                return false;
            }

            if (country) {
                var readOnly = country.getAttribute('readonly');
                if (readOnly && 'readonly' === readOnly) {
                    country.closest('#bcountry').style.display = 'none';
                }
            }

            // Remove optional label
            var invoiceTypeLabelOption = document.querySelector('label[for="billing_invoice_type"] .optional');
            if (invoiceTypeLabelOption) {
                invoiceTypeLabelOption.remove();
            }

            // Required and in not UE country
            if ('SELECT' === invoiceType.tagName) {
                if (country &&
                    'IT' === country.value &&
                    -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(wc_el_inv_invoice.country)
                ) {
                    if (invoiceType.tagName.toLowerCase() === 'select') {
                        switchType(invoiceType.options[invoiceType.selectedIndex].value, ev);
                    } else if (invoiceType.tagName.toLowerCase() === 'input') {
                        switchType(invoiceType.value, ev);
                    }
                } else {
                    if (invoiceType.tagName.toLowerCase() === 'select') {
                        switchTypeNoIT(invoiceType.options[invoiceType.selectedIndex].value, ev);
                    } else if (invoiceType.tagName.toLowerCase() === 'input') {
                        switchTypeNoIT(invoiceType.value, ev);
                    }
                }

                // Switch country
                if (country) {
                    switchCountry(country.value, invoiceType.value, ev);
                }

            } else {
                if (country &&
                    'IT' === country.value &&
                    -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(wc_el_inv_invoice.country)
                ) {
                    switchType(invoiceType[0].value, ev);
                } else {
                    switchTypeNoIT(invoiceType[0].value, ev);
                }

                // Switch country
                if (country) {
                    switchCountry(country.value, invoiceType[0].value, ev);
                }
            }

            choiceType(ev);
            initSelect2();
            cloneValueVat();
            viesCheckActions();

            // By activating the control of the Fiscal Code only for the "Private" customer type, the value
            // of the fiscal code will be validated through a correspondence
            // between the Fiscal Code and the Name and Surname fields
            if (country &&
                'IT' === country.value &&
                taxCode &&
                'on' === wc_el_inv_invoice.active_js_cf_check
            ) {
                cfCheck();
                taxCode.dispatchEvent(new Event('change'));
            }
        })

    }(jQuery, window.wc_el_inv_invoice)
);
