/**
 * 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) {

        /**
         * sdiRegex
         * @type {RegExp}
         */
        const sdiRegex = /^[a-zA-Z0-9]{7}$/;

        /**
         * pecRegex
         * @type {RegExp}
         */
        const pecRegex = /^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:\w*.?pec(?:.?\w+)*)$/i;

        /**
         * vatRegex
         * @type {RegExp}
         */
        const vatRegex = /^(ATU[0-9]{8}|BE0[0-9]{9}|BG[0-9]{9,10}|CY[0-9]{8}L|CZ[0-9]{8,10}|DE[0-9]{9}|DK[0-9]{8}|EE[0-9]{9}|(EL|GR)[0-9]{9}|ES[0-9A-Z][0-9]{7}[0-9A-Z]|FI[0-9]{8}|FR[0-9A-Z]{2}[0-9]{9}|GB([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{13})|HU[0-9]{8}|IE[0-9][A-Z0-9][0-9]{5}[A-Z]{1,2}|IT[0-9]{11}|LT([0-9]{9}|[0-9]{12})|LU[0-9]{8}|LV[0-9]{11}|MT[0-9]{8}|NL[0-9]{9}B[0-9]{2}|PL[0-9]{10}|PT[0-9]{9}|RO[0-9]{2,10}|SE[0-9]{12}|SI[0-9]{8}|SK[0-9]{10})$/i;

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

            taxCode.setCustomValidity("");

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

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

            if(typeof window.PMS_ChosenStrings !== 'undefined' && $.fn.chosen !== undefined ){
                $(invoiceType).chosen( PMS_ChosenStrings );
            }

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


            if (typeof $(choiceType).select2 !== "undefined") {
                $(choiceType).chosen( PMS_ChosenStrings );
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

            // Validation on change
            vatCheck();
            sdiCheck();
            cfCheck();
        }

        /**
         * Change Invoice Type Handler
         *
         * @since 1.0.0
         *
         * @param event
         */
        function changeInvoiceTypeEventHandler(event)
        {
            var country = document.getElementById('pms_billing_country');
            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)
            }

            // Validation on change
            vatCheck();
            sdiCheck();
            cfCheck();
        }

        /**
         * 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('pms_billing_country');
            var choiceTypeField = document.querySelector('.pms-pms-choice-type');
            var invoiceTypeField = document.querySelector('.pms-pms-invoice-type');
            var choiceTypeFieldLabel = document.querySelector('.pms-pms-choice-type label[for*="pms_choice_type"]');
            var invoiceTypeFieldLabel = document.querySelector('.pms-pms-invoice-type label[for*="pms_invoice_type"]');
            var sdi = document.getElementById('pms_sdi_type');
            var sdiField = document.querySelector('.pms-pms-sdi-type');

            var vat = document.getElementById('pms_vat_number');
            var vatField = document.querySelector('.pms-pms-vat-number');

            var taxCode = document.getElementById('pms_tax_code');
            var taxCodeField = document.querySelector('.pms-pms-tax-code');
            var cfMessage = null;

            if (taxCode) {
                clearTaxCodeValidationState(taxCode);
                cfMessage = taxCode.nextElementSibling;
            }

            var choiceType = document.getElementById('pms_choice_type');

            // Sdi not required for no IT country
            if (sdiField) {
                // SDI
                sdiField.style.display = 'none';
                if (sdi) {
                    sdi.classList.add('hide-field')
                    sdi.removeAttribute('required');
                    sdi.value = '';
                }
            }

            // Reset value on change
            if ('change' === ev.type) {
                if (sdi) {
                    sdi.value = '';
                }
                if (vat) {
                    vat.value = '';
                    setVatPrefix();
                }
                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 pms_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
                    taxCode.classList.add('hide-field')
                    taxCode.removeAttribute('required');
                }

                // VAT
                if (vatField) {
                    vatField.style.display = 'none';
                    vat.value = ''; // reset value
                    vat.classList.add('hide-field')
                    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 (invoiceTypeField) {
                    invoiceTypeField.style.display = 'block';
                }

                // TAX
                if (taxCodeField) {
                    taxCodeField.style.display = 'block';
                    if (taxCode) {
                        taxCode.classList.remove('hide-field')
                        taxCode.setAttribute('required', 'required');
                    }
                }

                // VAT
                if (vatField) {
                    vatField.style.display = 'block';
                    if (vat) {
                        vat.classList.remove('hide-field')
                        vat.setAttribute('required', 'required');
                    }
                }
            } else {

                // TAX
                if (taxCodeField) {
                    if (taxCode) {
                        taxCode.removeAttribute('required');
                    }
                }

                // VAT
                if (vatField) {
                    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';
                        vat.classList.add('hide-field')
                        vat.removeAttribute('required');
                    }
                    if (taxCode) {
                        taxCodeField.style.display = 'block';
                        taxCode.classList.remove('hide-field')
                    }
                    break;
                case 'company':
                case 'freelance':
                    if (vat) {
                        vatField.style.display = 'block';
                        vat.classList.remove('hide-field')
                    }
                    if (taxCode && 'on' === wc_el_inv_invoice.disable_cf) {
                        // TAX
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                        }
                        if (taxCode) {
                            taxCode.classList.add('hide-field')
                            taxCode.removeAttribute('required');
                            clearTaxCodeValidationState(taxCode);
                        }
                    }
                    break;
                case '':
                    if (taxCodeField) {
                        taxCodeField.style.display = 'none';
                        taxCode.classList.add('hide-field')
                    }
                    if (sdiField) {
                        sdiField.style.display = 'none';
                        sdi.classList.add('hide-field')
                    }
                    if (vatField) {
                        vatField.style.display = 'none';
                        vat.classList.add('hide-field')
                    }
                    break;
            }

            if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                clearTaxCodeValidationState(taxCode);
            }

            // 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('pms_billing_company');
            if (companyFiled) {
                console.log('[POP-CZM] toggleBillingCompany');
                if ('company' === type) {
                    companyFiled.setAttribute('required', 'required');
                } else {
                    companyFiled.removeAttribute('required');
                }
            }
        }

        /**
         * Switch Type and set args in input
         *
         * @since 1.0.0
         *
         * @param type
         * @param ev
         */
        function switchType(type, ev)
        {
            var country = document.getElementById('pms_billing_country');
            if (!country) {
                console.log('[POP-CZM] switchType: missing country, aborting.');
                return;
            }
            var choiceTypeField = document.querySelector('.pms-pms-choice-type');
            var invoiceTypeField = document.querySelector('.pms-pms-invoice-type');
            var choiceType = document.getElementById('pms_choice_type');
            var sdi = document.getElementById('pms_sdi_type');
            var sdiField = document.querySelector('.pms-pms-sdi-type');
            var vat = document.getElementById('pms_vat_number');
            var vatField = document.querySelector('.pms-pms-vat-number');
            var taxCode = document.getElementById('pms_tax_code');
            var taxCodeField = document.querySelector('.pms-pms-tax-code');
            if (taxCode) {
                clearTaxCodeValidationState(taxCode);
            }

            // 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 = '';
                    setVatPrefix();
                }
                if (taxCode) {
                    taxCode.value = '';
                }
            }

            // Initialize display fields
            if (choiceTypeField) {
                choiceTypeField.style.display = 'block';
            }

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

            if (taxCodeField) {
                taxCodeField.style.display = 'block';
                if (taxCode) {
                    taxCode.classList.remove('hide-field');
                }
            }
            if (vatField) {
                vatField.style.display = 'block';
                if (vat) {
                    vat.classList.remove('hide-field');
                }
            }

            switch (type) {
                default:
                case 'private':
                    // 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'));
                        }

                        if (taxCodeField) {
                            taxCodeField.style.display = 'block';
                        }
                        taxCode.classList.remove('hide-field')
                        taxCode.setAttribute('required', 'required');
                    }
                    // SDI check
                    if (sdiField) {
                        // SDI
                        sdiField.style.display = 'none';
                        if (sdi) {
                            sdi.value = ''; // reset value
                            sdi.classList.add('hide-field')
                            sdi.removeAttribute('required');
                        }
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'none';
                        if (vat) {
                            vat.classList.add('hide-field')
                            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';
                            if (sdi) {
                                sdi.classList.remove('hide-field')
                                sdi.setAttribute('required', 'required');
                            }
                        } else {
                            sdiField.style.display = 'none';
                            if (sdi) {
                                sdi.classList.add('hide-field')
                                sdi.removeAttribute('required');
                            }
                        }
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'block';
                        if (vat) {
                            vat.classList.remove('hide-field')
                            vat.setAttribute('required', 'required');
                        }
                    }

                    // TAX-CODE
                    if (taxCode && 'on' !== wc_el_inv_invoice.disable_cf) {
                        taxCodeField.style.display = 'block';
                        taxCode.classList.remove('hide-field')
                        taxCode.setAttribute('required', 'required');
                    } else if (taxCode && 'on' === wc_el_inv_invoice.disable_cf) {
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                            taxCode.classList.add('hide-field')
                            taxCode.removeAttribute('required');
                        }
                        clearTaxCodeValidationState(taxCode);
                    }

                    if (taxCode) {
                        clearTaxCodeValidationState(taxCode);
                    }
                    break;
                case '':
                    if (taxCodeField) {
                        taxCodeField.style.display = 'none';
                        if (taxCode) {
                            taxCode.classList.add('hide-field');
                            clearTaxCodeValidationState(taxCode);
                        }
                    }
                    if (sdiField) {
                        sdiField.style.display = 'none';
                        if (sdi) {
                            sdi.classList.add('hide-field');
                        }
                    }
                    if (vatField) {
                        vatField.style.display = 'none';
                        if (vat) {
                            vat.classList.add('hide-field');
                        }
                    }
                    break;
            }

            if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                clearTaxCodeValidationState(taxCode);
            }

            // Logic for displaying the fields if set to "receipt" at the change of state.
            if (choiceType) {
                var 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('pms_choice_type');

            initSelect2();

            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 invoiceType = document.getElementById('pms_invoice_type');
            var invoiceTypeField = document.querySelector('.pms-pms-invoice-type');
            var sdiField = document.querySelector('.pms-pms-sdi-type');
            var vatField = document.querySelector('.pms-pms-vat-number');
            var taxCodeField = document.querySelector('.pms-pms-tax-code');
            var sdi = document.getElementById('pms_sdi_type');
            var vat = document.getElementById('pms_vat_number');
            var taxCode = document.getElementById('pms_tax_code');

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

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

            switch (type) {
                case'invoice':
                    var country = document.getElementById('pms_billing_country');
                    // 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.classList.remove('hide-field')
                                    vat.value = '';
                                    setVatPrefix();
                                }
                            }
                            // Display Only IT
                            if ('IT' === country.value) {
                                if (sdi) {
                                    sdiField.style.display = 'block';
                                    if ('load' !== ev.type) {
                                        sdi.classList.remove('hide-field')
                                        sdi.value = '';
                                    }
                                }
                            }
                            if (taxCode) {
                                taxCodeField.style.display = 'block';
                                if ('load' !== ev.type) {
                                    taxCode.classList.remove('hide-field')
                                    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 (vat) {
                        vat.value = 'IT11111111111';
                        vatField.style.display = 'none';
                        vat.classList.add('hide-field')
                    }
                    if (sdi) {
                        sdi.value = '1111111';
                        sdiField.style.display = 'none';
                        sdi.classList.add('hide-field')
                    }
                    if (taxCode) {
                        taxCode.value = 'XXXXXX00L00L000X';
                        taxCodeField.style.display = 'none';
                        taxCode.classList.add('hide-field')
                        clearTaxCodeValidationState(taxCode);
                    }
                    invoiceTypeField.style.display = 'none';
                    break;
                // Reset fields
                case'reset':
                    // Reset billing company required
                    toggleBillingCompany(null);
                    if (vat) {
                        vat.value = '';
                        setVatPrefix();
                    }
                    if (sdi) {
                        sdi.value = '';
                    }
                    if (taxCode) {
                        taxCode.value = '';
                        clearTaxCodeValidationState(taxCode);
                    }
                    break;
                default:
                    break;
            }
        }

        // Set required fields
        setRequired();

        /**
         * setVatPrefix
         */
        function setVatPrefix()
        {
            var vat = document.getElementById('pms_vat_number');
            var country = document.getElementById('pms_billing_country');
            var prefix = country.value;
            // Removes any existing prefix and adds the new prefix
            vat.value = prefix + vat.value.replace(/^[A-Za-z]*/, '');
        }

        /**
         * CF check
         */
        function cfCheck()
        {
            var name = document.getElementById('pms_billing_first_name');
            var lastName = document.getElementById('pms_billing_last_name');
            var taxCode = document.getElementById('pms_tax_code');
            var invoiceType = document.getElementById('pms_invoice_type');
            var checkCodeFinal = false;
            var computeInverse = {};

            if (!taxCode || !name || !lastName || !invoiceType) {
                return;
            }

            if (taxCode.classList.contains('hide-field')) {
                return;
            }

            // 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("");
                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('pms_billing_first_name').value,
                            surname: document.getElementById('pms_billing_last_name').value,
                            gender: computeInverse.gender,
                            birthday: computeInverse.birthday,
                            birthplace: computeInverse.birthplace
                        };
                        var cfDataFinal = new CodiceFiscale(args);
                        console.log('[POP-CZM] CodiceFiscale di ' + args.name + ' ' + args.surname, cfDataFinal);
                        checkCodeFinal = (0 === cfDataFinal.code.indexOf(computeInverse.surname + computeInverse.name));
                    } else {
                        checkCodeFinal = false;
                    }
                    console.log('[POP-CZM] Check CF:', checkCodeFinal);
                    if (!checkCodeFinal) {
                        setTimeout(function () {
                            var cfMessage = taxCode.nextElementSibling;
                            if (cfMessage) {
                                cfMessage.remove();
                            }

                            //taxCode.value = '';
                            console.log('[POP-CZM] pop_invalid_tax_code', wc_el_inv_invoice.pop_invalid_tax_code)
                            taxCode.insertAdjacentHTML('afterend',
                                "<p class='no-valid-cf'><small>(*) <b>" + CF + "</b> " + wc_el_inv_invoice.invalid_tax_code + "</small></p>"
                            );
                            taxCode.setCustomValidity(wc_el_inv_invoice.pop_invalid_tax_code);
                        }, 200);
                        return false;
                    } else {
                        clearTaxCodeValidationState(taxCode);
                        return true;
                    }
                } else {
                    clearTaxCodeValidationState(taxCode);
                }
            })
        }

        /**
         * Vat check
         */
        function vatCheck()
        {
            var vat = document.getElementById('pms_vat_number');
            var country = document.getElementById('pms_billing_country');
            var invoiceType = document.getElementById('pms_invoice_type');

            if (vat.classList.contains('hide-field')) {
                return;
            }

            $(document).ready(function () {
                setVatPrefix();
            });

            $(country).on('change', function () {
                setVatPrefix();
            });

            $(invoiceType).on('change', function () {
                setVatPrefix();
            });

            $(vat).on('change', function (evt) {
                var success = document.querySelectorAll('.pms_field-success-wrapper');
                setTimeout(function (){
                    success.forEach(function (item, i) {
                        item.remove();
                    })
                }, 500)
                if (vatRegex.test(vat.value)) {
                    var errorP = document.querySelector('.pms_field-errors-wrapper.pms-is-js');
                    if (errorP) {
                        errorP.remove();
                    }
                }
            });

            $(vat).on('input', function () {
                var prefix = country.value;
                if (vat.value.indexOf(prefix) !== 0) {
                    vat.value = prefix + vat.value.slice(prefix.length);
                }
                if (vatRegex.test(vat.value)) {
                    vat.setCustomValidity("");
                } else {
                    vat.setCustomValidity(wc_el_inv_invoice.pop_invalid_vat_number);
                }
                vat.reportValidity();
            });

            $(vat).on('keydown', function (event) {
                var prefix = country.value;
                if (vat.selectionStart < prefix.length) {
                    event.preventDefault();
                }
            });
        }

        /**
         * Sdi check
         */
        function sdiCheck()
        {
            var sdi = document.getElementById('pms_sdi_type');
            if (!sdi) {
                return;
            }
            if (sdi.classList.contains('hide-field')) {
                return;
            }

            $(sdi).on('change', function () {
                if (sdiRegex.test(sdi.value) || pecRegex.test(sdi.value)) {
                    sdi.setCustomValidity("");
                } else {
                    console.log('[POP-CZM] pop_invalid_sdi_pec', wc_el_inv_invoice.pop_invalid_sdi_pec)
                    sdi.setCustomValidity(wc_el_inv_invoice.pop_invalid_sdi_pec);
                }
                sdi.reportValidity();
            });
        }

        // vatCheck on ajax complete action pms_tax_validate_vat
        $(document).ajaxComplete(function (event, xhr, settings) {
            var vat = document.getElementById('pms_vat_number');
            var urlParams = new URLSearchParams(settings.data);
            if (urlParams.has('action')) {
                var action = urlParams.get('action');
                if (action === 'pms_tax_validate_vat') {
                    vatCheck();
                    vat.dispatchEvent(new Event('change'));
                }
            }
        });

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

            // Default
            var invoiceType = document.getElementById('pms_invoice_type');
            var country = document.getElementById('pms_billing_country');
            var taxCode = document.getElementById('pms_tax_code');
            var sdi = document.getElementById('pms_sdi_type');
            var vat = document.getElementById('pms_vat_number');

            if (!invoiceType) {
                return false;
            }

            if (!country) {
                return false;
            }

            // Required and in not UE country
            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);
            }

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

            // 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 &&
                !taxCode.classList.contains('hide-field') &&
                'on' === wc_el_inv_invoice.active_js_cf_check
            ) {
                cfCheck();
                taxCode.dispatchEvent(new Event('change'));
            }

            // VAT number validation
            if (country &&
                'IT' === country.value &&
                vat.classList.contains('hide-field')
            ) {
                vatCheck();
                vat.dispatchEvent(new Event('change'));
            }

            // Validation of the unique SDI code
            if (country &&
                'IT' === country.value &&
                sdi &&
                !sdi.classList.contains('hide-field')
            ) {
                sdiCheck();
                sdi.dispatchEvent(new Event('change'));
            }

            // Validation on submit
            if (country && 'IT' === country.value && (vat || sdi || taxCode)) {
                var submits = [
                    document.getElementsByName('pms_change_subscription')[0],
                    document.getElementsByName('pms_new_subscription')[0],
                ]
                submits.forEach(function (submit) {
                    if (submit) {
                        submit.addEventListener('submit', function (event) {
                            console.log('[POP-CZM] submit event type:', event.type)
                            if (taxCode && !taxCode.classList.contains('hide-field') && 'IT' === country.value) {
                                cfCheck();
                            }
                            if (!vat.classList.contains('hide-field')) {
                                vatCheck();
                            }
                            if (sdi && !sdi.classList.contains('hide-field') && 'IT' === country.value) {
                                sdiCheck();
                            }

                            if (!this.checkValidity()) {
                                event.preventDefault();
                            }
                        })
                    }
                })
            }
        })

    }(jQuery, window.wc_el_inv_invoice)
);
