const routes = require('../../../../../../public/js/fos_js_routes.json');
import Routing from '../../../../../../vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router.min.js';
import * as Toastr from 'toastr';
import Swal from "sweetalert2";

if ('NodeList' in window && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = function (callback, thisArg) {
        thisArg = thisArg || window;
        for (var i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
        }
    };
}
Routing.setRoutingData(routes);
let $collectionHolder;
let inProgress = false;
let $promo = $('#cart_promo');
let degressiveRequest;
let promoRequest;
let shippingRequest;
let viewFieldCity = false;
if ($('section.shop').attr('data-field-city')) {
    viewFieldCity = $('section.shop').attr('data-field-city') === '0' ? false : true;
}
jQuery(document).ready(function () {

    if (document.querySelector('#cart_items')) {
        // Get the ul that holds the collection of tags
        $collectionHolder = $('#cart_items');
        if ($collectionHolder.length) {
            if ($collectionHolder.html().length > 0) {
                $('.cart-empty').hide();
                if ($promo.val()) {
                    calculPromo($promo.val());
                } else {
                    calculPromoAuto();
                }
            }
        }
        $('[name^="cart[deliveryAddress]"]').each(function (i, el) {

            if (el.getAttribute('type') != "checkbox") {
                $(this).removeAttr('required');
            }

        });
        // count the current form inputs we have (e.g. 2), use that as the new
        // index when inserting a new item (e.g. 2)
        $collectionHolder.data('index', $collectionHolder.find(':input').length);
        if ($('#cart_deliveryAddress_differentAddress').is(':checked')) {
            $('.form-address').show();
            $('[name^="cart[deliveryAddress]"]').each(function (i, el) {
                if (el.getAttribute('type') != "checkbox") {
                    $(this).attr('required', 'required');
                }

            });
        }
        if ($('#cart_invoiceAddress_country').val() == 'FR' && !viewFieldCity) {
            $('#cart_invoiceAddress_city').prop('readonly', true)
        }
        if ($('#cart_deliveryAddress_country').val() == 'FR' && !viewFieldCity) {
            $('#cart_deliveryAddress_city').prop('readonly', true)
        }

        $('#cart_invoiceAddress_postalCode,#cart_deliveryAddress_postalCode').keyup(delay(function (event) {
            let country = null;
            let postal = null;
            let city = null;
            if (event.target.id == 'cart_invoiceAddress_postalCode') {
                country = $('#cart_invoiceAddress_country');
                postal = $('#output_postal_invoice');
                city = $('#cart_invoiceAddress_city')
            } else if (event.target.id == 'cart_deliveryAddress_postalCode' ) {
                country = $('#cart_deliveryAddress_country');
                postal = $('#output_postal_delivery');
                city = $('#cart_deliveryAddress_city')
            }
            postal.hide();
            postal.empty();
            if (country.val() == 'FR') {
                if ($(this).val().length === 5 && !inProgress) {
                    inProgress = true;
                    let sortCities = [];
                    let cities = null;
                    $.get("https://geo.api.gouv.fr/communes", "codePostal=" + $(this).val()).done(function (data) {
                        inProgress = false;
                        Object.keys(data).forEach(function (key) {
                            sortCities[removeAccents(data[key]['nom'])] = data[key]['nom'].toUpperCase();
                        });

                        let $i = 0;
                        Object.keys(sortCities).sort().forEach(function (key) {
                            if ($i === 0) {
                                postal.show();
                                postal.empty();
                            }
                            let a = '<a href="#" data-scroll-ignore data-city="' + sortCities[key] + '">' + sortCities[key] + '</a>';
                            postal.append(a);
                            $i++;
                        });
                    }).fail(function (data) {
                        city.prop('readonly', false);
                        inProgress = false;
                    });

                } else {
                    city.val(null);
                }
            }
            event.preventDefault();
            event.stopPropagation();
        }, 300));



        $('#cart_invoiceAddress_email,#cart_invoiceAddress_phone').keyup(delay(function (event) {
            calculPromoAuto();
            event.preventDefault();
            event.stopPropagation();
        }, 300));

        $('#output_postal_invoice,#output_postal_delivery').on('click', 'a', function (e) {
            let city = $(this).data('city');
            if ($(this).parent().attr('id') == 'output_postal_invoice') {
                $('#cart_invoiceAddress_city').val(city);
                $('#output_postal_invoice').hide();
            } else if ($(this).parent().attr('id') == 'output_postal_delivery') {
                $('#cart_deliveryAddress_city').val(city);
                $('#output_postal_delivery').hide();

            }
            if ($promo.val()) {
                calculPromo($promo.val());
            } else {
                totalProductsPrice();
            }
            e.preventDefault();
            e.stopPropagation();
        });

        $('#cart_deliveryAddress_city,#cart_invoiceAddress_city').keyup(delay(function (event) {
            if ($promo.val()) {
                calculPromo($promo.val());
            } else {
                calculPromoAuto();
            }
            e.preventDefault();
            e.stopPropagation();
        }, 300));

        let deliveryMethods = document.querySelectorAll('.input_cart_deliveryMethod');
        if (deliveryMethods) {
            deliveryMethods.forEach((deliveryMethod) => {
                deliveryMethod.addEventListener('click', () => {
                    deliveryMethods.forEach((deliveryMethodBis) => {
                        if (deliveryMethodBis != deliveryMethod) {
                            deliveryMethodBis.checked = false;
                        }
                    });
                    if ($promo.val()) {
                        calculPromo($promo.val());
                    } else {
                        calculPromoAuto();
                    }
                });
            });
        }
    }
});

$('#cart_promo').on('change', function () {
    let code = $(this).val();
    if (code) {
        calculPromo(code);
    } else {
        calculPromoAuto();
    }
});

$('#cart_invoiceAddress_country').on('change', function () {
    $('#cart_invoiceAddress_postalCode').val('');
    $('#cart_invoiceAddress_city').val('');
    if ($('#cart_invoiceAddress_country').val() == 'FR' && !viewFieldCity) {
        $('#cart_invoiceAddress_city').prop('readonly', true);
    } else {
        $('#cart_invoiceAddress_city').prop('readonly', false)
    }
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }
});

$('#cart_deliveryAddress_country').on('change', function () {
    $('#cart_deliveryAddress_postalCode').val('');
    $('#cart_deliveryAddress_city').val('');
    if ($('#cart_deliveryAddress_country').val() == 'FR' && !viewFieldCity) {
        $('#cart_deliveryAddress_city').prop('readonly', true);
    } else {
        $('#cart_deliveryAddress_city').prop('readonly', false)
    }
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }
});

$('.button-shop').on('click', function (e) {
    // prevent the link from creating a "#" on the URL
    e.preventDefault();

    let item = $(this).attr('data-item');
    let price = $(this).attr('data-price');
    let product = $(this).attr('data-product');
    let selectBox = $(this).attr('data-selectBox');
    let elQty = $('.variant-qty[data-item="' + item + '"]');
    let qty = elQty[0].value;
    let typeVariant = $('.variant-type[data-product="' + product + '"] :selected').text();
    let typeValue = $('.variant-type[data-product="' + product + '"] :selected').val();
    if (!typeValue) {
        if (!document.querySelector('.variant[data-product="' + product + '"]')) {

            Toastr.warning(Translator.trans('shop.error.volume', {'selectBox': selectBox}, 'messages'));
            return;
        }
    }
    if (typeVariant == '') {
        typeVariant = $(this).parent().children('.article-info').find('.variant-name').text();
    }
    let name = $('.article-info[data-product="' + product + '"]').find('.cuvee-name').text();
    name = name.replace(/(<([^>]+)>)/ig, "");
    let quality = $('.article-info[data-product="' + product + '"]').find('.article-quality').text();
    if (qty <= 0) {
        Toastr.warning(Translator.trans('shop.error.quantity', {}, 'messages'));

        return;

    } else {
        $('.variant-qty').each(function (i, obj) {
            $('.variant-qty').foundation('removeErrorClasses', $(this));
            $('.variant-qty').val(0);
        });
        $('.cart-empty').hide();
        if (!$(this).is('[data-soldout]')) {
            let textAddToCart = $('section.shop').attr('data-adding-to-cart');
            addItemForm($collectionHolder, item, qty, price);
            Toastr.success(textAddToCart + ' ' + qty + ' ' + name + ' ' + quality);
        }

    }
});

$(".variant-type").change(function () {
    let optionSelected = $("option:selected", this);
    let product = $(this).data('product');
    let item = optionSelected.val();
    let price = parseFloat(optionSelected.data('price') * 100 / 10000).toFixed(2);
    let oldPrice = optionSelected.data('old-price');
    let elQty = $('.variant-qty[data-product="' + product + '"]');
    elQty[0].setAttribute('data-item', item);
    let elButton = $('.button-shop[data-product="' + product + '"]');
    if (optionSelected.data('soldout')) {
        elButton.attr('data-soldout', 'data-soldout');
        $(this).parent().parent().parent().find('.variant-qty').attr('disabled', 'disabled');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('hidden');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('promo');
        if (optionSelected.data('allsoldout')) {
            $(this).parent().parent().parent().parent().parent().parent().find('.ribbon span').text($(this).parent().parent().parent().parent().attr('data-text-ribbon'));
        } else {
            $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').addClass('soldout');
            $(this).parent().parent().parent().parent().parent().parent().find('.ribbon span').text($('section.shop').attr('data-text-soldout'));
        }
    } else if (optionSelected.data('discount')) {
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('hidden');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('soldout');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').addClass('promo');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon span').text($('section.shop').attr('data-text-promo'));
        elButton.removeAttr('data-soldout');
        $(this).parent().parent().parent().find('.variant-qty').removeAttr('disabled');
    } else if (optionSelected.data('ribbon')) {
        if (optionSelected.data('allsoldout')) {
            elButton.attr('data-soldout', 'data-soldout');
        } else {
            $(this).parent().parent().parent().find('.variant-qty').attr('disabled', false);
            elButton.removeAttr('data-soldout');
        }
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('hidden');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('soldout');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').removeClass('promo');
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon span').text($(this).parent().parent().parent().parent().attr('data-text-ribbon'));
    } else {
        $(this).parent().parent().parent().parent().parent().parent().find('.ribbon').addClass('hidden');
        elButton.removeAttr('data-soldout');
        $(this).parent().parent().parent().find('.variant-qty').removeAttr('disabled');
    }
    $('.variant-qty').each(function (i, obj) {
        $('.variant-qty').foundation('removeErrorClasses', $(this));
    });


    elButton[0].setAttribute('data-item', item);
    elButton[0].setAttribute('data-price', optionSelected.data('price'));

    $(this).parent().parent().parent().find(".variant-qty").data('item', item);
    if (oldPrice == null) {
        $(this).parent().parent().parent().parent().find(".variant-price").text(price + ' €');
    } else {

        let old = optionSelected.data('old-price').match(/\d+/)[0];
        old = parseFloat(old / 100).toFixed(2);
        $(this).parent().parent().parent().parent().find(".variant-price").html('<span class="old-price">' + old + ' €</span> ' + price + ' €');

    }

});
$(document).on('click', '.delete-cart-row', function (e) {
    $(e.target).parents('.form-group:first').remove();
    if ($('#cart_items').is(':empty')) {
        $('.cart-empty').show();
    }
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }
});

$('#cart_items').on('change', '.cart-item-quantity', function (e) {
    let item = $(this).data('item');
    let quantity = 0;
    let price = $('.cart-item-price[data-item="' + item + '"]').attr('data-price');
    if ($(this).val()) {
        quantity = parseInt($(this).val());
    }

    let totalItem = parseFloat(price * quantity).toFixed(2);
    $('.cart-item-total[data-item="' + item + '"]').text(totalItem + ' €');
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }

});

$('#cart_deliveryAddress_differentAddress').on('click', function (e) {
    if ($(this).is(':checked')) {
        $('.form-address').show();
        $('[name^="cart[deliveryAddress]"]').each(function (i, el) {
            if (el.getAttribute('type') != "checkbox") {
                $(this).attr('required', 'required');
            }

        });
    } else {
        $('.form-address').hide();
        $('[name^="cart[deliveryAddress]"]').each(function (i, el) {
            if (el.getAttribute('type') != "checkbox") {
                $(this).removeAttr('required');
            }

        });
    }
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }
});

function addItemForm($collectionHolder, item, quantity, price) {
    // Get the data-prototype explained earlier
    let prototype = $collectionHolder.data('prototype');

    // get the new index
    let index = $collectionHolder.data('index');

    let newForm = prototype;

    newForm = newForm.replace(/__name__/g, index);
    let prevItem = $('.cart-item-quantity[data-item="' + item + '"]');
    if (prevItem[0]) {
        let prevQuantity = prevItem[0].value;
        let totalQuantity = parseInt(prevQuantity) + parseInt(quantity);
        prevItem[0].value = totalQuantity;
        price = parseFloat(parseInt(price) * 100 / 10000).toFixed(2);
        let totalItem = parseFloat(price * totalQuantity).toFixed(2);
        let prevTotal = $('.cart-item-total[data-item="' + item + '"]');
        prevTotal.text(totalItem + ' €');
    } else {
        // increase the index with one for the next item
        $collectionHolder.data('index', index + 1);

        // Display the form in the page in an li, before the "Add a tag" link li
        let $newFormLi = $('#cart_items').append(newForm);
        $newFormLi.find('#cart_items_' + index + '_quantity').val(quantity);
        $newFormLi.find('#cart_items_' + index + '_quantity').attr('data-item', item);
        $newFormLi.find('#cart_items_' + index + '_variant').val(item);
        $newFormLi.find('#cart_items_' + index + '_variant').attr('data-item', item);
        $newFormLi.find('#cart_items_' + index + '_variant').val(item);
        $newFormLi.find('#cart_items_' + index + '_name').text($newFormLi.find('#cart_items_' + index + '_variant option[value=' + item + ']').text());
        price = parseFloat(parseInt(price) * 100 / 10000).toFixed(2);
        let totalItem = parseFloat(price * quantity).toFixed(2);

        $newFormLi.find('#cart_items_' + index + '_price').text(price + ' €');
        $newFormLi.find('#cart_items_' + index + '_price').attr('data-item', item);
        $newFormLi.find('#cart_items_' + index + '_price').attr('data-price', price);

        $newFormLi.find('#cart_items_' + index + '_total').attr('data-item', item);
        $newFormLi.find('#cart_items_' + index + '_total').text(totalItem + ' €');

    }
    if ($promo.val()) {
        calculPromo($promo.val());
    } else {
        calculPromoAuto();
    }
}

function totalProductsPrice() {
    let quantity = 0;
    let discount = 0;
    $('.cart-item-total').each(function (i, obj) {
        quantity = quantity + parseFloat($(this).html());
    });
    let discountValueAmount = document.querySelector('.value-discount').getAttribute('data-value-amount');
    let discountWithShipping = document.querySelector('.value-discount').getAttribute('data-withShipping');
    let discountValuePercent = document.querySelector('.value-discount').getAttribute('data-value-percent');
    if (discountValuePercent > 0 && discountWithShipping == 0) {
        discount = parseFloat(quantity * discountValuePercent).toFixed(2);
    }
    if (discountValueAmount > 0) {
        discount = parseFloat((discountValueAmount / 100).toFixed(2));
    }

    let total = quantity - discount;
    ;
    calculShiping(parseFloat(total).toFixed(2));

    $('.total-products-price').text(parseFloat(quantity).toFixed(2));
    $('.total-order-products').text(parseFloat(quantity).toFixed(2));
}

function calculShiping($total) {
    if (degressiveRequest && degressiveRequest.readyState != 4) {
        degressiveRequest.abort();
    }
    if (shippingRequest && shippingRequest.readyState != 4) {
        shippingRequest.abort();
    }
    $total = parseFloat($total);
    let form = $('#cart_items_form');
    degressiveRequest = $.ajax({
        type: 'POST',
        url: Routing.generate('promo_price'),
        dataType: 'json',
        data: form.serializeArray(),
        success: function (result) {
            $total = $total - parseFloat(result / 100);
            $('.row-degressive').show();
            $('.value-degressive').attr("data-value", parseFloat(result / 100));
            $('.value-degressive').text(parseFloat(-result / 100).toFixed(2));

            return;
        },
        error: function () {
            $('.row-degressive').hide();
            $('.value-degressive').attr("data-value", 0);

            return;
        },
        complete: function () {
            $('.alert-shipping-box').hide();
            shippingRequest = $.ajax({
                type: 'POST',
                url: Routing.generate('calcul_shipping'),
                dataType: 'json',
                data: form.serializeArray(),
                success: function (result) {
                    let discountWithShipping = document.querySelector('.value-discount').getAttribute('data-withShipping');
                    let discountValuePercent = document.querySelector('.value-discount').getAttribute('data-value-percent');
                    $('.alert-shipping-box').hide();
                    let shipping = parseFloat(result / 100);
                    $('.total-order-shipping').text(parseFloat(shipping).toFixed(2));
                    $total = $total + shipping;
                    if (discountValuePercent > 0 && discountWithShipping > 0) {
                        $total = $total - parseFloat($total * discountValuePercent).toFixed(2);
                    }

                    $('.total-order-total').text(parseFloat($total).toFixed(2));

                    if (document.querySelector('.tax-value')) {
                        let tax = $('.tax-value').data('value');
                        let totalTax = $total * tax;
                        $('.tax-value').text(parseFloat(totalTax).toFixed(2));
                        let totalTTC = totalTax + $total;
                        let discountWithShipping = document.querySelector('.value-discount').getAttribute('data-withShipping');
                        let discountValuePercent = document.querySelector('.value-discount').getAttribute('data-value-percent');
                        if (discountValuePercent > 0 && discountWithShipping > 0) {
                            totalTTC = totalTTC - parseFloat(totalTTC * discountValuePercent).toFixed(2);
                        }
                        $('.total-order-total-ttc').text(parseFloat(totalTTC).toFixed(2));

                        return;
                    }

                    return;
                },
                error: function (result) {
                    if (result.readyState != 0) {
                        $('.total-order-shipping').html('-');
                        $('.alert-shipping-box').show();
                        $('.alert-shipping').html(result.responseJSON);
                        //Toastr.error(Translator.trans(result.responseJSON, {}, 'messages'));
                        let discountWithShipping = document.querySelector('.value-discount').getAttribute('data-withShipping');
                        let discountValuePercent = document.querySelector('.value-discount').getAttribute('data-value-percent');
                        if (discountValuePercent > 0 && discountWithShipping > 0) {
                            $total = $total - parseFloat($total * discountValuePercent).toFixed(2);
                        }
                        $('.total-order-total').text(parseFloat($total).toFixed(2));
                    }
                    return;
                }
            });
        }
    });
}


function calculPromo(code) {
    $('.messagePromo').remove();
    let form = $('#cart_items_form');
    let formData = form.serializeArray();
    formData.push({name: "code", value: code});

    promoRequest = $.ajax({
        type: 'POST',
        url: Routing.generate('promo_code'),
        dataType: 'json',
        data: formData,
        success: function (result) {
            $('.messagePromo').remove();
            if (result['valuePercent']) {
                $('.value-discount').attr("data-value-amount", 0);
                if (result['withShipping']) {
                    $('.value-discount').attr("data-withShipping", 1);
                } else {
                    $('.value-discount').attr("data-withShipping", 0);
                }
                $('.value-discount').attr("data-value-percent", result['valuePercent']);
                $('.value-discount').text(parseFloat(-result['valuePercent'] * 100).toFixed(2) + ' %');
                if (parseFloat(result['valuePercent'] * 100).toFixed(2) > 0) {
                    $('.row-discount').show();
                } else {
                    $('.row-discount').hide()
                }
            } else {
                $('.value-discount').attr("data-withShipping", 0);
                $('.value-discount').attr("data-value-percent", 0);
                $('.value-discount').attr("data-value-amount", result['valueAmount']);
                $('.value-discount').text(parseFloat(-result['valueAmount'] / 100).toFixed(2) + ' €');
                if (parseFloat(result['valueAmount'] * 100).toFixed(2) > 0) {
                    $('.row-discount').show();
                } else {
                    $('.row-discount').hide()
                }
            }
            $('.form_cart_promo').append('<p class="messagePromo">' + result['message'] + '</p>');
            $('.verif-promo').html(' <i class="fas fa-check-circle fa-2x"></i>');
            totalProductsPrice();

            return;
        },
        error: function (result) {
            $('.messagePromo').remove();
            result = result.responseJSON;
            $('.row-discount').hide();
            $('.value-discount').attr("data-withShipping", 0);
            $('.value-discount').attr("data-value-amount", 0);
            $('.value-discount').attr("data-value-percent", 0);
            if ($('#cart_promo').val().length > 0) {
                $('.verif-promo').html('<i class="fas fa-times fa-2x"></i>');
                $('.form_cart_promo').append('<p class="messagePromo">' + result['message'] + '</p>');
            } else {
                $('.verif-promo').html('');
            }
            totalProductsPrice();
            calculPromoAuto();

            return;
        }
    });
}

function calculPromoAuto() {
    let form = $('#cart_items_form');
    let formData = form.serializeArray();
    promoRequest = $.ajax({
        type: 'POST',
        url: Routing.generate('promo_code_auto'),
        dataType: 'json',
        data: formData,
        success: function (result) {
            $('.messagePromo').remove();
            if (document.querySelector('#cart_promo') && document.querySelector('#cart_promo').value != "") {
                totalProductsPrice();

                return;
            } else {
                if (result['valuePercent']) {
                    if (result['withShipping']) {
                        $('.value-discount').attr("data-withShipping", 1);
                    } else {
                        $('.value-discount').attr("data-withShipping", 0);
                    }
                    $('.value-discount').attr("data-value-amount", 0);
                    $('.value-discount').attr("data-value-percent", result['valuePercent']);
                    $('.value-discount').text(parseFloat(-result['valuePercent'] * 100).toFixed(2) + ' %');
                    if (parseFloat(result['valuePercent'] * 100).toFixed(2) > 0) {
                        $('.row-discount').show();
                    } else {
                        $('.row-discount').hide()
                    }
                } else {
                    $('.value-discount').attr("data-withShipping", 0);
                    $('.value-discount').attr("data-value-percent", 0);
                    $('.value-discount').attr("data-value-amount", result['valueAmount']);
                    $('.value-discount').text(parseFloat(-result['valueAmount'] / 100).toFixed(2) + ' €');
                    if (parseFloat(result['valueAmount'] / 100).toFixed(2) > 0) {
                        $('.row-discount').show();
                    } else {
                        $('.row-discount').hide()
                    }
                }
            }

            totalProductsPrice();
            return;
        },
        error: function (result) {
             if (document.querySelector('#cart_promo')) {
                if (document.querySelector('#cart_promo').value != "") {
                    return ;
                }
            }
            $('.messagePromo').remove();
            $('.row-discount').hide();
            $('.value-discount').attr("data-withShipping", 0);
            $('.value-discount').attr("data-value-amount", 0);
            $('.value-discount').attr("data-value-percent", 0);

            totalProductsPrice();
            return;
        }
    });
}

function delay(fn, ms) {
    let timer = 0
    return function (...args) {
        clearTimeout(timer)
        timer = setTimeout(fn.bind(this, ...args), ms || 0)
    }
}

function removeAccents(str) {
    let accents = 'ÀÁÂÃÄÅàáâãäåßÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    let accentsOut = "AAAAAAaaaaaaBOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
    str = str.split('');
    str.forEach((letter, index) => {
        let i = accents.indexOf(letter);
        if (i != -1) {
            str[index] = accentsOut[i];
        }
    })
    return str.join('');
}

let deliveriesproducts = document.querySelectorAll('.product-delivery')
deliveriesproducts.forEach((deliveryproducts) => {
    deliveryproducts.addEventListener('click', (e) => {
        e.preventDefault();
        let label = deliveryproducts.getAttribute('data-label');
        $.ajax({
            type: 'GET',
            url: Routing.generate('delivery_method_products', {'id': deliveryproducts.getAttribute('data-delivery')}),
            dataType: 'json',
            success: function (result) {
                let html = '- ' + result.join('<br/>- ');
                Swal.fire({
                        title: Translator.trans('shop.delivery_method.viewProductList', {'title': label}, 'messages'),
                        html: html,
                        customClass: {
                            popup: 'product-delivery',
                            confirmButton: 'shop',
                        },
                    }
                )
            }
        });
        return false;
    })
});
