Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
42 kB
5
Indexable
Never
import angular from 'angular';

import cardTemplate from 'card.template.html';
import multiClubTemplate from 'multiclub.template.html';
import ButtonLoadingIndicator from 'src/utility/loading-indicator/button-loading-indicator.util';


/* FILTER NAMES */
const FILTER_12_MESI = '12 Mesi';
const FILTER_ACTIVE_12 = 'Active 12';
const FILTER_TUTTI = 'Tutti';
const FILTER_SEMPRE = 'Sempre';
const FILTER_DAY_NIGHT = 'Day&Night';
const FILTER_SPECIAL_AGE = 'Special Age';
const FILTER_SMART = 'Smart';

/* vars */
var ConfiguratorApp = angular.module('SubscriptionConfigurator', []);

ConfiguratorApp.config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}]);

ConfiguratorApp.factory('dataFactory', ['$http', function ($http) {

    var urlBase = window.location.pathname;
    var dataFactory = {};

    dataFactory.getProducts = function (club, filters) {

        const query =
            '?club=' + club.id +
            '&duration=' + filters.duration +
            '&age=' + filters.age +
            '&time=' + filters.time;

        return $http.get(urlBase + '/filter' + query);
    };

    dataFactory.getClubs = function (id, prodId) {
        return $http.get(urlBase + '/clubs' + '?club=' + id + '&prodId=' + prodId );
    };

    dataFactory.getCartRecap = function (id) {
        return $http.get(urlBase + '/cartRecap?productId='+ id);
    };

    return dataFactory;

}]);

ConfiguratorApp.factory('filterFactory', [function () {

    const filters = {
        club: '',
        duration: '',
        age: '',
        time: ''
    };

    return {

        getDuration: function () {
            return filters.duration;
        },
        setDuration: function (duration) {
            filters.duration = duration;
        },
        getAge: function () {
            return filters.age;
        },
        setAge: function (age) {
            filters.age = age;
        },
        getTime: function () {
            return filters.time;
        },
        setTime: function (time) {
            filters.time = time;
        }
    };
}]);

ConfiguratorApp.factory('modalService', [function () {
    return {
        openModal: function (id) {
            document.getElementById(id).style.display = 'block';
        },
        closeModal: function (id) {
            document.getElementById(id).style.display = 'none';
        },
        toggleModal: function (id) {
            const modal = document.getElementById(id);

            if (modal.style.display == 'none') {
                modal.style.display = 'block';
            } else {
                modal.style.display = 'none';
            }
        },
        showLoader: function (showText = true) {
            document.getElementById('vrgnModalLoader').style.display = 'block';
            if (!showText) {
                document.getElementById('modalText').style.display = 'none';
            }
        },
        hideLoader: function () {
            document.getElementById('vrgnModalLoader').style.display = 'none';
            document.getElementById('modalText').style.display = 'block';
        },
        toggleLoader: function () {

            const loader = document.getElementById('vrgnModalLoader');

            if (loader.style.display == 'none') {
                loader.style.display = 'block';
            } else {
                loader.style.display = 'none';
            }
        }
    };
}]);

ConfiguratorApp.directive('vrgnModal', ['modalService', function (modalService) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs) {

            function openModal() {

                modalService.toggleModal(attrs.vrgnModal);
            }

            el.on('click', openModal);
        }
    }
}]);

ConfiguratorApp.directive('vrgnClose', [function () {
    return {
        restrict: 'A',
        link: function (scope, el, attrs) {

            function closeModal() {
                document.getElementById(attrs.vrgnClose).style.display = 'none';
            }

            el.on('click', closeModal);
        }
    }
}]);

ConfiguratorApp.directive('vrgnProdCard', function () {
    return {
        restrict: 'EA',
        transclude: true,
        scope: {
            prod: '='
        },
        controller: ['$scope', function prodCardController($scope) {

            $scope.specialPromos = null;

            $scope.onClickOpenMulticlub = function (prodId) { $scope.$parent.onClickOpenMulticlub(prodId) };
            $scope.openModalSpecialPromo = function () { $scope.$parent.openModalSpecialPromo($scope) };
            $scope.onClickOpenCartSummary = function () { $scope.$parent.onClickOpenCartSummary($scope) };
            $scope.specialPromoAvailable = function () {
                const { exerpPromo, swPromo } = $scope.prod['promo'];
                return exerpPromo.filter(promo => promo.active).concat(swPromo.filter(promo => promo.active)).length;
            };
            $scope.onClickOpenServices = function () { $scope.$parent.onClickOpenServices() };

            $scope.onClickOpenCashbackModal = function (id) {$scope.$parent.onClickOpenCashbackModal(id) };
            $scope.onClickCloseCashbackModal = function (id) {$scope.$parent.onClickCloseCashbackModal(id) };

            $scope.onClickOpenModal = function (id) {$scope.$parent.onClickOpenModal(id) };
            $scope.onClickCloseModal = function (id) {$scope.$parent.onClickCloseModal(id) };
            $scope.specialPromos = $scope.specialPromoAvailable();
            $scope.privacy = window.privacy;

            $scope.specialCardDescription = ''
            $scope.basePrice = ''
            $scope.basePriceDescription = ''
            $scope.promoPrice = ''
            $scope.promoPriceDescription = ''
            $scope.singleLinePromo = false
            $scope.twoLinesPromo = false
            const prod = $scope.prod;

            console.log(prod)

            $scope.basePrice = prod.virginExerpFullPrice ? prod.virginExerpFullPrice.toFixed(2) : prod.prices.base_price.toFixed(2);
            if ($scope.specialPromos){
                if (prod.promo.exerpPromo[0] != null
                    && prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardDescription != null)
                {
                    $scope.specialCardDescription = prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardDescription
                }
                if (prod.promo.exerpPromo.lenght>0
                    && prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardFullPriceDescription)
                {
                    $scope.basePriceDescription = prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardFullPriceDescription
                }

                $scope.promoPrice = prod.prices.promo_price.product.toFixed(2);
                if (prod.virginExerpDiscountDescription){
                    $scope.promoPriceDescription = prod.virginExerpDiscountDescription;
                } else if (prod.promo.exerpPromo.lenght>0
                    && prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardDiscountedPriceDescription){
                    $scope.promoPriceDescription = prod.promo.exerpPromo[0].extensions.virginPromotionAttributes[0].specialCardDiscountedPriceDescription
                }

                if ($scope.basePrice !== $scope.promoPrice && !$scope.promoPriceDescription){
                    $scope.singleLinePromo = true
                } else if ($scope.promoPriceDescription) {
                    $scope.twoLinesPromo = true
                }
            }
        }],
        template: cardTemplate
    };
});

ConfiguratorApp.directive('vrgnMulticlub', function () {
    return {
        restrict: 'EA',
        transclude: true,
        scope: {
            multiclubData: '=' // two way binding
        },
        controller: ['$scope', function prodCardController($scope) {
            $scope.multiclubSearch = '';
        }],
        template: multiClubTemplate
    };
});

/**
 Filtro che serve a ritornare il numero di club accessibili dato in input una lista di club e l'attuale livello di abbonamento
 */

ConfiguratorApp.filter('activeClub', function () {
    return function (input, currentLevel) {
        const out = Array();

        for (let i = 0; i < input.length; i++) {
            if ((input[i].priority <= currentLevel ) && currentLevel !== 1 ) {
                out.push(input[i]);
            }
        }
        // conditional based on optional argument
        return out;
    };
})

ConfiguratorApp.controller('ConfigController', ['$scope', '$http', 'dataFactory', 'modalService', function ($scope, $http, dataFactory, modalService) {

    $scope.greeting = 'Welcome!';
    $scope.clubList = [];
    $scope.clubSearch = '';
    $scope.multiclubSearch = '';
    $scope.selectedProductCartRecap = {};
    $scope.cardBackground = '';
    $scope.tempFirstName = '';
    $scope.updatePrivacy = false;
    $scope.saveQuotationError = '';
    $scope.loginError = '';
    $scope.registrationError = '';
    $scope.updateDataError = '';

    $scope.customerFirstName =  window.context.customer.firstName;
    $scope.customerLastName =  window.context.customer.lastName;
    $scope.customerEmail =  window.context.customer.email;
    $scope.customerNewEmail = window.context.customer.email;
    $scope.customerPhone =  window.context.customer.customFields.phone_number;
    $scope.specialPrimoPrivacyUpdate = window.privacy;

    localStorage.setItem('userEmail', window.context.customer.email);

    $scope.formUpdateData = {
        privacy : window.privacy
    }

    $scope.formRegisterData = {
        privacy : window.privacy
    }

    $scope.filters = {
        club: '',
        duration: window.page.durationFacet.find(durationFacetObj => durationFacetObj.default === true).id,
        age: window.page.ageFacet.find(ageFacetObj => ageFacetObj.default === true).id,
        time: window.page.timeFacet.find(timeFacetObj => timeFacetObj.default === true).id
    };

    $scope.selectedClub = window.page.preferredClub;

    $scope.productList = [];
    $scope.upgradeList = [];
    $scope.allProducts = [];
    $scope.multiclubData = {};
    $scope.currentPromoProduct = '';
    $scope.oldAgeValue = '';

    $scope.init = function () {
        $scope.clubList = window.clubList;
        $scope.actionSearchProd(true);
        $scope.checkActive12Empty();
    };

    $scope.checkActive12Empty = async function () {
        const filters = JSON.parse(JSON.stringify($scope.filters));
        filters.duration = $scope.getActive12FilterId();
        filters.age = $scope.getTuttiFilterId();
        filters.time = $scope.getSempreFilterId();
        dataFactory.getProducts(
            $scope.selectedClub,
            filters
        ).then(function successCallback(response) {

            if(response.data.results.length == 0) {
                $scope.disableBtn($scope.getActive12BtnUI());
                if ($scope.filters.duration == $scope.getActive12FilterId()) {
                    $scope.filters.duration = $scope.get12MesiFilterId();
                    $scope.actionSearchProd();
                }
            } else {
                $scope.enableBtn($scope.getActive12BtnUI());
            }

        }, function errorCallback(response) {

            console.error('Response: ', response);
        });
    }

    $scope.actionSearchProd = function (init, showTextLoading = false) {

        modalService.showLoader(showTextLoading);

        $scope.checkIntegrityRequest();

        document.getElementById('vrgnCartSummaryRecap').style.display = 'none';

        if (!init) {
            $scope.resetColorLevelChange();
        }

        dataFactory.getProducts(
            $scope.selectedClub,
            $scope.filters
        ).then(function successCallback(response) {

            $scope.productList = response.data.results;

            if ($scope.productList.length > 0 && $scope.productList[0].upgrades) {
                $scope.upgradeList = $scope.productList[0].upgrades;
                $scope.allProducts = $scope.productList.concat($scope.productList[0].upgrades);
            }

            $scope.resetColorLevelChange();

            $scope.checkFilters();

            $scope.oldAgeValue = $scope.filters.age;

            modalService.hideLoader();

        }, function errorCallback(response) {

            console.error('Response: ', response);
        });
    };

    $scope.checkIntegrityRequest = function () {
        if ($scope.isSpecialAgeChecked() && ($scope.filters.age != $scope.oldAgeValue)) {
            $scope.filters.time = $scope.getSempreFilterId();
        } else if ($scope.isDayNightChecked()) {
            $scope.filters.age = $scope.getTuttiFilterId();
        }

        if ($scope.shouldDisableDaynightTutti()) {
            $scope.filters.age = $scope.getTuttiFilterId();
            $scope.filters.time = $scope.getSempreFilterId();
        }
    }

    $scope.shouldDisableDaynightTutti = function () {
        return $scope.isActive12Checked() || $scope.isSmartChecked();
    }

    $scope.get12MesiFilterId = function () {
        return window.page.durationFacet.find((e) => e.name == FILTER_12_MESI).id;
    }

    $scope.getActive12FilterId = function () {
        return window.page.durationFacet.find((e) => e.name == FILTER_ACTIVE_12).id;
    }

    $scope.getTuttiFilterId = function () {
        return window.page.ageFacet.find((e) => e.name == FILTER_TUTTI).id;
    }

    $scope.getSempreFilterId = function () {
        return window.page.timeFacet.find((e) => e.name == FILTER_SEMPRE).id;
    }

    $scope.checkFilters = function () {
        $scope.enableAgeFilters();
        $scope.enableTimeFilters();

        if ($scope.shouldDisableDaynightTutti()) {
            $scope.disableBtn($scope.getSpecialAgeBtnUI());
            $scope.disableBtn($scope.getDayNightBtnUI());
        }
    }

    /* ButtonUI getters */
    $scope.getSpecialAgeBtnUI = function () {
        return document.getElementById(FILTER_SPECIAL_AGE).parentNode;
    }

    $scope.getDayNightBtnUI = function () {
        return document.getElementById(FILTER_DAY_NIGHT).parentNode;
    }

    $scope.getSempreBtnUI = function () {
        return document.getElementById(FILTER_SEMPRE).parentNode;
    }

    $scope.getTuttiBtnUI = function () {
        return document.getElementById(FILTER_TUTTI).parentNode;
    }

    $scope.getActive12BtnUI = function () {
        return document.getElementById(FILTER_ACTIVE_12).parentNode;
    }

    /* ButtonUI getters */
    $scope.getSpecialAgeBtn = function () {
        return $scope.getFilterBtnById(FILTER_SPECIAL_AGE);
    }

    $scope.getDayNightBtn = function () {
        return $scope.getFilterBtnById(FILTER_DAY_NIGHT);
    }

    $scope.getSempreBtn = function () {
        return $scope.getFilterBtnById(FILTER_SEMPRE);
    }

    $scope.getTuttiBtn = function () {
        return $scope.getFilterBtnById(FILTER_TUTTI);
    }

    /* Button checkers */
    $scope.isActive12Checked = function () {
        return $scope.isDurationBtnChecked(FILTER_ACTIVE_12);
    }

    $scope.isSmartChecked = function () {
        return $scope.isDurationBtnChecked(FILTER_SMART);
    }

    $scope.isSpecialAgeChecked = function () {
        return $scope.isAgeBtnChecked(FILTER_SPECIAL_AGE);
    }

    $scope.isDayNightChecked = function () {
        return $scope.isTimeBtnChecked(FILTER_DAY_NIGHT);
    }

    $scope.isDurationBtnChecked = function (id) {
        return window.page.durationFacet.some((e) => e.id == $scope.filters.duration && e.name == id);
    }

    $scope.isAgeBtnChecked = function (id) {
        return window.page.ageFacet.some((e) => e.id == $scope.filters.age && e.name == id);
    }

    $scope.isTimeBtnChecked = function (id) {
        return window.page.timeFacet.some((e) => e.id == $scope.filters.time && e.name == id);
    }

    /* Visibility utils */
    $scope.enableAgeFilters = function () {
        $scope.enableGroupFilters(document.getElementById('ageGroup'));
    }

    $scope.enableTimeFilters = function () {
        $scope.enableGroupFilters(document.getElementById('timeGroup'));
    }

    $scope.enableGroupFilters = function (group) {
        Array.from(group.children).map((e) => $scope.enableBtn(e));
    }

    $scope.disableBtn = function (btn) {
        btn.classList.add('disabled');

        // change the tip to warn that the product is not available
        const tooltip = btn.querySelector('.tooltipWrapper');
        if (tooltip) {
            tooltip.querySelector('.description').classList.add('tooltipHours-disabled');
            tooltip.querySelector('.unavailableProductClubTooltipText').classList.remove('tooltipHours-disabled');
        }
    }

    $scope.enableBtn = function (btn) {
        btn.classList.remove('disabled');

        // change the tip to warn that the product is available
        const tooltip = btn.querySelector('.tooltipWrapper');
        if (tooltip) {
            tooltip.querySelector('.description').classList.remove('tooltipHours-disabled');
            tooltip.querySelector('.unavailableProductClubTooltipText').classList.add('tooltipHours-disabled');
        }
    }

    /* Html element utils */
    $scope.getFilterBtnById = function (id) {
        const inputId = document.getElementById(id).parentNode.getAttribute('for');
        return document.querySelector(`input[id='${inputId}']`);
    }

    $scope.onClickOpenModal = function (modalId) {
        document.getElementById(modalId).style.display = 'block';
        document.body.style.overflow = 'hidden';
    };

    $scope.onClickCloseModal = function (modalId) {
        document.getElementById(modalId).style.display = 'none';
        document.body.style.overflow = 'auto';

        // Remove the appended HTML
        if (modalId === 'vrgnCfgSpecialPromo' || modalId === 'vrgnCfgUpdatePrivacy') {
            const appendedPromoHTML = document.querySelectorAll(`#${modalId} [data-promo-index]`).length > 0;

            if (appendedPromoHTML) {
                document.querySelectorAll(`#${modalId} [data-promo-index]`).forEach(element => element.remove());
            }
        }
    };

    $scope.onClickOpenCashbackModal = function (modalId) {
        const el = document.querySelector('div[data-cashbackmodal-id=c' + modalId +']');
        if(el) {
            el.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }
    };

    $scope.onClickCloseCashbackModal = function (modalId) {
        const el = document.querySelector('div[data-cashbackmodal-id=c' + modalId +']');
        if(el) {
            el.style.display = 'none';
            document.body.style.overflow = 'auto';
        }

    };

    $scope.onClickSelectClub = function (club) {

        $scope.selectedClub = club;

        $scope.actionSearchProd(null, true);
        $scope.onClickCloseModal('vrgnClubSelectionDialog');
        $scope.checkActive12Empty();
    };

    $scope.onClickOpenMulticlub = function (prodId) {
        modalService.showLoader();

        dataFactory.getClubs(
            $scope.selectedClub.id, prodId
        ).then(function successCallback(response) {


            $scope.multiclubData = response.data.url;

            modalService.openModal('vrgnCfgMulticlubDialog');
            modalService.hideLoader();

        }, function errorCallback(response) {
            modalService.hideLoader();
            console.error('Response: ', response);
        });
    };

    $scope.openModalSpecialPromo = function (selectedCard) {

        // Store the current clicked product, so that we can use it in the modal.
        $scope.currentPromoProduct = selectedCard.prod;

        modalService.showLoader();

        if ($scope.updatePrivacy) {

            /* CASE: User has changed privacy value via button in previous modal (NO RELOAD) */

            $scope.updateModalPromoData('vrgnCfgSpecialPromo');
            modalService.openModal('vrgnCfgSpecialPromo');
        } else {

            /* CASE: User privacy is `true` (ON PAGE LOAD) */

            $scope.updateModalPromoData('vrgnCfgUpdatePrivacy');
            modalService.openModal('vrgnCfgUpdatePrivacy');
        }

        modalService.hideLoader();

    };

    $scope.openModalQuotation = function () {

        modalService.showLoader();

        modalService.openModal('quotationPopUp');

        modalService.hideLoader();
    };

    $scope.onClickOpenCartSummary = function (selectedCard) {

        dataFactory.getCartRecap(
            selectedCard.prod.id
        ).then(function successCallback(response) {

            $scope.selectedProductCartRecap = response.data.results;
            document.getElementById('vrgnCartSummaryRecap').style.display = 'flex';
            const hiddenProductIdField = document.createElement('input');
            hiddenProductIdField.type = 'hidden';
            hiddenProductIdField.value = selectedCard.prod.id;
            hiddenProductIdField.name = 'productId';
            document.getElementById('registrationUserFormCheckout').appendChild(hiddenProductIdField);
            document.getElementById('loginUserForm').appendChild(hiddenProductIdField);

            $scope.onColorLevelChange(selectedCard.prod);

        }, function errorCallback(response) {

            document.getElementById('vrgnCartSummaryRecap').style.display = 'none';
            console.error('Response Error : ', response);
        });

    };

    $scope.resetColorLevelChange = function () {

        const overrideColor = true;

        let isPromoDaPaura = false;
        if ($scope.productList[0] && 'undefined' !== typeof $scope.productList[0].badgeText && $scope.productList[0].badgeText === 'Promo da paura'){
            isPromoDaPaura = true;
        }

        for (let i = 0; i < document.getElementsByClassName('vrgnCfgFilterGroup').length; i++) {

            for (let x = 0; x < document.getElementsByClassName('vrgnCfgFilterGroup')[i].children.length; x++) {

                if (document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].checked == true) {

                    var radioChecked =  document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].nextElementSibling.children[0];

                    if (overrideColor) {
                        radioChecked.style.background = '#E10A0A';
                    } else {
                        radioChecked.style.background = '#3e3e3e';
                    }

                    if (document.getElementsByClassName($scope.cardBackground).length != 0) {
                        radioChecked.classList.remove($scope.cardBackground)
                    }

                } else if (document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].checked == false) {

                    var radioNotChecked =  document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].nextElementSibling.children[0];

                    radioNotChecked.style.background = '#f7f6f9';

                    if (document.getElementsByClassName($scope.cardBackground).length != 0) {
                        radioNotChecked.classList.remove($scope.cardBackground)
                    }
                }

                if (document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].children[0]) {
                    const obj = document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].children[0];
                    if (isPromoDaPaura && (obj.id == '12' || obj.id == FILTER_SPECIAL_AGE || obj.id == FILTER_DAY_NIGHT)) {
                        obj.style.background = '#E10A0A';
                    }
                }
            }
        }
    }

    $scope.onColorLevelChange = function (selectedCard) {

        // REFACTORING

        $scope.resetColorLevelChange()

        const overrideColor = true;
        const overrideGroupColor = 1;

        if (overrideColor) {
            selectedCard.level = overrideGroupColor;
        }

        $scope.cardBackground = 'card-background-' + selectedCard.level;
        var cardBackground = 'card-background-' + selectedCard.level;
        var cardBorder= 'card-border-' + selectedCard.level;

        for (let i = 0; i < document.getElementsByClassName('vrgnCfgFilterGroup').length; i++) {

            for (let x = 0; x < document.getElementsByClassName('vrgnCfgFilterGroup')[i].children.length; x++) {

                if (document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].checked == true) {

                    var radioChecked =  document.getElementsByClassName('vrgnCfgFilterGroup')[i].children[x].nextElementSibling.children[0];

                    radioChecked.classList.add(cardBackground)

                }

            }
        }

        var card = 'card_' + selectedCard.id;

        const vrgnCartCheckout = document.getElementsByClassName('vrgnCartCheckout')[0]
        vrgnCartCheckout.className = vrgnCartCheckout.className.replace(/\bcard-background-+?/g, '');

        const rightSectionVrgnCart = document.getElementsByClassName('rightSectionVrgnCart')[0]
        rightSectionVrgnCart.className = rightSectionVrgnCart.className.replace(/\bcard-background-+?/g, '');

        for (let i = 0; i < document.getElementsByClassName('vrgnCgfCardButtonContainer').length; i++) {

            if (!(document.getElementsByClassName('vrgnCgfCardButtonContainer')[i].classList.contains(card))) {

                const vrgnCgfCardButtonContainer = document.getElementsByClassName('vrgnCgfCardButtonContainer')[i]

                vrgnCgfCardButtonContainer.className = vrgnCgfCardButtonContainer.className.replace(/\bcard-background-+?/g, '');

                vrgnCgfCardButtonContainer.children[0].className = vrgnCgfCardButtonContainer.children[0].className.replace(/\bcard-background-+?/g, '');

                vrgnCgfCardButtonContainer.children[0].style.cssText = 'border: 1px solid #000'
                vrgnCgfCardButtonContainer.children[0].children[0].style.cssText = 'display : none;'

                vrgnCgfCardButtonContainer.parentElement.className  = vrgnCgfCardButtonContainer.parentElement.className.replace(/\bcard-border-+?/g, '');
            }

        }

        document.getElementsByClassName(card)[0].classList.add(cardBackground);

        document.getElementsByClassName(card)[0].children[0].classList.add(cardBackground);

        document.getElementsByClassName(card)[0].children[0].style.cssText = 'border: 0px;'

        document.getElementsByClassName(card)[0].children[0].children[0].style.cssText = 'display : block; fill : #fff;'

        document.getElementsByClassName(card)[0].parentElement.classList.add(cardBorder);

        document.getElementsByClassName('vrgnCartCheckout')[0].classList.add(cardBackground);

        document.getElementsByClassName('rightSectionVrgnCart')[0].classList.add(cardBackground);


    };

    $scope.openModalChangePersonalData = function () {

        modalService.showLoader();

        modalService.openModal('vrgnCfgChangeData');

        modalService.hideLoader();
    };

    $scope.updateUserData = function (event) {

        // gestione nome parent nello scope

        $scope.tempFirstName = document.getElementsByName('firstName')[0].value;

        var formDataArray = $('#formChangeData').serializeArray();
        var formData = new FormData();

        for (var key in formDataArray) {
            formData.append(formDataArray[key].name, formDataArray[key].value)
            if(formDataArray[key].name == 'email'){
                var newEmail = formDataArray[key].value;
            }
            if(formDataArray[key].name == 'addUser'){
                var newUser = formDataArray[key].value;
            }
            if(formDataArray[key].name == 'privacy'){
                $scope.specialPrimoPrivacyUpdate = formDataArray[key].value == 0 ? false : true;
                // HACK to show/hide the different prices, depending on the privacy value
                if($scope.specialPrimoPrivacyUpdate){
                    $scope.showPromoDiscounts();
                }
            }
        }

        if(typeof newUser == 'undefined'){
            $scope.customerNewEmail = newEmail;
            localStorage.setItem('userEmail', newEmail);
        }


        $http({
            method: 'POST',
            url: 'configurator/editData',
            headers: {'Content-Type': undefined },
            data: formData
        }).then(function successCallback(response) {
            if (response.data.error) {
                $scope.updateDataError = response.data.messageSnippet;
            } else {
                $scope.updateDataError = '';
                if (newUser) {
                    $scope.productList = response.data.results;
                }
                $scope.onClickCloseModal('vrgnCfgChangeData');
            }

            const submit = event.target;
            $scope.removeSwButtonLoader(submit);

        }, function errorCallback(response) {
            console.log(response)
        });

    };

    $scope.updateUserDataValues = function (event, addUser) {
        const reset = !addUser;

        $scope.customerFirstName = !reset ? window.context.customer.firstName : '';
        $scope.customerLastName = !reset ? window.context.customer.lastName : '';
        $scope.customerEmail = !reset ? window.context.customer.email : '';
        $scope.customerPhone = !reset ? window.context.customer.customFields.phone_number : '';
    };

    $scope.updateUserPrivacy = function (arg) {

        var formDataArray = $('#formUpdatePrivacy').serializeArray();
        var formData = new FormData();

        $scope.updatePrivacy = arg;

        for (var key in formDataArray) {
            formData.append(formDataArray[key].name, formDataArray[key].value);
        }
        formData.append('privacy', arg);

        if (arg == true) {

            $scope.updateImplicitRegistrationPrivacy();
            /* CASE: User has changed privacy value to `true` via button in previous modal */
            document.getElementById('vrgnCartSummaryRecap').style.display = 'none';
            $scope.resetColorLevelChange();
            for (let i = 0; i < document.getElementsByClassName('vrgnCgfCardButtonContainer').length; i++) {


                const vrgnCgfCardButtonContainer = document.getElementsByClassName('vrgnCgfCardButtonContainer')[i];

                vrgnCgfCardButtonContainer.className = vrgnCgfCardButtonContainer.className.replace(/\bcard-background-+?/g, '');

                vrgnCgfCardButtonContainer.children[0].className = vrgnCgfCardButtonContainer.children[0].className.replace(/\bcard-background-+?/g, '');

                vrgnCgfCardButtonContainer.children[0].style.cssText = 'border: 1px solid #000';
                vrgnCgfCardButtonContainer.children[0].children[0].style.cssText = 'display : none;';

                vrgnCgfCardButtonContainer.parentElement.className  = vrgnCgfCardButtonContainer.parentElement.className.replace(/\bcard-border-+?/g, '');

            }
            $scope.onClickCloseModal('vrgnCfgUpdatePrivacy');
            $scope.specialPrimoPrivacyUpdate = true;

            $scope.updateModalPromoData('vrgnCfgSpecialPromo');

            // HACK to show/hide the different prices, depending on the privacy value
            $scope.showPromoDiscounts();

            modalService.openModal('vrgnCfgSpecialPromo');

            $http({
                method: 'POST',
                url: 'configurator/privacyUpdate',
                headers: {'Content-Type': undefined },
                data: formData
            }).then(function successCallback(response) {
                console.log(response)
            }, function errorCallback(response) {
                console.log(response)
            });
        } else if (arg == null) {
            $scope.onClickCloseModal('vrgnCfgUpdatePrivacy');
        }

    };

    $scope.updateImplicitRegistrationPrivacy = function () {
        const form = document.querySelector('#registrationUserFormCheckout');
        const privacyCheckboxes = document.querySelector('.vrgnPrivacy');
        const checkboxSi = document.querySelector('#registrationPrivacySi');
        const checkboxNo = document.querySelector('#registrationPrivacyNo');

        if (form && privacyCheckboxes && checkboxSi) {
            privacyCheckboxes.classList.add('d-none');
            checkboxSi.checked = true;
            if (checkboxNo) {
                checkboxNo.checked = false;
            }
        }
    }

    $scope.saveQuotation = function () {

        var formDataArray = $('#formSaveQuotation').serializeArray();
        var formData = new FormData();

        for (var key in formDataArray) {
            formData.append(formDataArray[key].name, formDataArray[key].value)
        }

        $http({
            method: 'POST',
            url: 'configurator/quotation',
            headers: {'Content-Type': undefined },
            data: formData
        }).then(function successCallback(response) {
            if (response.data.success) {
                $scope.onClickCloseModal('quotationPopUp');
                $scope.selectedProductCartRecap.quotationAvailable = false;
            } else {
                $scope.saveQuotationError = response.data.snippetMessage;
            }
        }, function errorCallback(response) {
            console.log(response)
        });
    }

    $scope.loginUser = function (event) {

        // add loading animation
        const loader = new ButtonLoadingIndicator(document.querySelector('#loginUserForm > .loginButton'));
        loader.create();

        const submit = event.target;
        const form = submit.form;
        const formData = new FormData(form);
        const email = form.querySelector('[name="username"]').value;
        const password = form.querySelector('[name="password"]').value;

        if (email !== '' && password !== '') {

            $http({
                method: 'POST',
                url: 'configurator/login',
                headers: {'Content-Type': undefined },
                data: formData
            }).then(function successCallback(response) {
                loader.remove();
                if (response.data.success) {
                    $scope.loginError = '';
                    location.reload();
                } else {
                    $scope.loginError = response.data.messageSnippet;
                }

                $scope.removeSwButtonLoader(submit);

            }, function errorCallback(response) {
                loader.remove();
                console.log(response)
            });

        } else {
            $scope.loginError = 'Inserisci tutti i campi necessari'
        }
    };

    $scope.registrationUser = function () {

        // add loading animation
        const loader = new ButtonLoadingIndicator(document.querySelector('#registrationUserForm > .registrationButton'));
        loader.create();

        var formDataArray = $('#registrationUserForm').serializeArray();
        var formData = new FormData();

        for (var key in formDataArray) {
            formData.append(formDataArray[key].name, formDataArray[key].value)
        }

        $http({
            method: 'POST',
            url: 'configurator/register',
            headers: {'Content-Type': undefined },
            data: formData
        }).then(function successCallback(response) {
            loader.remove();
            if (response.data.success) {
                $scope.registrationError = '';
                location.reload();
            } else {
                $scope.registrationError = response.data.messageSnippet;
            }
        }, function errorCallback(response) {
            loader.remove();
            console.log(response)
        });

    };

    $scope.checkUncheckPrivacyUpdateData = function(event){

        if ($scope.formUpdateData.privacy == event.target.value)
            $scope.formUpdateData.privacy = '';
    };

    $scope.checkUncheckPrivacyRegistration = function(event){

        if ($scope.formRegisterData.privacy == event.target.value)
            $scope.formRegisterData.privacy = '';
    };

    /**
     * Remove appended Shopware loader
     *
     * INFO: By using `data-form-submit-loader="true"` on the button[type="submit"],
     *       a SW-plugin is triggered and a loader element will appended to it and the button disabled.
     *
     * @param submit - The submit button
     */
    $scope.removeSwButtonLoader = function (submit) {
        const loaderAttr = submit.hasAttribute('data-form-submit-loader');

        if (!loaderAttr) return;

        const loader = submit.querySelector('.loader');
        submit.removeAttribute('disabled');
        loader.remove();
    };

    /**
     * Handles the display of active promotion list in the modal
     *
     * @param {String} modalId - The ID of promo modal
     */
    $scope.updateModalPromoData = function (modalId) {
        const prodData = $scope.currentPromoProduct;
        const promoList =  document.querySelector(`#${modalId} .promo-list-target`);

        if (!promoList) {
            return;
        }

        const promoDeadlineLabelEl = document.querySelector(`#${modalId} .deadline-promo-label`);
        const promoDeadlineLabel = promoDeadlineLabelEl ? promoDeadlineLabelEl.textContent : '' ;
        const promos = $scope.getAllProductPromos(prodData);

        // Append HTML for each promo
        promos.forEach(function (promo, index) {
            const promoDesc = promo.extensions.virginPromotionAttributes[0].description;
            const promoTitle = promoDesc ? promoDesc : promo.name;

            let promoHtml = `
                <div class="promo content" data-promo-index="${index}">
                    <div class="promo-title">${promoTitle}</div>
                </div>
            `;

            if (promo.validUntil && promo.extensions.virginPromotionAttributes[0].hideEndDate !== true) {
                const validUntil = new Date(promo.validUntil).toLocaleDateString('it-it');
                promoHtml = `
                <div class="promo content" data-promo-index="${index}">
                    <div class="promo-title">${promoTitle}</div>
                    <div class="promo-deadline">${promoDeadlineLabel} ${validUntil} </div>
                </div>
            `;
            }

            promoList.innerHTML += promoHtml;
        });
    };

    /**
     * Get all special promotions of current product (on clicked card promo batch)
     *
     * @param {String} prodData - The data of the current card
     *
     * @return {object} promos - All promos
     */
    $scope.getAllProductPromos = function (prodData) {
        const promos = [];

        prodData.promo.exerpPromo.forEach(function (exerpPromo) {
            if (exerpPromo.active) {
                promos.push(exerpPromo);
            }
        });

        prodData.promo.swPromo.forEach(function (swPromo) {
            if (swPromo.active) {
                promos.push(swPromo);
            }
        });

        return promos;
    };

    /**
     * Check if promotions are available
     *
     * INFO: The return is NOT working correctly right now. So we use an override CSS-HACK: `d-block`
     * @param {object} selectedCard - The ID of promo modal
     *
     * @return {boolean} result - Returns true/false, when promos are available.
     */
    $scope.specialPromoAvailable = function (selectedCard) {
        const prodData = selectedCard.prod;
        const promos = $scope.getAllProductPromos(prodData);
        const result = promos.length > 0;

        $scope.specialPromos = promos.length;

        if ($scope.specialPromos) {
            // HACK: Override the `d-none`!!!
            document.querySelector(`#prod_${selectedCard.prod.id} .vrgnCgfSpecialPromo`).classList.add('d-block');
        }

        return result;
    };

    /**
     * FRONTEND HACK:
     * Set class to `.vrgnCardContainer` element, to show/hide the promo prices by CSS depends on the privacy value.
     */
    $scope.showPromoDiscounts = function () {
        document.querySelector('.vrgnCardContainer').classList.remove('privacy-no');
        document.querySelector('.vrgnCardContainer').classList.add('privacy-yes');
        const vrgnCgfCardCashback = document.querySelector('.vrgnCgfCardCashback');
        if(vrgnCgfCardCashback) {
            vrgnCgfCardCashback.style.display = 'block';
        }
    };

    $scope.init();

}]);

export default ConfiguratorApp;