window.Webflow ||= []; window.Webflow.push(() => { const countryToCurrency = {}; const countryFlags = {}; const compareButtons = document.querySelectorAll('.cc-compare'); const fromCountrySelects = document.querySelectorAll('.cc-country-from'); const toCountrySelects = document.querySelectorAll('.cc-country-to'); function parseCollectionList() { const listItems = document.querySelectorAll('.c-countries-collection-list .w-dyn-item'); listItems.forEach(function (item) { populateMaps(item); }); populateSelectOptions(); setInitialValues(); updateElementsFromURL(); setFlagFromURL(); } // function to populate maps function populateMaps(item) { const countryElem = item.querySelector('.c-country-name'); const currencyCodeElem = item.querySelector('.c-currency-code'); const currencySymbolElem = item.querySelector('.c-currency-symbol'); const countryFlagElem = item.querySelector('.c-country-flag'); if (countryElem && currencyCodeElem && currencySymbolElem && countryFlagElem) { const country = countryElem.innerText.trim(); countryToCurrency[country] = { code: currencyCodeElem.innerText.trim(), symbol: currencySymbolElem.innerText.trim(), }; countryFlags[country] = countryFlagElem.innerText.trim(); } } // Function to populate select options function populateSelectOptions() { fromCountrySelects.forEach((fromSelect) => { fromSelect.innerHTML = ''; for (const country in countryToCurrency) { fromSelect.innerHTML += ``; } }); toCountrySelects.forEach((toSelect) => { // Get the current URL path const path = window.location.pathname; const sendMoneyIndex = path.indexOf('/send-money'); let countryName = ''; if (sendMoneyIndex !== -1) { countryName = path.substring(sendMoneyIndex + 12).replace(/-/g, ' '); if (countryName) { toSelect.innerHTML = ``; } else { toSelect.innerHTML = ''; } } else { toSelect.innerHTML = ''; } for (const country in countryToCurrency) { if (country !== countryName) { toSelect.innerHTML += ``; } } }); } // Function to set initial values function setInitialValues() { const countryFromFlags = document.querySelectorAll('.cc-country-from-flag'); const countryToFlags = document.querySelectorAll('.cc-country-to-flag'); const currencySymbols = document.querySelectorAll('.cc-currency-symbol'); countryFromFlags.forEach((flagElement) => { flagElement.innerText = countryFlags['United Kingdom'] || ':gb:'; }); countryToFlags.forEach((flagElement) => { flagElement.innerText = countryFlags['Spain'] || ':es:'; }); currencySymbols.forEach((symbolElement) => { const symbol = countryToCurrency['United Kingdom'] ? countryToCurrency['United Kingdom'].symbol : '£'; symbolElement.innerText = symbol; }); } // function to update elements based on URL path function updateElementsFromURL() { const urlPath = window.location.pathname; const urlSearchParams = new URLSearchParams(window.location.search); let amount = urlSearchParams.get('amount'); if (urlPath.startsWith('/transfer-money/')) { const pathParts = urlPath.split('/'); if (pathParts.length >= 3) { const countries = pathParts[2].split('-to-'); if (countries.length === 2) { const countryFrom = formatCountryName(countries[0]); const countryTo = formatCountryName(countries[1]); // Check if amount is not present or empty, set default to 1000 if (!amount) { amount = '1000'; urlSearchParams.set('amount', amount); window.history.replaceState(null, null, urlPath + '?' + urlSearchParams.toString()); } document .querySelectorAll('.cc-amount') .forEach((elem) => (elem.value = amount || '1000')); // Update currency symbols const currencySymbolFrom = countryToCurrency[countryFrom]?.symbol || ''; const currencySymbolTo = countryToCurrency[countryTo]?.symbol || ''; document.querySelectorAll('.cc-currency-symbol').forEach((elem) => { elem.innerText = currencySymbolFrom; }); const fromCurrencyCode = countryToCurrency[countryFrom]?.code; const toCurrencyCode = countryToCurrency[countryTo]?.code; if (!fromCurrencyCode || !toCurrencyCode) { return; } document .querySelectorAll('.cc-country-from-flag-js, .cc-country-from-flag') .forEach((elem) => (elem.innerText = countryFlags[countryFrom] || '')); document .querySelectorAll('.cc-country-to-flag-js, .cc-country-to-flag') .forEach((elem) => (elem.innerText = countryFlags[countryTo] || '')); document .querySelectorAll('.cc-amount-js') .forEach((elem) => (elem.innerText = amount || '0.00')); document .querySelectorAll('.cc-currency-code-from-js') .forEach((elem) => (elem.innerText = countryToCurrency[countryFrom]?.code || 'EUR')); document .querySelectorAll('.cc-currency-code-to-js') .forEach((elem) => (elem.innerText = countryToCurrency[countryTo]?.code || 'EUR')); fetchCurrencyAPIAndUpdate( countryToCurrency[countryFrom]?.code, countryToCurrency[countryTo]?.code ); document.querySelectorAll('.cc-amount').forEach((elem) => (elem.value = amount || '')); document .querySelectorAll('.cc-country-from') .forEach((elem) => (elem.value = countryFrom)); document.querySelectorAll('.cc-country-to').forEach((elem) => (elem.value = countryTo)); document.querySelectorAll('.cc-compare').forEach((elem) => (elem.innerText = 'Update')); } } } } // Function to extract country name from URL and update flag function setFlagFromURL() { const path = window.location.pathname; const sendMoneyIndex = path.indexOf('/send-money/'); if (sendMoneyIndex !== -1) { const countryNameFromURL = path.substring(sendMoneyIndex + 12).replace(/-/g, ' '); const formattedCountryName = formatCountryName(countryNameFromURL); updateToCountryFlag(formattedCountryName); // Optionally set the dropdown value to match the URL toCountrySelects.forEach((select) => { select.value = formattedCountryName; }); } } setFlagFromURL(); // Call this function when the page loads function formatCountryName(urlCountry) { return urlCountry .replace(/-/g, ' ') .split(' ') .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(' '); } // function to update country to flag function updateToCountryFlag(countryName) { const flag = countryFlags[countryName] || ' '; document.querySelectorAll('.cc-country-to-flag').forEach((elem) => { elem.innerText = flag; }); } toCountrySelects.forEach((toSelect) => { toSelect.addEventListener('change', function () { const selectedCountry = formatCountryName(this.value); updateToCountryFlag(selectedCountry); }); }); // function to display an error function showError(message, parentForm) { const errorDisplay = parentForm.querySelector('.cc-js-error'); errorDisplay.style.display = 'block'; errorDisplay.innerText = message; setTimeout(() => { errorDisplay.style.display = 'none'; }, 3000); } // function to calculate amount and exchange rate + displaying data function calculateAndDisplayTotal() { const toCountry = document.querySelector('.cc-country-to').value; // Get the selected 'from' country const currencyCode = countryToCurrency[toCountry]?.code || ''; // Get the currency symbol const currencySymbol = countryToCurrency[toCountry]?.symbol || ''; // Get the currency symbol // Update all elements with the class 'cc-currency-symbol-from-js' with the currency symbol document.querySelectorAll('.cc-currency-symbol-from-js').forEach((elem) => { elem.innerText = currencyCode; }); const collectionItems = document.querySelectorAll('.c-collection-item-block'); collectionItems.forEach(function (item) { // Find all exchange rate and mid-rate elements in this item const exchangeRateElements = item.querySelectorAll('.cc-exchange-rate-js'); const midRateElements = item.querySelectorAll('.cc-mid-rate-js'); const feesElements = item.querySelectorAll('.cc-fees-js'); const amountElements = item.querySelectorAll('.cc-amount-js'); const totalAmountElements = item.querySelectorAll('.cc-amount-total-js'); // Use the first instance of each required class for calculations const exchangeRate = parseFloat(exchangeRateElements[0]?.innerText) || 0; const percent = parseFloat(midRateElements[0]?.innerText) || 0; const fees = parseFloat(feesElements[0]?.innerText) || 0; const amount = parseFloat(amountElements[0]?.innerText) || 1000; // Default to 1000 if not available if (isNaN(exchangeRate) || isNaN(amount)) { console.error('Invalid amount or exchange rate in an item'); return; } // Adjusted Exchange Rate Calculation const adjustedExchangeRate = exchangeRate * (1 - percent / 100); // Update all exchange rate elements exchangeRateElements.forEach(function (elem) { elem.innerText = adjustedExchangeRate.toFixed(4); }); // Total Amount Calculation const total = fees > 0 ? adjustedExchangeRate * amount - fees : adjustedExchangeRate * amount; // Update all total amount elements totalAmountElements.forEach(function (elem) { elem.innerText = total.toFixed(2); }); item.setAttribute('data-label-amount', total.toFixed(2)); item.setAttribute('data-currency-symbol', currencySymbol || currencyCode); }); } calculateAndDisplayTotal(); // Call this function on page load or when the list is updated // fetch data from currency API function fetchCurrencyAPIAndUpdate(fromCurrencyCode, toCurrencyCode) { if (!fromCurrencyCode || !toCurrencyCode) { return; } fetch( `https://api.currencyapi.com/v3/latest?apikey=fca_live_EdmYK5QBoIvqiDdz8xJsTAEJP60teoGvyEmsSomz&base_currency=${fromCurrencyCode}` ) .then((response) => { if (!response.ok) throw new Error('Network response was not ok.'); return response.json(); }) .then((data) => { if (data && data.data && data.data[toCurrencyCode]) { const lastUpdatedISO = data.data[toCurrencyCode]?.last_updated_at; // Define options for date formatting const dateOptions = { year: 'numeric', month: 'long', day: '2-digit' }; // Parse the ISO date string and format it const lastUpdated = lastUpdatedISO ? new Date(lastUpdatedISO).toLocaleDateString('en-US', dateOptions) : new Date().toLocaleDateString('en-US', dateOptions); document .querySelectorAll('.cc-last-updated-js') .forEach((elem) => (elem.innerText = lastUpdated)); // exchange rate document .querySelectorAll('.cc-exchange-rate-js') .forEach( (elem) => (elem.innerText = data.data[toCurrencyCode].value.toFixed(4) || '0.0') ); } calculateAndDisplayTotal(); // Add this line to update the total }) .catch((error) => { console.error('Error fetching currency data:', error); }); } // country from fromCountrySelects.forEach(function (select) { select.addEventListener('change', function () { const parentForm = this.closest('.cc-form-js'); const country = this.value; const currencySymbol = countryToCurrency[country] ? countryToCurrency[country].symbol : '£'; const flag = countryFlags[country] || ''; parentForm.querySelector('.cc-currency-symbol').innerText = currencySymbol; parentForm.querySelector('.cc-country-from-flag').innerText = flag; }); }); // compare button compareButtons.forEach(function (button) { button.addEventListener('click', function (e) { e.preventDefault(); this.innerText = 'In progress...'; const parentForm = this.closest('.cc-form-js'); const amountInput = parentForm.querySelector('.cc-amount'); const fromCountrySelect = parentForm.querySelector('.cc-country-from'); const toCountrySelect = parentForm.querySelector('.cc-country-to'); const amount = amountInput.value; const fromCountry = fromCountrySelect.value; const toCountry = toCountrySelect.value; const fromCurrencyCode = countryToCurrency[fromCountry]?.code; const toCurrencyCode = countryToCurrency[toCountry]?.code; if (amount.trim() === '') { showError('Please enter a desired amount', parentForm); amountInput.focus(); this.innerText = 'Compare'; return; } const parsedAmount = parseFloat(amount); if (isNaN(parsedAmount) || !fromCurrencyCode || !toCurrencyCode) { showError('Invalid country selection', parentForm); this.innerText = 'Compare'; return; } fetch( `https://api.currencyapi.com/v3/latest?apikey=fca_live_EdmYK5QBoIvqiDdz8xJsTAEJP60teoGvyEmsSomz&base_currency=${fromCurrencyCode}` ) .then((response) => { if (!response.ok) throw new Error('Network response was not ok.'); return response.json(); }) .then((data) => { if (!data.data || !data.data[toCurrencyCode]) throw new Error('Rate missing in response'); const rate = data.data[toCurrencyCode].value; const convertedAmount = rate * parsedAmount; setTimeout(() => { window.location.href = `${window.location.origin}/transfer-money/${fromCountry.replace(/\s+/g, '-').toLowerCase()}-to-${toCountry.replace(/\s+/g, '-').toLowerCase()}?amount=${amount}`; }, 2000); }) .catch((error) => { showError(error.message || 'Error in conversion', parentForm); this.innerText = 'Compare'; }); }); }); setTimeout(parseCollectionList, 1000); });