{% include 'bold-common' %}
{{ 'bold-common.js' | asset_url | script_tag }}
{{ 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js' | script_tag }}
{{ 'https://use.fontawesome.com/5258675980.js' | script_tag }}
{{ 'bold-currency-converter.init.js' | asset_url | script_tag }}
{{ 'flags.min.css' | asset_url | stylesheet_tag }}
{{ 'currency-picker.css' | asset_url | stylesheet_tag}}
<script type="application/javascript">
const BOLD_CART_ITEM_PRICE = '<span class="Bold-theme-hook-DO-NOT-DELETE bold_cart_item_price" style="display:none !important;"></span>';
const BOLD_CART_ITEM_QTY = '<span class="Bold-theme-hook-DO-NOT-DELETE bold_cart_item_qty" style="display:none !important;"></span>';
const BOLD_CART_TOTAL = '<span class="Bold-theme-hook-DO-NOT-DELETE bold_cart_total" style="display:none !important;"></span>';
const BOLD_CART_ITEM_TOTAL = '<span class="Bold-theme-hook-DO-NOT-DELETE bold_cart_item_total" style="display:none !important;"></span>';
var rateInfo = {};
var currencyListShow = false;
var defaultShopCurrency = '';
BOLDCURRENCY.converter = {
requestRates: function ( callback, originalVals) {
BOLD.helpers.js.get("https://mc.boldapps.net/{{shop.permanent_domain}}/rates")
.then(
returnedValue => {
callback(returnedValue, originalVals)
})
.catch(err => {
var currencyPicker = document.getElementById('currency-picker-current-currency');
currencyPicker.className = '';
currencyPicker.classList.add("hidden");
});
},
getRatesAndConvert: function (data, originalVals) {
rateInfo = data.currencies;
BOLDCURRENCY.moneyFormats = data.moneyFormat;
defaultShopCurrency = data.defaultShopCurrency;
console.log(BOLDCURRENCY.currencyCookie.read());
BOLDCURRENCY.currentCurrency = BOLDCURRENCY.currencyCookie.read() !== '' ? BOLDCURRENCY.currencyCookie.read() : defaultShopCurrency;
data.geoLocate === true ?
BOLDCURRENCY.converter.geoLocate(originalVals) :
BOLDCURRENCY.converter.convertAll(rateInfo, originalVals, defaultShopCurrency, BOLDCURRENCY.currentCurrency);
BOLDCURRENCY.converter.populateSelect(rateInfo);
},
populateSelect: function(data) {
var currencyPicker = document.getElementById('currency-picker');
var currentCurrencyDisplay = document.getElementById('currency-picker-current-currency');
BOLDCURRENCY.converter.setCurrentCurrency();
if (hasClass(currentCurrencyDisplay, 'loading-currency-widget')) {
removeClass(currentCurrencyDisplay, 'loading-currency-widget')
}
var objKeys = Object.keys(data);
for(var i = 0; i < objKeys.length; i++) {
var li = document.createElement('li');
var countryCode = BOLDCURRENCY.currencyCodesAndCountryCodes[objKeys[i]];
var spanFlag = document.createElement('span');
spanFlag.style.backgroundImage = "url('{{ 'flags.png' | asset_url }}')";
spanFlag.className = "flag flag-" + countryCode.toLowerCase();
li.style.position = 'relative';
li.className = 'currency-dropdown-option';
li.innerHTML = objKeys[i];
li.dataset.value = objKeys[i];
li.appendChild(spanFlag);
currencyPicker.appendChild(li);
}
currencyPicker.value = BOLDCURRENCY.currencyCookie.read() !== null ? BOLDCURRENCY.currencyCookie.read() : defaultShopCurrency;
},
convertAll: function (rateData, originalValues, oldCurrency, newCurrency, format){
var boldCartItemPrices = document.getElementsByClassName('bold_cart_item_price');
var valuesWithRulesApplied = [];
var moneyElements = document.getElementsByClassName('money');
var isCartPage = window.location.href.indexOf("/cart") > -1;
var cents = 0;
var oldFormat = BOLDCURRENCY.moneyFormats[oldCurrency][format || BOLDCURRENCY.format] || '{{amount}}';
var newFormat = BOLDCURRENCY.moneyFormats[newCurrency][format || BOLDCURRENCY.format] || '{{amount}}';
var totalsPerRow = 0;
var newFormattedAmount = '';
BOLDCURRENCY.currentCurrency = newCurrency;
if (isCartPage) {
BOLD.common.cartDoctor.registerPriceMod('BOLDCURRENCYCONVERTER', function(price){
if (oldFormat.indexOf('amount_no_decimals') !== -1) {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(price, 10), newCurrency);
}
else if (oldCurrency === 'JOD' || oldCurrency == 'KWD' || oldCurrency == 'BHD') {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(price*10, 10), newCurrency);
}
else {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(price, 10), newCurrency);
}
cents = BOLDCURRENCY.converter.applyRules(cents, rateData[BOLDCURRENCY.currentCurrency].rules, rateData[BOLDCURRENCY.currentCurrency].significantDigits);
return cents;
});
BOLD.common.cartDoctor.updateCart()
} else {
for(var i = 0; i < moneyElements.length; i++) {
var isItemPrice = hasClass(moneyElements[i].parentElement.firstChild, '.bold_cart_item_price' ) || hasId(moneyElements[i].parentElement, 'ProductPrice');
var isCompareToPrice = hasId(moneyElements[i].parentElement, '#ComparePrice') || moneyElements[i].parentElement.nextSibling.innerText === 'Sale price';
if (oldFormat.indexOf('amount_no_decimals') !== -1) {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(originalValues[i]*100, 10), newCurrency);
}
else if (oldCurrency === 'JOD' || oldCurrency == 'KWD' || oldCurrency == 'BHD') {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(originalValues[i]/10, 10), newCurrency);
}
else {
cents = BOLDCURRENCY.converter.convertPrice(parseInt(originalValues[i]*100, 10), newCurrency);
}
cents = BOLDCURRENCY.converter.applyRules(cents, rateData[BOLDCURRENCY.currentCurrency].rules, rateData[BOLDCURRENCY.currentCurrency].significantDigits);
valuesWithRulesApplied.push(cents);
newFormattedAmount = BOLDCURRENCY.converter.formatMoney(cents, newFormat);
moneyElements[i].innerHTML = newFormattedAmount;
}
}
BOLDCURRENCY.currencyCookie.write(newCurrency);
},
convertPrice: function (valueToConvert, newCurrency) {
var rateTo = rateInfo[newCurrency].rate;
return valueToConvert * rateTo;
},
applyRules: function (value, rules, significantDigits) {
for (var k = 0; k <= significantDigits; k++) {
var modulus = Math.pow(10, significantDigits - k);
let matchedRule = _.find(rules, function(rule){
return value % modulus / 100 >= rule.low && value % modulus / 100 <= rule.high
});
if(typeof matchedRule !== 'undefined') {
let baseComponent = value - value % modulus;
return baseComponent + matchedRule.value * 100 ;
}
}
return value;
},
getOriginalValues: function (){
var originalValues = [];
var moneyElements = document.getElementsByClassName('money');
var comparePrice = document.getElementById('ComparePrice');
var productPrice = document.getElementById('ProductPrice');
for(var i = 0; i < moneyElements.length; i++) {
originalValues.push(moneyElements[i].innerText.replace(/[^0-9.]/g, ''));
}
if (productPrice !== null){
originalValues.push(parseInt(productPrice.innerText.replace(/[^0-9.]/g, '')));
}
if (comparePrice !== null){
originalValues.push(parseInt(comparePrice.innerText.replace(/[^0-9.]/g, '')));
}
return originalValues;
},
getCompareToValues: function () {
var compareToValues = [];
var moneyElements = document.getElementsByClassName('money');
for(var i = 0; i < moneyElements.length; i++) {
if(moneyElements[i].parentElement.nextSibling.innerText == 'Sale price') {
compareToValues.push(moneyElements[i].innerText.replace(/[^0-9.]/g, ''));
}
}
return compareToValues;
},
formatMoney: function (cents, format) {
if (typeof cents == 'string') {
cents = cents.replace('.','');
}
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var formatString = format || '$\{\{amount\}\}';
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) {
return 0;
}
number = parseFloat((number/100.0)).toFixed(2);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1].length === 1 || parts[1].length > 2 ? Math.floor(parts[1]) * 10 : parts[1];
return precision === 0 ? dollars : dollars + decimal + cents;
}
switch(formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
},
setCurrentCurrency: function () {
var currencyPickerCurrentCurrency = document.getElementById('currency-picker-current-currency');
var currentCurrencySpan = document.getElementById('current-currency-span');
var currencyCurrencyName = document.getElementById('current-currency-name');
var currentCountryCode = BOLDCURRENCY.currencyCodesAndCountryCodes[BOLDCURRENCY.currentCurrency];
currentCurrencySpan.className = "flag flag-" + currentCountryCode.toLowerCase();
currencyCurrencyName.innerHTML = BOLDCURRENCY.currentCurrency;
},
geoLocate(originalVals) {
if(document.cookie.indexOf('initialized') === -1) {
let now = new Date();
let time = now.getTime();
time += 900 * 1000;
now.setTime(time);
document.cookie =
'initialized=' + true +
'; expires=' + now.toUTCString() +
'; path=/';
BOLD.helpers.js.get( 'https://shappify-cdn.com/cf_helper/get_country.php')
.then(
returnedValue => {
let currencyAndCountryCodes = BOLDCURRENCY.currencyCodesAndCountryCodes;
for(var key in currencyAndCountryCodes) {
if(typeof rateInfo[key] !== 'undefined' && currencyAndCountryCodes[key] === returnedValue){
BOLDCURRENCY.currentCurrency = key;
BOLDCURRENCY.converter.setCurrentCurrency();
}
}
BOLDCURRENCY.converter.convertAll(rateInfo, originalVals, defaultShopCurrency, BOLDCURRENCY.currentCurrency);
});
} else {
BOLDCURRENCY.converter.convertAll(rateInfo, originalVals, defaultShopCurrency, BOLDCURRENCY.currentCurrency);
}
},
openCurrencyList: function () {
var currencyList = document.getElementById('currency-picker');
var currencyPickerChevron = document.getElementById('currency-picker-chevron');
removeClass(currencyPickerChevron, ' fa-chevron-down');
addClass(currencyPickerChevron, ' fa-chevron-up');
currencyListShow = true;
removeClass(currencyList, 'hidden');
},
closeCurrencyList: function () {
var currencyList = document.getElementById('currency-picker');
var currencyPickerChevron = document.getElementById('currency-picker-chevron');
removeClass(currencyPickerChevron, ' fa-chevron-up');
addClass(currencyPickerChevron, ' fa-chevron-down');
currencyListShow = false;
addClass(currencyList, 'hidden');
},
initialize: function () {
var currentCurrencyDisplay = document.getElementById('currency-picker-current-currency');
var currencyPickerList = document.getElementById('currency-picker');
var originalValues = BOLDCURRENCY.converter.getOriginalValues();
var compareToValues = BOLDCURRENCY.converter.getCompareToValues();
BOLDCURRENCY.converter.requestRates(BOLDCURRENCY.converter.getRatesAndConvert, originalValues);
currentCurrencyDisplay.addEventListener('click', function(e){
if(currencyListShow) {
BOLDCURRENCY.converter.closeCurrencyList();
} else {
BOLDCURRENCY.converter.openCurrencyList();
}
});
currencyPickerList.addEventListener('click', function(e){
BOLDCURRENCY.converter.convertAll(rateInfo, originalValues, BOLDCURRENCY.currentCurrency, e.target.dataset.value);
BOLDCURRENCY.converter.closeCurrencyList();
BOLDCURRENCY.converter.setCurrentCurrency();
});
document.body.addEventListener('click', function (e) {
if(!hasId(e.target, 'currency-picker-current-currency')
&& !hasId(e.target, 'currency-picker')
&& !hasId(e.target, 'current-currency-name')
&& !hasId(e.target, 'current-currency-span')
&& !hasId(e.target, 'currency-picker-chevron')){
BOLDCURRENCY.converter.closeCurrencyList();
}
});
}
};
document.addEventListener("DOMContentLoaded", function(event) {
BOLDCURRENCY.converter.initialize();
});
function hasId(element, id) {
return (element.id).indexOf(id) > -1;
}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function addClass(element, className) {
if(!hasClass(element, className)) {
return element.className += className;
}
}
function removeClass(element, className) {
return element.className = element.className.replace(className, '');
}
</script>