document.addEventListener('DOMContentLoaded', function() {
    var inputs = document.querySelectorAll("[data-rsfp-phonenumber]");

    inputs.forEach(function(input){
        var options = JSON.parse(input.getAttribute('data-rsfp-phonenumber'));

        window.intlTelInput(input, {
            initialCountry: options['initialCountry'],
            geoIpLookup: function(success, failure) { return window.RSFormProGeoIpLookup(success, failure); },
            strictMode: true,
            i18n: {...{
                selectedCountryAriaLabel: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_SELECTEDCOUNTRYARIALABEL'),
                noCountrySelected: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_NOCOUNTRYSELECTED'),
                countryListAriaLabel: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_COUNTRYLISTARIALABEL'),
                searchPlaceholder: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_SEARCHPLACEHOLDER'),
                zeroSearchResults: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_ZEROSEARCHRESULTS'),
                oneSearchResult: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_ONESEARCHRESULT'),
                multipleSearchResults: RSFormPro.Translations.commonTranslate('COM_RSFORM_PHONENUMBER_MULTIPLESEARCHRESULTS'),
            }, ...options['i18n']},
            containerClass: 'rsfp-phone-input',
            showFlags: options['showFlags'],
            allowDropdown: options['allowDropdown'],
            onlyCountries: options['onlyCountries'],
            hiddenInput: function(telInputName) {
                var name = telInputName;
                var matches = name.match(/form\[(.*)\]/);
                if (matches.length > 0 && matches[1])
                {
                    name = matches[1];
                }
                return {
                    phone: "hidden_phone[" + name + ']',
                    country: "hidden_country_code[" + name + ']'
                }
            }
        });
    })
});

window.RSFormProGeoIpLookup = function(success, failure) {
    window.RSFormProGeoIpLookupNext(success, failure);
}

window.RSFormProGeoIpLookupNext = function(success, failure) {
    var fn = window.RSFormProGeoIpLookupServices.pop();
    if (typeof fn === 'function') {
        fn(success, failure)
    } else {
        failure();
    }
};

window.RSFormProGeoIpLookupServices = [
    function(success, failure) {
        fetch("https://ipapi.co/json")
            .then(function(res) {
                try {
                    return res.json();
                } catch (err) {
                    throw new TypeError('Not a JSON');
                }
            })
            .then(function(data) {
                if (typeof data.country_code !== 'undefined') {
                    success(data.country_code);
                } else {
                    throw new TypeError('No country code found');
                }
            })
            .catch(function() {
                window.RSFormProGeoIpLookupNext(success, failure);
            });
    },
    function(success, failure) {
        fetch('https://get.geojs.io/v1/ip/country')
            .then(function (res) {
                return res.text();
            })
            .then(function (data) {
                if (data.trim().length === 2) {
                    success(data.trim());
                } else {
                    throw new TypeError('No country code returned');
                }
            })
            .catch(function () {
                window.RSFormProGeoIpLookupNext(success, failure);
            });
    },
    function(success, failure) {
        fetch("https://ipwho.is/")
            .then(function(res) {
                try {
                    return res.json();
                } catch (err) {
                    throw new TypeError('Not a JSON');
                }
            })
            .then(function(data) {
                if (typeof data.country_code !== 'undefined') {
                    success(data.country_code);
                } else {
                    throw new TypeError('No country code found');
                }
            })
            .catch(function() {
                window.RSFormProGeoIpLookupNext(success, failure);
            });
    }
];

window.RSFormProGeoIpLookupServices.reverse();