﻿(function ($) {
    $.validator.setDefaults({
        ignore: ".ignore",
        onkeyup: false,
        onfocusout: false,
        onclick: false
    });
}(jQuery));

if (_iframeMode === true) {
    initResizeMessagesForIFrameMode();
}

function initResizeMessagesForIFrameMode() {
    if (window.ResizeObserver === undefined) {
        //IE11 fallback
        setInterval(function () {
            var height = $('div.page-wrapper').outerHeight(true);
            //console.log('IFrame content height changed (fallback): ', height);

            var message = {
                type: 'viessmann-iframe-resized',
                height: height
            };

            parent.postMessage(message, "*");
        }, 500);
    } else {
        var resizeObserver = new ResizeObserver(function (entries) {
            var height = $(entries[0].target).outerHeight(true);
            //console.log('IFrame content height changed: ', height);

            var message = {
                type: 'viessmann-iframe-resized',
                height: height
            };

            parent.postMessage(message, "*");
        });

        resizeObserver.observe($('div.page-wrapper')[0]);
    }
}

//Show dealer map
function loadMap() {
    //Load map
    if (_mapsApiLoaded && $("#HasContactWithDealer").is(":checked")) {
        $('.js-googlemaps-consent').hide();
        $('.js-googlemaps-map').show();

        //reset markers
        _markers = [];

        //UNDONE: make start coordinates country specific
        _map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 50.5039, lng: 4.4699 },
            zoom: 6
        });

        _options = {
            imagePath: _mapClusterMarkerImage
        };

        _markerCluster = new MarkerClusterer(_map, _markers, _options);
    }
};

$(function () {
    //ignore validation on certain field
    var ignoreValidationOnField = function (query) {
        var field = $(query);
        if (!field.hasClass("ignore")) {
            field.addClass("ignore");
        }
    };

    //ignore required fields
    var ignoreValidation = function () {
        $(".ignore").removeClass("ignore");

        switch (_scenarioType) {
            case 1: //product conf + dosier
                if (!$("#Contact_AskOffer").is(":checked") && !$("#Contact_AskEnergyChecque").is(":checked")) {
                    ignoreValidationOnField("#Contact_Address_Street");
                    ignoreValidationOnField("#Contact_Address_ZipCode");
                    ignoreValidationOnField("#Contact_Address_City");
                    ignoreValidationOnField("#Contact_Address_Country"); //not always on the page
                } else {
                    //if quote or energy cheque is checked DossierZipCode and DossierCountry are no longer required
                    ignoreValidationOnField("#DossierZipCode");
                    ignoreValidationOnField("#DossierCountry"); //not always on the page
                }
                if (!$("#Contact_AskOffer").is(":checked") || !$("#QuoteAlternativeAddress").is(":checked")) {
                    ignoreValidationOnField("#Contact_InstallationAddress_Street");
                    ignoreValidationOnField("#Contact_InstallationAddress_ZipCode");
                    ignoreValidationOnField("#Contact_InstallationAddress_City");
                    ignoreValidationOnField("#Contact_InstallationAddress_Country"); //not always on the page
                }
                ignoreValidationOnField("#Project_Comments");
                break;
            case 2: //product conf + vitocontact quote
            case 3: //vitocontact quote
                if (!$("#QuoteAlternativeAddress").is(":checked")) {
                    ignoreValidationOnField("#Contact_InstallationAddress_Street");
                    ignoreValidationOnField("#Contact_InstallationAddress_ZipCode");
                    ignoreValidationOnField("#Contact_InstallationAddress_City");
                    ignoreValidationOnField("#Contact_InstallationAddress_Country"); //not always on the page
                }
                break;
            case 4: //energycheque
                if (!$("#Contact_AskOffer").is(":checked") || !$("#QuoteAlternativeAddress").is(":checked")) {
                    ignoreValidationOnField("#Contact_InstallationAddress_Street");
                    ignoreValidationOnField("#Contact_InstallationAddress_ZipCode");
                    ignoreValidationOnField("#Contact_InstallationAddress_City");
                    ignoreValidationOnField("#Contact_InstallationAddress_Country"); //not always on the page
                }
                ignoreValidationOnField("#Project_Comments");
                break;
        }

        if (!$("#HasContactWithDealer").is(":checked") || $("#Contact_IsNotDealerAvailable").is(":checked")) {
            ignoreValidationOnField("#Contact_FullDealerId");
        }

        if (!$("#HasContactWithDealer").is(":checked") || !$("#Contact_IsNotDealerAvailable").is(":checked")) {
            ignoreValidationOnField("#Contact_DealerName");
            ignoreValidationOnField("#Contact_DealerAddress_ZipCode");
            ignoreValidationOnField("#Contact_DealerAddress_City");
        }

        //if all selected energy sources are either PV or PS then the question about surface area is hidden
        if ($("input[name='Project.PreferredEnergySourceCodes']:checked").length > 0
            && $.makeArray($("input[name='Project.PreferredEnergySourceCodes']:checked"))
                .every(function (x) { return ($(x).val() === 'PV' || $(x).val() === 'PS') })) {
            ignoreValidationOnField("input[name='Project.SurfaceFork']");
        }

        if ($("#Project_AlreadyInstalled").is(":checked")) {
            //if AlreadyInstalled checkbox is checked you no longer need to select a term from the list
            ignoreValidationOnField("input[name='Project.Term']"); //
        } else {
            //if AlreadyInstalled is not checked, HasContactWithDealer is not required
            ignoreValidationOnField("#HasContactWithDealer");
        }
    };

    var showTarget = function (inputElem, targetQuery) {
        var target = $(targetQuery);
        if (isElementActive(inputElem)) {
            target.addClass('visible');
            target.removeClass('hidden'); //needed for dealer section
            target.slideDown();
        } else {
            target.removeClass('visible');
            target.slideUp(function () {
                target.addClass('hidden'); //needed for dealer section
            });
        }
    }; 

    var displayTarget = function (makeVisible, targetQuery) {
        var target = $(targetQuery);
        if (makeVisible) {
            target.addClass('visible');
            target.removeClass('hidden'); //needed for dealer section
            target.slideDown();
        } else {
            target.removeClass('visible');
            target.slideUp(function () {
                target.addClass('hidden'); //needed for dealer section
            });
        }
    }; 

    var isElementActive = function (inputElem) {
        var input = $(inputElem);
        if (input.is(":checked")
            || (input.is("input:text") && input.val() !== "")
            || (input.hasClass("info-toggle") && input.hasClass("active"))) {
            return true;
        } else {
            return false;
        }
    };

    $('#DossierZipCode').blur(function () {
        $('#Contact_Address_ZipCode').val($(this).val());
    });
    $('#Contact_Address_ZipCode').blur(function () {
        $('#DossierZipCode').val($(this).val());
    });

    $('#DossierCountry').blur(function () {
        $('#Contact_Address_Country').val($(this).val());
    });
    $('#Contact_Address_Country').blur(function () {
        $('#DossierCountry').val($(this).val());
    });

    //show label above input field when placeholder not is used && input has a value
    $("input[placeholder]").on("keyup", function () {
        var input = $(this);
        if (input.val() !== "") {
            //show label
            $(input.prev()).addClass("visible");
            return true;
        }

        $(input.prev()).removeClass("visible");
    });

    //Project

    //preferred energy sources
    $("input[name='Project.PreferredEnergySourceCodes']").on("change", function () {
        var div = $($(this).parent().parent()); 
        if (div.hasClass("error")) {
            div.removeClass("error");
        }

        //if all selected energy sources are either PV or PS then the question about surface area is hidden
        var onlyPVAndPSSelected = $("input[name='Project.PreferredEnergySourceCodes']:checked").length > 0
            && $.makeArray($("input[name='Project.PreferredEnergySourceCodes']:checked"))
                .every(function (x) { return ($(x).val() === 'PV' || $(x).val() === 'PS') });

        var target = $("#surfacefork-wrap");
        if (onlyPVAndPSSelected) {
            if (!target.hasClass("hidden")) {
                target.addClass("hidden");
            }
        } else {
            if (target.hasClass("hidden")) {
                target.removeClass("hidden");
            }
        }

        reconfigureDealerFieldsForEnergySource(true);

        ignoreValidation();
    });

    //surface Area
    $("input[name='Project.SurfaceFork']").on("change", function () {
        var div = $($(this).parent().parent());
        if (div.hasClass("error")) {
            div.removeClass("error");
        }
    });

    //term 
    $("input[name='Project.Term']").on("change", function () {
        var div = $($(this).parent().parent());
        if (div.hasClass("error")) {
            div.removeClass("error");
        }
    });

    $("#Project_AlreadyInstalled").on("change", function () {
        var input = $(this);
        var target = $("#project-term-wrap");

        if (!input.is(":checked")) {
            if (target.hasClass("hidden")) {
                target.removeClass("hidden");
            }

            //show quote checkbox bar
            $("#FormAskOfferBar").show();
        } else {
            if (!target.hasClass("hidden")) {
                target.addClass("hidden");
            }

            //if quote checkbox is checked, uncheck it
            if ($("#Contact_AskOffer").is(":checked")) {
                $("#Contact_AskOffer").click();
            }

            //hide quote checkbox bar
            $("#FormAskOfferBar").hide();

            //check dealer checkbox if not yet active
            if (!$("#HasContactWithDealer").is(":checked")) {
                $("#HasContactWithDealer").click();
            }
        }

        ignoreValidation();
    });

    //Quote option

    //Show or hide alternative contact installation address checkbox (dossier form and energy cheque form)
    $("#Contact_AskOffer").on("change", function () {
        if (_scenarioType == 1) { //product dossier
            displayTarget(isElementActive("#Contact_AskOffer") || isElementActive("#Contact_AskEnergyChecque"), "#FormContactAddress");

            showTarget(this, "#FormShowAlternativeContactInstallationAddress");
            if (isElementActive("#QuoteAlternativeAddress")) {
                showTarget(this, "#FormContactInstallationAddress");
            }

            var dealerSectionActive = (isElementActive("#Contact_AskOffer") || isElementActive("#Contact_AskEnergyChecque"));
            $('#form-footer-dealerselection-wrapper').toggle(dealerSectionActive);
            if (!dealerSectionActive) {
                clearAllDealerData();
            }
        } else {
            showTarget(this, "#FormShowAlternativeContactInstallationAddress");
            if (isElementActive("#QuoteAlternativeAddress")) {
                showTarget(this, "#FormContactInstallationAddress");
            }
        }

        ignoreValidation();
    });

    //Show or hide alternative contact installation address (quote form and energy cheque form)
    $("#QuoteAlternativeAddress").on("change", function () {
        showTarget(this, "#FormContactInstallationAddress");

        ignoreValidation();
    });

    //Energycheque option
    
    $("#Contact_AskEnergyChecque").on("change", function () {
        //Show or hide alternative contact address checkbox
        if (_scenarioType == 1) { //product dossier
            displayTarget(isElementActive("#Contact_AskOffer") || isElementActive("#Contact_AskEnergyChecque"), "#FormContactAddress");

            var dealerSectionActive = (isElementActive("#Contact_AskOffer") || isElementActive("#Contact_AskEnergyChecque"));
            $('#form-footer-dealerselection-wrapper').toggle(dealerSectionActive);
            if (!dealerSectionActive) {
                clearAllDealerData();
            }
        }

        ignoreValidation();
    });

    //Dealer selection

    var addMarker = function (latitude, longitude, title, id) {
        var icon = _mapMarkerImageInactive;
        if ($("#Contact_FullDealerId").val() > 0 && $("#Contact_FullDealerId").val() == id) {
            icon = _mapMarkerImageActive;
        }

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(latitude, longitude),
            icon: icon,
            title: title,
            html: id
        });

        google.maps.event.addListener(marker, 'click', function () {
            resetMarkerIcons();
            setMarkerActive(this);
            this.setIcon(_mapMarkerImageActive);
        });

        _markers.push(marker);

        return marker;
    };

    var addDealerLi = function (dealer) {
        var li = '<li class="dealer-item"><a href="" data-id="' + dealer.id + '">' + dealer.name + '</a></li>';
        $("#dealer-list").append(li);
    };

    var resetMarkerIcons = function () {
        for (var i = 0; i < _markers.length; i++) {
            _markers[i].setIcon(_mapMarkerImageInactive);
        }
    };

    var setMarkerActive = function (marker) {
        //clear selected items
        $(".dealer-item a").removeAttr("selected");

        //save selected item
        $("a[data-id=" + marker.html + "]").attr("selected", true);
        $("#Contact_FullDealerId").val(marker.html);

        hideCustomDealerData();
    };

    var clearDealerSearch = function () {
        $("#dealer-list").html("");
        $("#dealersearch").parent().removeClass("error");
        $("#Contact_FullDealerId").val("");

        removeNoDealersError();

        if (_mapsApiLoaded) {
            _markers = [];
            if (_markerCluster !== undefined && _markerCluster !== null) {
                _markerCluster.clearMarkers();
            }
        }
    };

    var searchDealers = function () {
        var searchTerm = $("#dealersearch").val();

        var filterByEnergySources = $.makeArray($("input[name='Project.PreferredEnergySourceCodes']:checked"))
            .map(function (x) { return $(x).val() });

        //UNDONE: what should this check on? The haas query param or the checkbox or both?
        var filterByHeatingAsAService = $("input[name='HeatingAsAServiceFromQuery']").val().toLowerCase();

        var url = _serviceUrl;
        
        var data = {
            searchTerm: searchTerm,
            filterByEnergySources: filterByEnergySources,
            filterByHeatingAsAService: filterByHeatingAsAService
        };

        if (data.searchTerm !== "") {
            $.ajax({
                type: 'POST',
                url: url + "/api/viessmann/contact/getavailabledealers",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.dealers.length > 0) {
                        //build dealers
                        $.each(result.dealers, function (index, dealer) {
                            if (_mapsApiLoaded) {
                                addMarker(dealer.latitude, dealer.longitude, dealer.name, dealer.id);
                            }
                            addDealerLi(dealer);
                        });

                        $(".dealer-item a").on("click", function (e) {
                            e.preventDefault();

                            var dealerId = $(this).attr('data-id');

                            //clear selected items
                            $(".dealer-item a").removeAttr("selected");

                            //save selected item
                            $(this).attr('selected', true);
                            $("#Contact_FullDealerId").val(dealerId);

                            hideCustomDealerData();

                            if (_mapsApiLoaded) {
                                var result = $.grep(_markers, function (e) { return e.html == dealerId; });
                                if (result.length > 0 && result[0] !== undefined) {
                                    resetMarkerIcons();
                                    result[0].setIcon(_mapMarkerImageActive);
                                }
                            }
                        });

                        if ($("#Contact_FullDealerId").val() > 0) {
                            $(".dealer-item a[data-id='" + $("#Contact_FullDealerId").val() + "']").attr("selected", true);
                        }

                        if (_mapsApiLoaded) {
                            _markerCluster = new MarkerClusterer(_map, _markers, _options);
                        }
                        
                        removeNoDealersError();
                    } else {
                        showNoDealersError();
                    }
                },
                error: function (error) {
                    showNoDealersError();
                }
            });
        }
    };

    function removeNoDealersError() {
        $('#no-dealers-found').removeClass("visible");
        $('#no-dealers-found').addClass("hidden"); //needed for dealer section
    }

    function showNoDealersError() {
        $('#no-dealers-found').addClass("visible");
        $('#no-dealers-found').removeClass("hidden"); //needed for dealer section
        $("#dealersearch").parent().addClass("error");
    }

    function reconfigureDealerFieldsForEnergySource(doClearAllDealerData) {
        if (doClearAllDealerData) {
            //reset all dealer data because the dealer selected from the map list could be wrong now
            clearAllDealerData();
        }
    }

    var hideCustomDealerData = function () {
        $("#Contact_IsNotDealerAvailable").prop('checked', false);
        displayTarget(false, "#dealer-address");
        $('#dealer-address input').val('');

        ignoreValidation();
    };

    var clearAllDealerData = function () {
        $("#HasContactWithDealer").prop('checked', false);
        showTarget($("#HasContactWithDealer"), ".dealer-locator");

        $("#dealersearch").val("");
        clearDealerSearch();

        hideCustomDealerData();
    };

    $("#dealer-search").on("click", function () {
        clearDealerSearch();
        searchDealers();
    });

    $("#dealersearch").on("keydown", function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            clearDealerSearch();
            searchDealers();
        }
    });

    $("#HasContactWithDealer").on("change", function () {
        showTarget(this, ".dealer-locator");
        //do not check on class 'hidden' because it is only added after the animation has finished
        if (!$('.dealer-locator').hasClass('visible')) {
            $("#dealersearch").val("");
            clearDealerSearch();
        } else {
            loadMap();
        }

        ignoreValidation();
    });

    $("#Contact_IsNotDealerAvailable").on("change", function () {
        showTarget(this, "#dealer-address");
        //reset dealer map, do not check on class 'hidden' because it is only added after the animation has finished
        if ($('#dealer-address').hasClass('visible')) {
            $("#dealersearch").val("");
            clearDealerSearch();
        }

        ignoreValidation();
    });

    //form submit

    $("form").submit(function (e) {
        var validator = $("form").validate();

        var notice = $("#PrivacyNotice");
        if ($(this).valid() && notice.is(":checked")) {
            grecaptcha.execute();
            return false;
        }

        //remove all errors
        $('.input-wrapper').removeClass("error");

        for (var i = 0; i < validator.errorList.length; i++) {
            var error = validator.errorList[i];

            if ($(error.element).parent().hasClass('radio') || $(error.element).parent().hasClass('checkbox')) {
                $(error.element).parent().parent().addClass("error"); 
            } else {
                $(error.element).parent().addClass("error");
            }
        }

        if (!notice.is(":checked")) {
            notice.parent().addClass("error");
            $('[data-valmsg-for=PrivacyNotice]').html('<span>' + $("#PrivacyNotice").attr("data-val-required") + '</span>');
            $('[data-valmsg-for=PrivacyNotice]').attr("data-valmsg-replace", "false");
        } else {
            notice.parent().removeClass("error");
            $('[data-valmsg-for=PrivacyNotice]').html('');
            $('[data-valmsg-for=PrivacyNotice]').attr("data-valmsg-replace", "true");
        }

        return false;
    });

    //initialize the view on load

    if (_preferredEnergySourceCodes.length > 0) {
        $("label[for*='preferred']").removeClass("selected");

        for (var i = 0; i < _preferredEnergySourceCodes.length; i++) {
            $("input[name='Project.PreferredEnergySourceCodes'][value='" + _preferredEnergySourceCodes[i] + "']").attr("checked", true);
            $("input[name='Project.PreferredEnergySourceCodes'][value='" + _preferredEnergySourceCodes[i] + "']").next('label').addClass("selected");
        }

        //if all selected energy sources are either PV or PS then the question about surface area is hidden
        if (_preferredEnergySourceCodes.every(function (x) { return (x === 'PV' || x === 'PS') })) {
            if (!$("#surfacefork-wrap").hasClass("hidden")) {
                $("#surfacefork-wrap").addClass("hidden");
            }
        }
    }

    if (_surfaceFork !== "") {
        $("label[for*='SurfaceFork']").removeClass("selected");
        $("input[name='Project.SurfaceFork'][value='" + _surfaceFork + "']").attr("checked", true);
        $("input[name='Project.SurfaceFork'][value='" + _surfaceFork + "']").next('label').addClass("selected");
    }

    if (_term !== "") {
        $("input[name='Project.Term'][value='" + _term + "']").attr("checked", true);

        if (_term === "5") {
            $('input[name="Project.AlreadyInstalled"]').removeProp('checked');
            $('input[name="Project.AlreadyInstalled"]').click();
        }
    }

    if ($("#HasContactWithDealer").is(":checked") || ($("#Contact_FullDealerId").val() > 0 && _dealerSearchTerm !== "") || $("#Contact_IsNotDealerAvailable").is(":checked")) {
        $("#HasContactWithDealer").prop('checked', true);
        showTarget($("#HasContactWithDealer"), ".dealer-locator");
        loadMap();

        if ($("#Contact_FullDealerId").val() > 0 && _dealerSearchTerm !== "") {
            $("#dealersearch").val(_dealerSearchTerm);
            searchDealers();
        } else if ($("#Contact_IsNotDealerAvailable").is(":checked")) {
            showTarget($("#Contact_IsNotDealerAvailable"), "#dealer-address");
        }
    }

    if ($('#Contact_DealerName').val() != "" && $('#Contact_DealerAddress_ZipCode').val() != "" && $('Contact_DealerAddress_City').val() != "") {
        $('input[name="Contact.IsNotDealerAvailable"]').removeProp('checked');
        $('input[name="Contact.IsNotDealerAvailable"]').click();
    }

    reconfigureDealerFieldsForEnergySource(false);

    if ($('#Contact_InstallationAddress_Street').val() != "" && $('#Contact_InstallationAddress_ZipCode').val() != "" && $('Contact_InstallationAddress_City').val() != "") {
        $('input[name=QuoteAlternativeAddress]').removeProp('checked');
        $('input[name=QuoteAlternativeAddress]').click();
    }

    // form footers
    if ($('#Contact_AskOffer').prop('checked')) {
        $('#Contact_AskOffer').removeProp('checked');
        $('#Contact_AskOffer').click();
    }

    if ($('#Contact_AskEnergyChecque').prop('checked')) {
        $('#Contact_AskEnergyChecque').removeProp('checked');
        $('#Contact_AskEnergyChecque').click();
    }

    ignoreValidation(); 
});

function initializeContactRecaptcha() {
    grecaptcha.render('recaptchaContactForm');
}

function submitContactForm() {
    var form = $('form').eq(0);
    var action = form.attr('action');
    var method = form.attr('method');
    
    $.ajax({
        type: method,
        url: action,
        data: form.serialize(),
        success: function (data) {
            if (data.FormSubmitted) {
                form.replaceWith(
                    '<div class="container container-small">' +
                        '<h4>' + data.ConfirmationTitle + '</h4>' +
                        '<p>' + data.ConfirmationText + '</p>' +
                    '</div>'
                );

                for (var i = 0; i < data.GoogleAnalyticsEventsOnLoad.length; i++) {
                    var gaevent = data.GoogleAnalyticsEventsOnLoad[i];
                    if (gaevent.Type === 0) {
                        if (data.GoogleAnalyticsEventTrackingType === "DATALAYER") {
                            window.dataLayer.push({
                                'event': 'FormSubmission',
                                'eventCategory': gaevent.Category,
                                'eventAction': gaevent.Action,
                                'eventLabel': gaevent.Label
                            });
                        } else if (data.GoogleAnalyticsEventTrackingType === "GA") {
                            ga('send', 'event', gaevent.Category, gaevent.Action, gaevent.Label);
                        }
                    } else if (gaevent.Type === 1) {
                        if (data.GoogleAnalyticsEventTrackingType === "DATALAYER") {
                            window.dataLayer.push({
                                'event': 'VirtualPageview',
                                'virtualPageURL': gaevent.Path
                            });
                        } else if (data.GoogleAnalyticsEventTrackingType === "GA") {
                            ga('send', 'pageview', gaevent.Path);
                        }
                    }
                }
            }

            $('.form__step-counter .form__step-counter__step--current')
                .removeClass('form__step-counter__step--current')
                .addClass('form__step-counter__step--passed');
        }
    });
}


$(function () {
    var multistepWrapper = $('.multistep-form-steps');
    var multistepWrapperDuration = parseFloat(multistepWrapper.css('transition-duration')) * 1000;

    var step = $('.js-multistep-form-step.active').index() + 1;

    init();

    function init() {
        var multistepForm = $('.multistep-form');

        $('.js-prev', multistepForm).click(function () {
            doPrev();
        });

        $('.js-next', multistepForm).click(function () {
            doNext();
        });

        var activeStepHeight = $('.js-multistep-form-step.active').css('height');

        setMultiStepWrapperHeight(activeStepHeight, activeStepHeight);
    }

    function doPrev() {
        animateBack();
    }

    function doNext() {
        var activeFormControls = $('.multistep-form form .active input, .multistep-form form .active textarea, .multistep-form form .active select');
        var formControls = $('.multistep-form form input, .multistep-form form textarea, .multistep-form form select');
        var validationCheck = activeFormControls.valid();

        if (validationCheck) {
            formControls.closest('.error').removeClass('error');
            $('[data-valmsg-for]').html('');
            animateNext();
        } else {
            $('.multistep-form form').submit();
        }
    }

    function animateBack() {
        var activeStep = $('.js-multistep-form-step.active');
        var goToStep = activeStep.prev();

        if (goToStep.length) {
            animateStep(activeStep, goToStep);
            animateStepCounter(false);

            step--;

            animateButtons();
        }
    }

    function animateNext() {
        var activeStep = $('.js-multistep-form-step.active');
        var goToStep = activeStep.next();

        if (goToStep.length) {
            animateStep(activeStep, goToStep);
            animateStepCounter(true);

            step++;

            animateButtons();
        }
    }

    function animateStep(activeStep, goToStep) {
        goToStep.removeClass('hidden');

        setMultiStepWrapperHeight(activeStep.css('height'), goToStep.css('height'));

        activeStep.removeClass('active');
        goToStep.addClass('active');

        setTimeout(function () {
            activeStep.addClass('hidden');
        }, 500);
    }

    function animateStepCounter(isNext) {
        var counterCurrentStep = $('.form__step-counter__step').eq(step - 1);
        var counterGoToStep = $('.form__step-counter__step').eq(step);

        if (isNext) {
            counterCurrentStep.addClass('form__step-counter__step--passed');
        } else {
            counterGoToStep = $('.form__step-counter__step').eq(step - 2);
        }

        counterCurrentStep.removeClass('form__step-counter__step--current');
        counterGoToStep
            .addClass('form__step-counter__step--current')
            .removeClass('form__step-counter__step--passed');
    }

    function animateButtons() {
        if (step <= 1) {
            $('.multistep-actions .js-prev').hide(250);
        } else {
            $('.multistep-actions .js-prev').show(250);
        }

        if (step >= $('.multistep-form-step').length) {
            $('.multistep-actions .js-next').hide(250);
            //$('.multistep-actions').removeClass('container-small');
            $('.submit-button').show(250);
        } else {
            $('.multistep-actions .js-next').show(250);
            //$('.multistep-actions').addClass('container-small');
            $('.submit-button').hide(250);
        }
    }

    function setMultiStepWrapperHeight(currentStepHeight, stepHeight) {
        multistepWrapper.css({
            height: currentStepHeight
        });

        setTimeout(function () {
            multistepWrapper.css({
                height: stepHeight
            });
        });

        setTimeout(function () {
            multistepWrapper.css({
                height: 'auto'
            });
        }, multistepWrapperDuration);
    }
});

$(function () {
    var infoToggle = $('.info-toggle');
    infoToggle.click(function () {
        $(this).toggleClass('active');
    });

    var haasTooltip = $('.form-footer-haas-tooltip-wrapper');
    haasTooltip.click(function () {
        $(this).toggleClass('form-footer-haas-tooltip-wrapper--active');
    });

    $(document).click(function (event) {
        var $target = $(event.target);
        if (!$target.closest('.form-footer-haas-tooltip-wrapper').length &&
            $('.form-footer-haas-tooltip-wrapper').is(":visible")) {
            $('.form-footer-haas-tooltip-wrapper').removeClass('form-footer-haas-tooltip-wrapper--active');
        }
    });
});