var Wick = Wick || {};
Wick.PDPti = (function () {

    let tiObj = {
        system: {
            floors: $('.ti-floor'),
        },
        startingInfo: {
            sqmPERpack: 1.25,
            pricePERpack: 14.04
        },
        userInfo: {
            minPostPrice: 99.9,
            totalWaste: true,
            postCode: '',
            disposal: false,
            disposalArea: 0,
            tilingOptions: []
        }
    };
    let scrollDelay = 500;
    let tileEstimateInfo = $('#info-tile-estimation');
    let totalAreaInput = $('.ti-total-area__input-total');
    let quantityInput = '.ti-total-area__input-quantity';
    let bannerHeight = 0;
    if ($('.sticky-wrapper').length) {
        bannerHeight = $('.sticky-wrapper').eq(0).height();
    }
    let minMeasure = '5.0';
    let measure = 'metres';

    // FLOOR START
    let addFloorBtn = $('.ti-floor__add-floor');
    let closeFloorBtn = $('.ti-floor__close');
    let floorInputs = $('.ti-floor input');

    floorInputs.on('input', function () {
        let x = $(this).closest('.ti-floor').find('input');
        let y = $(this).closest('.ti-floor').find('.ti-floor__result-value');
        let x1 = x.eq(0).val();
        let x2 = x.eq(1).val();
        let area = (x1 * x2);
        const context = $(this).closest('.ti__estimate');

        if (area !== 0) {
            y.text(+area.toFixed(2));
        } else {
            y.text(0);
        }
        updateFloorArea(context);
    });

    closeFloorBtn.on('click', function () {
        const context = $(this).closest('.ti__estimate');
        $(this).closest('.ti-floor').remove();
        tiObj.system.floors = $('.ti-floor');
        updateFloorArea(context);
    });

    let cloneFloor = $('.ti-floor').eq(0).clone(true);

    addFloorBtn.on('click', function () {
        const context = $(this).closest('.ti__estimate');
        $(this).before(cloneFloor.clone(true));
        tiObj.system.floors = $('.ti-floor');
        updateFloorArea(context);
    });

    function updateFloorArea(context) {
        let results = context.find('.ti-floor__result-value'),
            resultValue = 0;

        for (let i = 0; i < tiObj.system.floors.length; i++) {
            if ($(results[i]).text() === '-') {
                continue
            }
            resultValue += +$(results[i]).text();
        }
        if (resultValue > 0) {
            context.find('.ti-total-area__input-total').val(resultValue);
            checkTotal(context);
            updateTotals(context);
        }
    }

    // FLOOR END

    let wastageInput = '#wastage';
    let wastageInput1 = '#wastage_measurement';

    let notificationAccordion = '.ti-total-area__detail-name_accordion';

    $(wastageInput).change(function () {
        calculationWastage(wastageInput);
    });

    $(wastageInput1).change(function () {
        calculationWastage(wastageInput1);
    });


    function calculationWastage(wastage) {
        const context = $(wastage).closest('.ti__estimate');

        if ($(wastage).attr('checked') === 'checked') {
            $(wastage).removeAttr('checked');
            tiObj.userInfo.totalWaste = false;
            if (context.find(notificationAccordion).hasClass('collapsed')) {
                context.find(notificationAccordion).click();
            }
        } else {
            $(wastage).attr('checked', 'checked');
            tiObj.userInfo.totalWaste = true;
        }
        context.find('.ti__total').toggleClass('ti__total-waste');
        updateTotals(context);
    }

    let calculationContent = $('#tile-calculation-content');
    let calculationInfo = $('#info-tile-calculation');
    let unitSmall = '.ti-unit_small';
    let unitBig = '.ti-unit_big';
    let calcWrapper = $(".pdp-price__calculator-wrapper");
    let tileEsimateMeasurement = $('#open-tile-estimation_measurement');
    let unitSelect = $(".unit-selection");
    let tileEstimateContent = $('#tile-estimation-content');
    let warningValue = '.ti__warning-value';
    let warningMeasurement = '.ti__warning-measurement';

    calcWrapper.on('click', function (e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: ($(calculationInfo).offset().top - bannerHeight)
        }, scrollDelay);
        calculationContent.css('display', 'block');
        calculationInfo.removeClass('accordion_collapsed');
    });

    tileEsimateMeasurement.on('click', function (e) {
        e.preventDefault();
        const context = $(this).closest('.ti');
        if (checkTotal(context) === true) {
            context.find('#ti_total-area').removeClass('ti__floors-invalid');

            $('#info-tile-estimation').removeClass('accordion_collapsed');
            $('#tile-estimation-content').show();

            $('#info-tile-calculation').addClass('accordion_collapsed');
            $('#tile-calculation-content').hide();

            resetCalculator(context);

        } else {
            tiObj.system.notification1 = Wick.Notification.show({
                text: `You need to add a wall/floor area or enter a total area of at least ${minMeasure} square ${measure} to continue to the next step of your estimate`,
                container: $(this).parents('.ti__step').find('.ti__error'),
                type: 'error',
                noScrolling: true,
            });

            context.find('#ti_total-area').addClass('ti__floors-invalid');
        }
    });


    unitSelect.on('change', function () {
        const context = $(this).parents('.ti');

        switch ($(this).val()) {
            case 'feet':
                context.find(unitSmall).html('ft');
                context.find(unitBig).html('FT');
                minMeasure = '54.0';
                measure = 'feet';
                measureAbbr = 'SQFT';
                break;
            case 'metres':
                context.find(unitSmall).html('m');
                context.find(unitBig).html('M');
                minMeasure = '5.0';
                measure = 'metres';
                measureAbbr = 'SQM';
                break;
            case 'cm':
                context.find(unitSmall).html('cm');
                context.find(unitBig).html('CM');
                minMeasure = '50000.0';
                measure = 'cm';
                measureAbbr = 'SQCM';
                break;
            case 'inches':
                context.find(unitSmall).html('in');
                context.find(unitBig).html('IN');
                minMeasure = '7750.0';
                measure = 'inches';
                measureAbbr = 'SQIN';
                break;
            default:
                context.find(unitSmall).html('m');
                context.find(unitBig).html('M');
                minMeasure = '5.0';
                measure = 'metres';
                measureAbbr = 'SQM';
        }

        if (tiObj.system.notification1) {
            tiObj.system.notification1.hide();
        }

        context.find(warningValue).text(minMeasure);
        context.find(warningMeasurement).text(measureAbbr);
    });

    let step1Next = $('.ti__step1 .ti__next .btn');
    let step2Next = $('.ti__step2 .ti__next .btn');
    let step3Next = $('.ti__step3 .ti__next .btn');

    step1Next.on('click', function () {
        const context = $(this).closest('.ti');
        if (checkTotal(context) === true) {
            context.find('.ti__floors').removeClass('ti__floors-invalid');
            goToStep2(context);
        } else {
            tiObj.system.notification1 = Wick.Notification.show({
                text: 'You need to add a wall/floor area or enter a total area of at least 5 square metres to continue to the next step of your estimate',
                container: $(this).parents('.ti__step').find('.ti__error'),
                type: 'error',
                noScrolling: true,
                //temporary: true,
                //closeBtn: true,
                //delay: 1000
            });

            context.find('.ti__floors').addClass('ti__floors-invalid');
        }
    });

    step2Next.on('click', function () {
        let optionsSelected = optionsItems.filter(function () {
            return $(this).attr('checked') === 'checked';
        });
        let optionsBlock = $('.ti__cost_options');
        let radioChose = removalRadio.filter(function () {
            return $(this).attr('checked') === 'checked';
        });
        let radioLevelling = removalRadioLevelling.filter(function () {
            return $(this).attr('checked') === 'checked';
        });
        let radioBlock = $('.ti__cost_removal');
        let radioBlockLevelling = $('.ti__cost_levelling');
        let postCodeValue = $('.ti__cost_postcode input').val();
        let postCodeBlock = $('.ti__cost_postcode');

        if (postCodeValue.length > 4 && radioChose.length && optionsSelected.length && isLevellingBlockOpen(radioLevelling.length)) {
            if (tiObj.system.notification2) {
                tiObj.system.notification2.hide();
            }
            optionsBlock.removeClass('ti__cost-invalid');
            radioBlock.removeClass('ti__cost-invalid');
            radioBlockLevelling.removeClass('ti__cost-invalid');
            postCodeBlock.removeClass('ti__cost-invalid');
            tiObj.userInfo.tilingOptions = [];
            optionsSelected.map(function () {
                tiObj.userInfo.tilingOptions.push($(this).siblings('span').text());
            });
            tiObj.userInfo.disposal = radioChose.siblings('span').text() === 'Yes';
            tiObj.userInfo.disposalArea = +disposalInput.val();
            tiObj.userInfo.postCode = postCodeValue;
            goToStep3();
        } else {
            tiObj.system.notification2 = Wick.Notification.show({
                text: 'Please answer the questions above before continuing.',
                container: $(this).parents('.ti__step').find('.ti__error'),
                type: 'error',
                noScrolling: true,
                //temporary: true,
                //closeBtn: true,
                //delay: 1000
            });
            optionsBlock.removeClass('ti__cost-invalid');
            radioBlock.removeClass('ti__cost-invalid');
            radioBlockLevelling.removeClass('ti__cost-invalid');
            postCodeBlock.removeClass('ti__cost-invalid');

            if (!optionsSelected.length) {
                optionsBlock.addClass('ti__cost-invalid');
            }
            if (!radioChose.length) {
                radioBlock.addClass('ti__cost-invalid');
            }
            if (!(postCodeValue.length > 4)) {
                postCodeBlock.addClass('ti__cost-invalid');
            }
            if (!radioLevelling.length) {
                radioBlockLevelling.addClass('ti__cost-invalid');
            }
        }
    });

    let checkBox2 = $('.choose__callback input.form-toggler');
    let formDetails = $('.form-details');
    let innerRow = $('.form-details .form-row');

    checkBox2.change(function () {
        if ($(this).hasClass('form-toggler-on')) {
            formDetails.addClass('form-details_open');
        } else {
            formDetails.removeClass('form-details_open');
        }
    });

    step3Next.on('click', function () {
        let chooseCallback = $(".choose__callback");
        let contactInfo = [];


        if (formDetails.hasClass('form-details_open')) {
            innerRow.each(function () {
                if ($(this).find('input').val() === "") {
                    $(this).find(".form-row__error").css("display", "block");
                    $(this).find('input').css("border", "1px solid #cf000f");
                    contactInfo.push(0)
                } else {
                    $(this).find(".form-row__error").css("display", "none");
                    $(this).find('input').css("border", "1px solid #ccc");
                    contactInfo.push(1)
                }
            })

        }

        function checkContactInfo() {
            if (formDetails.hasClass('form-details_open')) {
                return contactInfo.every((item) => item !== 0);
            } else {
                return true;
            }
        }

        let hasContactInfo = checkContactInfo();

        if (tiObj.userInfo.finalChoose && hasContactInfo) {
            if (tiObj.system.notification3) {
                tiObj.system.notification3.hide();
            }
            chooseCallback.removeClass('red-border');

            if (tiObj.userInfo.finalChoose == 'Call me to discuss installation') {
                $('#modal-thank-you').modal();
            }
        } else {
            tiObj.system.notification3 = Wick.Notification.show({
                text: 'Please answer the questions above before continuing.',
                container: $(this).parents('.ti__step').find('.ti__error'),
                type: 'error',
                noScrolling: true,
                //temporary: true,
                //closeBtn: true,
                //delay: 1000
            });
            chooseCallback.addClass('red-border');
        }
    });

    totalAreaInput.on('input', function () {
        const context = $(this).closest('.ti__estimate');
        checkTotal(context);
        updateTotals(context);
        resetFloors(tiObj.system.floors)
    });


    function checkTotal(context) {
        if (!context.hasClass('tile-measurement')) {
            let inputValue = parseInt(context.find('.ti-total-area__input-total').val());
            if (inputValue < +minMeasure || isNaN(inputValue)) {
                context.find('.ti__total').addClass('less-then-5');
            } else {
                context.find('.ti__total').removeClass('less-then-5');
                if (tiObj.system.notification1) {
                    tiObj.system.notification1.hide();
                }
            }
            return !(inputValue < +minMeasure || isNaN(inputValue));
        } else {
            if (tiObj.system.notification1) {
                tiObj.system.notification1.hide();
            }
            context.find('.ti__total').removeClass('less-then-5');
        }
    }

    function resetFloors(floors) {
        for (let i = 0; i < floors.length; i++) {
            $(floors[i]).find('input').attr('placeholder', '-').val('');
            $(floors[i]).find('.ti-floor__result-value').text('-');
        }
    }

    function resetCalculator(context) {
        resetFloors(tiObj.system.floors);
        context.find('.ti-floor').not('.ti-floor:first').remove();
        tiObj.system.floors = $('.ti-floor');
        context.find('.ti-total-area__input-total').val('');
        updateTotals(context);
        context.find(quantityInput).val('');
        unitSelect.val('metres');

        context.find(unitSmall).html('m');
        context.find(unitBig).html('M');
        minMeasure = '5.0';
        measure = 'metres';
    }

    function updateTotals(context) {
        let wastage = 1.1;
        if (tiObj.userInfo.totalWaste === false) {
            wastage = 1;
        }
        let inputValue = context.find('.ti-total-area__input-total').val() * wastage;
        tiObj.userInfo.totalArea = +(inputValue / wastage).toFixed(2);
        tiObj.userInfo.totalWasteArea = +inputValue.toFixed(2);
        context.find('.ti-total-area__wastage-value').text(tiObj.userInfo.totalWasteArea);
        context.find('.ti-total-area__row-cost').text(tiObj.userInfo.totalWasteArea);
        tiObj.userInfo.packs = Math.ceil(inputValue / tiObj.startingInfo.sqmPERpack);
        context.find(quantityInput).val(tiObj.userInfo.packs);
        $('.ti__cost_removal-input input').val(+tiObj.userInfo.totalArea);
        $('.ti__cost_removal-value').text(+tiObj.userInfo.totalArea);
        context.find('.ti-total-area__row-number').text(tiObj.userInfo.packs);
        context.find('.ti-total-area__total-value').text('£' + (tiObj.userInfo.packs * tiObj.startingInfo.pricePERpack).toFixed(2));
        $('.ti__overview-price_total-value').text('£' + (tiObj.userInfo.packs * tiObj.startingInfo.pricePERpack + tiObj.userInfo.minPostPrice).toFixed(2) + '*');
    }

    let finalRadio = $('.ti__choose .form-toggler');
    $(finalRadio).change(function () {
        $(this).attr('checked', 'checked');
        finalRadio.not($(this)).removeAttr('checked');
        tiObj.userInfo.finalChoose = $(this).siblings('span').text();
    });

    let removalArea = $('.ti__cost_removal');
    let removalRadio = $('.ti__cost_removal-radio input');
    $(removalRadio).change(function () {
        $(this).attr('checked', 'checked');
        if ($(this).siblings('span').text() === 'Yes') {
            $(removalArea).addClass('ti__cost_removal-yes');
        } else {
            $(removalArea).removeClass('ti__cost_removal-yes');
        }
        removalRadio.not($(this)).removeAttr('checked');
    });

    let removalRadioLevelling = $('.ti__cost_levelling-radio input');
    $(removalRadioLevelling).change(function () {
        $(this).attr('checked', 'checked');
        removalRadioLevelling.not($(this)).removeAttr('checked');
    });

    let optionsItems = $('.ti__cost_options-list input');

    $(optionsItems).change(function () {
        if ($(optionsItems[optionsItems.length - 1]).attr('checked') === 'checked') {
            $(optionsItems[optionsItems.length - 1]).click();
        }
        if ($(optionsItems[optionsItems.length - 1])[0] === $(this)[0]) {
            let y = optionsItems.filter(function (item) {
                return item < optionsItems.length - 1;
            }).filter(function () {
                return $(this).attr('checked') === 'checked';
            });
            y.click();
        }

        if ($(this).attr('checked') === 'checked') {
            $(this).removeAttr('checked');
        } else {
            $(this).attr('checked', 'checked');
        }
    });

    let disposalInput = $('.ti__cost_removal-input input');

    disposalInput.change(function () {
        $('.ti__cost_removal-value').text($(this).val());
    });

    let concreteCbx = $('#concrete');
    let levellingBlock = $('.ti__cost_levelling');

    concreteCbx.on('click', function () {
        levellingBlock.toggleClass('ti__cost_levelling_open');
    });

    function isLevellingBlockOpen(y) {
        let x = $('.ti__cost_levelling_open').length;

        if (x) {
            if (y) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    function goToStep2(context) {
        context.find('.ti__step1').addClass('ti__step1-inactive');
        context.find('.ti__step2').addClass('ti__step2-active');
        context.find('.ti__step1 .ti__header').addClass('ti__header-inactive');
        context.find('.ti__step2 .ti__header').removeClass('ti__header-inactive');

        if (window.innerWidth > 767) {
            $('html, body').animate({scrollTop: $('#info-tile-estimation .ti__step1')[0].offsetTop - bannerHeight}, scrollDelay);
        } else {
            $('html, body').animate({scrollTop: $('#info-tile-estimation .ti__step2')[0].offsetTop - bannerHeight}, scrollDelay);
        }
    }

    function goToStep3() {
        $('.ti__step2').addClass('ti__step2-inactive').removeClass('ti__step2-active');
        $('.ti__step3').addClass('ti__step3-active');
        $('.ti__step2 .ti__header').addClass('ti__header-inactive');
        $('.ti__step3 .ti__header').removeClass('ti__header-inactive');

        $('html, body').animate({scrollTop: $('.ti__step3')[0].offsetTop - bannerHeight}, scrollDelay);
    }

    function returnToStep1() {
        $('.ti__step1').removeClass('ti__step1-inactive');
        $('.ti__step2').removeClass('ti__step2-active ti__step2-inactive');
        $('.ti__step3').removeClass('ti__step3-active');
        $('.ti__step .ti__header').addClass('ti__header-inactive');
        $('.ti__step1 .ti__header').removeClass('ti__header-inactive');

        $('html, body').animate({scrollTop: $('.ti__step1').offset().top - bannerHeight}, scrollDelay);
    }

    function returnToStep2() {
        $('.ti__step2').removeClass('ti__step2-inactive').addClass('ti__step2-active');
        $('.ti__step3').removeClass('ti__step3-active');
        $('.ti__step .ti__header').addClass('ti__header-inactive');
        $('.ti__step2 .ti__header').removeClass('ti__header-inactive');

        $('html, body').animate({scrollTop: $('.ti__step2').offset().top - bannerHeight}, scrollDelay);
    }

    $('.ti__step1-return').click(function (e) {
        e.preventDefault();
        returnToStep1();
    });

    $('.ti__step2-return').click(function (e) {
        e.preventDefault();
        returnToStep2();
    });

    $('.ti__new-link').click(function (e) {
        e.preventDefault();
    });

    return tiObj;
})();
