import { handleQuantityChange } from '../basket/quantity-change-handler';
import { updateQuantityAction } from '../basket/update-quantity';
import { ROUTES } from '../utils/routes';
import { callAction } from '../utils/http-action';
import { updateTotal } from '../basket/mini-basket-total';
import { updateQuantityOperation } from '../basket/update-quantity-operation';
import {
    checkProductArrays,
    getCartEntries,
    getMessageInfo,
    isMessageExist,
    updatePromotion,
    showNotification,
} from '../basket/basket-utils';
import { updateCartBase } from '../basket/basket-update-cart';
import { updateCartActionBase } from '../basket/basket-update-cart-action';
import { hideLoader, showLoader } from '../utils/loader';

const Handlebars = require('hbsfy/runtime');
import orderItemTemplate from '../../../components/mini-basket/mini-basket-order-item.hbs';
import miniBasketMainWrap from '../../../components/mini-basket/mini-basket.hbs';
import miniBasketEmpty from '../../../components/mini-basket/mini-basket-empty.hbs';
Handlebars.registerHelper('eq', function (a, b) {
    return a === b;
});

Handlebars.registerHelper('removeFirst', function (str, remove) {
    if (typeof str !== 'string' || typeof remove !== 'string') return str;
    if (str.startsWith(remove)) {
        return str.slice(remove.length);
    }
    return str;
});

Handlebars.registerHelper('isToggleVatAvailable', function () {
    return Wick.checkLocalEnv ? false : window.ACC?.app?.isVatToggleAvailable;
});

var Wick = window.Wick || {};

const urlsToReload = ['/cart', '/merge-carts'];

Wick.MiniBasketSliderFE = {
    events: {
        MINI_BASKET_CHECKOUT: 'MINI_BASKET_CHECKOUT',
        MINI_BASKET_VIEW_BASKET: 'MINI_BASKET_VIEW_BASKET',
        SHOW_MINI_BASKET: 'SHOW_MINI_BASKET',
        MINI_BASKET_QUANTITY_INCREASE: 'MINI_BASKET_QUANTITY_INCREASE',
        MINI_BASKET_QUANTITY_DECREASE: 'MINI_BASKET_QUANTITY_DECREASE',
        MINI_BASKET_ITEM_REMOVE: 'MINI_BASKET_ITEM_REMOVE',
    },
    el: {
        miniBasket: '.custom-slider.mini-basket',
        customLoader: '.mini-basket .basket-loader',
        subtotal: '.checkout-widget__item-bold',
        value: '.checkout-widget__item-value',
        vat: '.checkout-widget__item-vat',
        delivery: '.checkout-widget__item-delivery',
        charity: '.checkout-widget__item-charity',
        cc: '.checkout-widget__item-cc',
        discountItem: '.checkout-widget__details-discount',
        totalToggle: '.mini-basket__total-toggle',
        totalToggleValue: '.mini-basket__total-toggle-value',
        orderItem: '.mini-basket .card.product-card-preview',
        products: '.mini-basket .products',
        miniBasketSection: '.mini-basket .products',
        miniBasketTotal: '.custom-slider__count',
        headerBasketCount: '.header-minicart .header-minicart__counter',
        itemTotalIncVat: '.price .including-vat-inherit .value',
        itemTotalExcVat: '.price excluding-vat-inherit .value',
        itemTotal: '.price',
        orderItemOffers: '.products__offers',
        orderItemInfo: '.products__details-body',
        productCardPreview: '.card.product-card-preview',
        notifications: '.custom-slider__notifications',
        btnQuantity: '.card .btn--quantity',
        btnQuantityMinus: '.btn--quantity[data-action="minus"]',
        btnRemove: '.card .btn--remove',
        customSliderWrap: '.custom-slider__wrap',
        miniBasketFooter: '.custom-slider__footer',
        customSliderEmpty: '.custom-slider__empty',
        quantityValue: '.product-card__quantity-value',
        productsItem: '.products__item',
        totalHide: 'order-item__total-hide',
        btnCheckout: '#addToCartPopupCheckoutButton',
        btnViewBasket: '.mini-basket a.btn-view-basket-cta',
        basketTotalItem: '.basket-total-items',
    },
    classes: {
        HIDDEN_CLASS_NAME: 'd-none',
    },
    cartEntries: [],
    getEqualMapForUpdateCart: function (data) {
        return [
            {
                item: Wick.MiniBasketSliderFE.el.subtotal,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: data.subtotalWithoutCharity?.formattedValue,
                value: data.subTotal?.value,
                title: 'Items subtotal:',
            },
            {
                item: Wick.MiniBasketSliderFE.el.vat,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: data.totalTax?.formattedValue,
                value: data.totalTax?.value,
                title: 'VAT:',
            },
            {
                item: Wick.MiniBasketSliderFE.el.cc,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: 'Free',
                title: 'Click & Collect:',
            },
            {
                item: Wick.MiniBasketSliderFE.el.delivery,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: data.deliveryCost?.formattedValue,
                value: data.deliveryCost?.value,
                title: 'Delivery:',
            },
            {
                item: Wick.MiniBasketSliderFE.el.charity,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: data.charityPrice?.formattedValue,
                value: data.charityPrice?.value,
                title: 'Charity donation:',
            },
            {
                item: Wick.MiniBasketSliderFE.el.discountItem,
                itemValue: Wick.MiniBasketSliderFE.el.value,
                dataValue: data.totalDiscounts ? data.totalDiscounts?.formattedValue : '',
                value: data.totalDiscounts ? data.totalDiscounts?.value : '',
                title: 'Discount(s):',
            },
            {
                item: Wick.MiniBasketSliderFE.el.totalToggle,
                itemValue: Wick.MiniBasketSliderFE.el.totalToggleValue,
                dataValue: data.totalPrice?.formattedValue,
                value: data.totalPrice?.value,
            },
        ];
    },
    isInitial: true,
    isMiniBasketOpened: false,
    actionEventType: null,
    isMiniBasketLoaded: false,
    miniBasketUpdateItemQuantity(e) {
        const $item = $(e.currentTarget).closest(Wick.MiniBasketSliderFE.el.productCardPreview);
        const quantityElement = $item.find(Wick.MiniBasketSliderFE.el.quantityValue);
        const value = quantityElement.text();
        const action = $(e.currentTarget).attr('data-action');
        const entryNumber = +$item.attr('data-id');

        if (action === 'plus')
            Wick.MiniBasketSliderFE.actionEventType =
                Wick.MiniBasketSliderFE.events.MINI_BASKET_QUANTITY_INCREASE;
        if (action === 'minus')
            Wick.MiniBasketSliderFE.actionEventType =
                Wick.MiniBasketSliderFE.events.MINI_BASKET_QUANTITY_DECREASE;
        if (action === 'remove')
            Wick.MiniBasketSliderFE.actionEventType =
                Wick.MiniBasketSliderFE.events.MINI_BASKET_ITEM_REMOVE;

        handleQuantityChange({
            quantityInput: quantityElement,
            action,
            value,
            context: $item,
            entryNumber,
            onQuantityChange: Wick.MiniBasketSliderFE.updateQuantityAction,
            debounceQuantityChange: Wick.MiniBasketSliderFE.debounceQuantityChange,
            parentWrap: Wick.MiniBasketSliderFE.el.productsItem,
        });
    },
    debounceQuantityChange: _.debounce(function (entryNumber, value, quantityInput, context) {
        showLoader(Wick.MiniBasketSliderFE.el.customLoader);
        Wick.MiniBasketSliderFE.updateQuantityAction(entryNumber, value, quantityInput, context);
    }, 500),
    updateQuantityAction: function (entryNumber, quantityToUpdate, quantityInput, context) {
        updateQuantityAction({
            entryNumber,
            quantityToUpdate,
            quantityInput,
            context,
            hideLoader: () =>
                setTimeout(() => hideLoader(Wick.MiniBasketSliderFE.el.customLoader), 500),
            updateAction: Wick.MiniBasketSliderFE.updateAction,
            isLocalEnv: Wick.checkLocalEnv,
            basketData: Wick.MiniBasketData,
            updateQuantityOperation: Wick.MiniBasketSliderFE.updateQuantityOperation,
            callActionFn: callAction,
            routes: ROUTES,
            isMiniBasket: true,
        });

        Wick.MiniBasketSliderFE.toggleMinusButtonState(context, quantityToUpdate);
    },
    toggleMinusButtonState($item, value) {
        const $minusBtn = $item.find(Wick.MiniBasketSliderFE.el.btnQuantityMinus);
        if (value > 1) {
            $minusBtn.prop('disabled', false);
        } else {
            $minusBtn.prop('disabled', true);
        }
    },
    updateAction: function (response, quantityToUpdate, quantityInput, context, successCallback) {
        Wick.MiniBasketSliderFE.updateQuantityOperation(
            quantityToUpdate,
            quantityInput,
            context,
            response
        );
        successCallback(response);
    },
    updateQuantityOperation: function (quantityToUpdate, quantityInput, context, data) {
        const $notifications = $(Wick.MiniBasketSliderFE.el.notifications);
        if ($notifications.children().length > 0) {
            $notifications.empty();
        }

        updateQuantityOperation(quantityToUpdate, quantityInput, context, data, {
            updateCart: Wick.MiniBasketSliderFE.updateCart,
            showNotification: Wick.MiniBasketSliderFE.showNotification,
            updateQuantity: Wick.MiniBasketSliderFE.updateQuantity,
            updateItemTotal: null,
            isMessageExist: Wick.MiniBasketSliderFE.isMessageExist,
            getMessageInfo: Wick.MiniBasketSliderFE.getMessageInfo,
        });
    },
    updateCart: function (repaintData, context, charity, initial, callback) {
        console.log('case(api) to update cart');
        updateCartBase({
            isLocalEnv: Wick.checkLocalEnv,
            apiUrl: ROUTES.BASKET_GET_CART,
            apiType: 'GET',
            hideLoader: () =>
                setTimeout(() => hideLoader(Wick.MiniBasketSliderFE.el.customLoader), 500),
            callActionFn: callAction,
            actionCallback: callback || Wick.MiniBasketSliderFE.updateCartAction,
            repaintData,
            context,
            charity,
            initial,
            localUpdateFn: function (initial, repaintData, context, charity) {
                if (initial) {
                    Wick.MiniBasketSliderFE.getCartEntries(Wick.MiniBasketData.initialCartState);
                } else {
                    updateTotal(
                        Wick.MiniBasketData.updateCart,
                        Wick.MiniBasketSliderFE.getEqualMapForUpdateCart(
                            Wick.MiniBasketData.updateCart
                        )
                    );

                    if (repaintData) {
                        Wick.MiniBasketSliderFE.repaintOrderItems(
                            Wick.MiniBasketData.updateCart,
                            repaintData
                        );
                    } else {
                        Wick.MiniBasketSliderFE.updateItemsCount(Wick.MiniBasketData.updateCart);
                    }

                    !charity ||
                        Wick.MiniBasketSliderFE.addCharityEntryNumber(
                            Wick.MiniBasketData.updateCart
                        );
                    if (context && context.length) {
                        Wick.MiniBasketSliderFE.updatePromotion(
                            Wick.MiniBasketData.updateCart,
                            context
                        );
                    }
                    Wick.MiniBasketSliderFE.getCartEntries(Wick.MiniBasketData.updateCart);
                    Wick.MiniBasketSliderFE.checkProductArrays(Wick.MiniBasketData.updateCart) ||
                        Wick.MiniBasketSliderFE.removeOrderItem(repaintData);
                    setTimeout(() => hideLoader(Wick.MiniBasketSliderFE.el.customLoader), 1000);
                }
            },
        });
    },
    updateCartAction: function (response, { repaintData, context, charity, initial }) {
        updateCartActionBase({
            response,
            repaintData,
            context,
            charity,
            initial,
            updateOrderSummaryFn: updateTotal,
            getEqualMapFn: Wick.MiniBasketSliderFE.getEqualMapForUpdateCart,
            repaintOrderItemsFn: Wick.MiniBasketSliderFE.repaintOrderItems,
            addCharityEntryNumberFn: Wick.MiniBasketSliderFE.addCharityEntryNumber,
            updatePromotionFn: Wick.MiniBasketSliderFE.updatePromotion,
            cartEntries: Wick.MiniBasketSliderFE.cartEntries,
            getCartEntriesFn: () => Wick.MiniBasketSliderFE.getCartEntries(response),
            checkProductArraysFn: Wick.MiniBasketSliderFE.checkProductArrays,
            removeOrderItemFn: Wick.MiniBasketSliderFE.removeOrderItem,
            elOrderItem: Wick.MiniBasketSliderFE.el.orderItem,
            triggerCartUpdate: false,
            extraActionsMiniBasket: () => {
                Wick.MiniBasketSliderFE.toggleMiniBasketEmptyView();
                Wick.MiniBasketSliderFE.updateItemsCount(response);

                if (Wick.MiniBasketSliderFE.actionEventType) {
                    Wick.MiniBasketSliderFE.fireMiniBasketActionEvent(
                        Wick.MiniBasketSliderFE.actionEventType,
                        response
                    );
                }
            },
        });
    },
    fireMiniBasketActionEvent(eventType, cartData) {
        if (!eventType) return;
        const payload = {
            orderType: cartData.orderType || '',
            deliveryOrderGroups: cartData.deliveryOrderGroups || [],
            pickupOrderGroups: cartData.pickupOrderGroups || [],
        };
        const event = createEvent(eventType, payload, {});
        window.dispatchEvent(event);
    },
    removeOrderItem(data) {
        Wick.MiniBasketSliderFE.updateItemsCount(data);
    },
    repaintOrderItems: function (data) {
        const ccGroup = data.pickupOrderGroups || [],
            deliveryGroup = data.deliveryOrderGroups || [];
        let itemDetails = {};
        let position = 0;

        $(Wick.MiniBasketSliderFE.el.orderItem).remove();

        if (deliveryGroup.length) {
            deliveryGroup.forEach((obj) => {
                obj.entries.forEach((item) => {
                    if (item.charity) return;
                    itemDetails = { item, type: 'delivery', data, position };
                    $(Wick.MiniBasketSliderFE.el.products).append(
                        Wick.MiniBasketSliderFE.createOrderItem(itemDetails)
                    );
                    position++;
                });
            });
        }

        if (ccGroup.length) {
            ccGroup.forEach((obj) => {
                obj.entries.forEach((item) => {
                    itemDetails = { item, type: 'cc', data, position };
                    $(Wick.MiniBasketSliderFE.el.products).append(
                        Wick.MiniBasketSliderFE.createOrderItem(itemDetails)
                    );
                    position++;
                });
            });
        }

        Wick.MiniBasketSliderFE.updateItemsCount(data);

        $(document).trigger('cartRerender');
    },
    showNotification: function (data) {
        showNotification(data, Wick.MiniBasketSliderFE.el.notifications);

        Wick.MiniBasketSliderFE.scrollToNotifications();
    },
    scrollToNotifications: function () {
        const $notifications = $(Wick.MiniBasketSliderFE.el.notifications);
        if (!$notifications.children().length) return;

        const $scrollContainer = $(Wick.MiniBasketSliderFE.el.customSliderWrap);
        if (!$scrollContainer.length) return;

        $scrollContainer.stop(true, true).animate({ scrollTop: 0 }, 200);
    },
    isMessageExist: isMessageExist,
    getMessageInfo: getMessageInfo,
    getCartEntries: function (data) {
        if (!data.deliveryOrderGroups) {
            data.deliveryOrderGroups = [];
            data.pickupOrderGroups = [];
            Wick.MiniBasketSliderFE.cartEntries = getCartEntries(data);
            return;
        }

        Wick.MiniBasketSliderFE.cartEntries = getCartEntries(data);
    },
    checkProductArrays: checkProductArrays,
    createOrderItem(itemDetails) {
        let promotionsHtml = '';
        if (itemDetails.item.updateable) {
            promotionsHtml = Wick.MiniBasketSliderFE.addPromotions(
                itemDetails.item,
                itemDetails.data
            );
        }

        if (
            itemDetails.item.deliveryPointOfService &&
            itemDetails.item.deliveryPointOfService.description
        ) {
            itemDetails.item.deliveryPointOfService.description =
                Wick.MiniBasketSliderFE.capitalizeWords(
                    itemDetails.item.deliveryPointOfService.description
                );
        }

        return orderItemTemplate({
            item: itemDetails.item,
            type: itemDetails.type,
            promotionsHtml,
            position: itemDetails.position,
        });
    },
    capitalizeWords(str) {
        return str
            .toLowerCase()
            .split(' ')
            .map(function (word) {
                return word.charAt(0).toUpperCase() + word.slice(1);
            })
            .join(' ');
    },
    updateItemsCount(data) {
        const totalCount = data.totalUnitCount || 0;

        $(Wick.MiniBasketSliderFE.el.miniBasketTotal).text(`Your basket (${totalCount})`);
        $(Wick.MiniBasketSliderFE.el.headerBasketCount).text(`${totalCount}`);
        $(Wick.MiniBasketSliderFE.el.basketTotalItem).html(`${totalCount}`);
    },
    updatePromotion: function (data) {
        updatePromotion(
            data,
            Wick.MiniBasketSliderFE.el.orderItem,
            Wick.MiniBasketSliderFE.el.orderItemOffers,
            Wick.MiniBasketSliderFE.el.orderItemInfo,
            Wick.MiniBasketSliderFE.addPromotions
        );
    },
    addPromotions: function (item, data) {
        let arr = [];

        data.potentialProductPromotions &&
            data.potentialProductPromotions.forEach((entry) => {
                entry.consumedEntries.forEach((promo) => {
                    if (promo.orderEntryNumber === item.entryNumber) {
                        if (arr.length) {
                            let duplicate = arr.every((el) => {
                                return (
                                    el !== `<div class="products__promo">${entry.description}</div>`
                                );
                            });

                            !duplicate ||
                                arr.push(`<div class="products__promo">${entry.description}</div>`);
                        } else {
                            arr.push(`<div class="products__promo">${entry.description}</div>`);
                        }
                    }
                });
            });

        data.appliedProductPromotions &&
            data.appliedProductPromotions.forEach((entry) => {
                entry.consumedEntries.forEach((promo) => {
                    if (promo.orderEntryNumber === item.entryNumber && entry.description) {
                        if (arr.length) {
                            let duplicate = arr.every((el) => {
                                return (
                                    el !== `<div class="products__promo">${entry.description}</div>`
                                );
                            });

                            !duplicate ||
                                arr.push(`<div class="products__promo">${entry.description}</div>`);
                        } else {
                            arr.push(`<div class="products__promo">${entry.description}</div>`);
                        }
                    }
                });
            });

        return arr.length ? `<div class="products__offers">${arr.join('')}</div>` : '';
    },
    initPopupSlider() {
        createPopupSlider({
            type: 'miniBasket',
            sliderSelector: '.custom-slider.mini-basket',
            onAppendEvent: Wick.MiniBasketSliderFE.events.SHOW_MINI_BASKET,
            onAppend: function (event, { showSlider }) {
                Wick.MiniBasketSliderFE.toggleMiniBasketEmptyView();
                showSlider();
            },
            onClose: function () {
                $(Wick.MiniBasketSliderFE.el.notifications).empty();
                Wick.MiniBasketSliderFE.isMiniBasketOpened = false;
                Wick.MiniBasketSliderFE.actionEventType = null;
            },
        });
    },
    toggleMiniBasketEmptyView() {
        if (!Wick.MiniBasketSliderFE.cartEntries.length) {
            if (!$(Wick.MiniBasketSliderFE.el.customSliderEmpty).length) {
                $(Wick.MiniBasketSliderFE.el.customSliderWrap).append(miniBasketEmpty());
                $(Wick.MiniBasketSliderFE.el.miniBasketFooter).addClass(
                    Wick.MiniBasketSliderFE.classes.HIDDEN_CLASS_NAME
                );
            }
        } else {
            $(Wick.MiniBasketSliderFE.el.customSliderWrap)
                .find(Wick.MiniBasketSliderFE.el.customSliderEmpty)
                .remove();
            $(Wick.MiniBasketSliderFE.el.miniBasketFooter).removeClass(
                Wick.MiniBasketSliderFE.classes.HIDDEN_CLASS_NAME
            );

            if (!$(Wick.MiniBasketSliderFE.el.products).length) {
                $(Wick.MiniBasketSliderFE.el.customSliderWrap).append(
                    '<div class="products popover-mini-basket__cards-holder"></div>'
                );
            }
        }
    },
    appendMiniBasketWrap() {
        if (!$(Wick.MiniBasketSliderFE.el.miniBasket).length) {
            $('body').append(miniBasketMainWrap());
        }
    },
    isEmptyBasketLocal() {
        return window.location.pathname.includes('page_product-details-saved-pl.html');
    },
    shouldReloadPage: function () {
        return urlsToReload.includes(window.location.pathname);
    },
    openMiniBasket() {
        if (Wick.MiniBasketSliderFE.isInitial && Wick.checkLocalEnv) {
            const initialCartState = Wick.MiniBasketSliderFE.isEmptyBasketLocal()
                ? Wick.MiniBasketData.initialCartEmptyState
                : Wick.MiniBasketData.initialCartState;

            Wick.MiniBasketSliderFE.getCartEntries(initialCartState);

            updateTotal(
                initialCartState,
                Wick.MiniBasketSliderFE.getEqualMapForUpdateCart(initialCartState)
            );
            Wick.MiniBasketSliderFE.repaintOrderItems(initialCartState);
            Wick.MiniBasketSliderFE.showMiniBasketEvent();
            setTimeout(() => {
                Wick.MiniBasketSliderFE.isInitial = false;
            }, 100);
            return;
        }

        if (!Wick.MiniBasketSliderFE.isMiniBasketLoaded) {
            Wick.MiniBasketSliderFE.updateCart(
                true,
                undefined,
                undefined,
                false,
                function (response, params) {
                    Wick.MiniBasketSliderFE.updateCartAction(response, params);
                    Wick.MiniBasketSliderFE.isMiniBasketLoaded = true;
                    Wick.MiniBasketSliderFE.isMiniBasketOpened = true;
                    Wick.MiniBasketSliderFE.showMiniBasketEvent();
                }
            );
        } else {
            Wick.MiniBasketSliderFE.showMiniBasketEvent();
        }
    },
    showMiniBasketEvent() {
        return new Promise((resolve, reject) => {
            const eventDetail = { resolve, reject };
            const event = createEvent(
                Wick.MiniBasketSliderFE.events.SHOW_MINI_BASKET,
                {},
                eventDetail
            );
            window.dispatchEvent(event);
        });
    },
    bindMiniBasketBtnHandler(selector, eventName) {
        $(document).on('click', selector, function (e) {
            e.preventDefault();
            return new Promise((resolve, reject) => {
                const eventDetail = { resolve, reject };
                const event = createEvent(eventName, {}, eventDetail);
                window.dispatchEvent(event);
            })
                .then(() => {
                    window.location.href = $(selector).attr('href');
                })
                .catch((error) => {
                    console.error(error);
                });
        });
    },
    init() {
        $(Wick.MiniBasketSliderFE.el.miniBasket).on(
            'click',
            Wick.MiniBasketSliderFE.el.btnQuantity,
            Wick.MiniBasketSliderFE.miniBasketUpdateItemQuantity
        );
        $(Wick.MiniBasketSliderFE.el.miniBasket).on(
            'click',
            Wick.MiniBasketSliderFE.el.btnRemove,
            Wick.MiniBasketSliderFE.miniBasketUpdateItemQuantity
        );

        Wick.MiniBasketSliderFE.bindMiniBasketBtnHandler(
            Wick.MiniBasketSliderFE.el.btnCheckout,
            Wick.MiniBasketSliderFE.events.MINI_BASKET_CHECKOUT
        );

        Wick.MiniBasketSliderFE.bindMiniBasketBtnHandler(
            Wick.MiniBasketSliderFE.el.btnViewBasket,
            Wick.MiniBasketSliderFE.events.MINI_BASKET_VIEW_BASKET
        );
    },
};

$(document).ready(function () {
    const $minicartBtn = $('.header-minicart .header-minicart__btn');
    if (!$minicartBtn.length) return;

    if (Wick.MiniBasketSliderFE.shouldReloadPage()) {
        $minicartBtn.on('click', () => window.location.reload());
        return;
    }

    $minicartBtn.on('click', () => Wick.MiniBasketSliderFE.openMiniBasket());

    Wick.MiniBasketSliderFE.appendMiniBasketWrap();
    Wick.MiniBasketSliderFE.initPopupSlider();
    Wick.MiniBasketSliderFE.init();
});
