/* Minification failed. Returning unminified contents.
(1467,46-49): run-time error JS1009: Expected '}': ...
(1467,46-49): run-time error JS1006: Expected ')': ...
(1467,45): run-time error JS1004: Expected ';'
(1492,1-2): run-time error JS1002: Syntax error: }
(1492,2-3): run-time error JS1195: Expected expression: )
(1626,18-21): run-time error JS1009: Expected '}': ...
(1626,18-21): run-time error JS1003: Expected ':': ...
(1626,94-95): run-time error JS1006: Expected ')': }
(1626,94): run-time error JS1004: Expected ';'
(1626,96-97): run-time error JS1195: Expected expression: :
(1627,97-98): run-time error JS1195: Expected expression: )
(1635,74-77): run-time error JS1009: Expected '}': ...
(1635,74-77): run-time error JS1006: Expected ')': ...
(1635,77-84): run-time error JS1006: Expected ')': options
(1635,100-101): run-time error JS1003: Expected ':': ,
(1635,121): run-time error JS1004: Expected ';'
(1635,121-122): run-time error JS1195: Expected expression: )
(1635,123-124): run-time error JS1195: Expected expression: :
(1636,10-11): run-time error JS1195: Expected expression: )
(1641,48-51): run-time error JS1009: Expected '}': ...
(1641,48-51): run-time error JS1006: Expected ')': ...
(1641,48): run-time error JS1004: Expected ';'
(1641,127-128): run-time error JS1195: Expected expression: )
(1647,5-6): run-time error JS1006: Expected ')': }
(1648,1-2): run-time error JS1002: Syntax error: }
(1648,2-3): run-time error JS1195: Expected expression: )
 */
var lkb = lkb || {};

(function ($) {
    var mobileSwitchWidth = '750';
    var maxFixedHeight = '500';

    var landkredittui = {
        Toggle: function(toggled, activeFunction) {
            if ($(toggled).hasClass('selected')) {
                this.HideAll();
            } else {
                landkredittui.Fader.ShowFader();
                $(toggled).addClass('selected');
                activeFunction();
            }
        },

        HideSearch: function() {
            $('._jsMobileSearch').removeClass('selected');
            $('._jsSearchInput').hide();
        },

        HideAll: function() {
            landkredittui.Fader.HideFader();
            landkredittui.HideSearch();
        },

        Fader:
        {
            BindElement: function(faderRef) {
                $(faderRef).on('click',
                    function(e) {
                        landkredittui.HideAll();

                        e.preventDefault();
                    });

                landkredittui.Fader.BindClose();
            },
            ShowFader: function() {
                $('._jsFader').fadeIn();
            },

            HideFader: function() {
                $('._jsFader').fadeOut();
            },
            BindClose: function() {
                $('._jsClose').on('click',
                    function(e) {
                        landkredittui.Fader.HideFader();
                        e.preventDefault();
                    });
            }
        },

        ContactScheme:
        {
            BindElement: function(faqDetails, faqQuestion) {
                this.CustomerServiceFaqHide(faqDetails);
                this.CustomerServiceFaqToggle(faqDetails, faqQuestion);
            },

            CustomerServiceFaqHide: function(details) {
                $(details).hide();
            },

            CustomerServiceFaqToggle: function(details, question) {
                $(question).on('click',
                    function(e) {
                        $(this).closest('li').children(details).toggle();
                        $(this).show();
                        e.preventDefault();
                        return false;
                    });
            }
        },

        Search:
        {
            QuickSearchFocus: function(searchText) {
                $(searchText).on('focus',
                    function() {
                        $(this).addClass('charged');
                    });

                $(searchText).on('blur',
                    function() {
                        if ($(this).val() === '') {
                            $(this).removeClass('charged');
                        }
                    });

                $(searchText).on('keypress', function(event) {
                    if (event.which === 13) {
                        var original = $(this).data('searchtext');
                        if ($(this).val().length === 0 || original === $(this).val()) {
                            event.preventDefault();
                            return;
                        }

                        $(this).siblings().closest('._jsQuickSearchButton').click();
                        event.preventDefault();
                    }
                });

                $(searchText).siblings().closest('._jsQuickSearchButton').on('click',
                    function(e) {
                        var form = $('form');
                        if (form === undefined) return;

                        var action = form.attr('action');
                        if (action === undefined) return;

                        var errorPath = '/error/';
                        var actionSubstring = action.substring(0, Math.min(errorPath.length, action.length));
                        if (actionSubstring.toLowerCase() === errorPath) {
                            var newAction = '/Error/ErrorHandler.aspx';
                            if (action.indexOf('?') >= 0) {
                                var queryString = action.substring(action.indexOf('?'), action.length);
                                newAction = newAction + queryString;
                            }
                            form.attr('action', newAction);
                        }
                    });
            },

            QuickSearchFocus2: function($searchText, $searchContainer, $searchToggler) {
                $searchToggler.on('click',
                    function() {
                        $searchContainer.toggleClass('is-visible');
                        if ($searchContainer.is('.is-visible')) {
                            $searchText.focus();
                        }
                    });

                $searchText.on('keypress', function(event) {
                    if (event.which === 13) {
                        var original = $(this).data('searchtext');
                        if ($(this).val().length === 0 || original === $(this).val()) {
                            event.preventDefault();
                            return;
                        }

                        $(this).siblings().closest('._jsQuickSearchButton2').click();
                        event.preventDefault();
                    }
                });

                $searchText.siblings().closest('._jsQuickSearchButton2').on('click',
                    function(event) {
                        event.preventDefault();

                        var searchtext = $searchText.val();
                        $searchText.val($searchText.val().replace('<', '').replace('>', ''));
                        var searchurl = $searchText.siblings('._jsQuickSearchUrl').html();

                        window.location = searchurl + searchtext;
                    });

                $searchText.autocomplete({
                    source: function() {
                        var searchtext = $searchText.val();
                        $searchText.val($searchText.val().replace('<', '').replace('>', ''));
                        var currentPage = $searchText.siblings('._jsQuickSearchCurrentPage').html();

                        $.ajax({
                            type: 'GET',
                            url: '/SearchMvc/QuickSearch/?',
                            data: {
                                currentPage: currentPage,
                                searchText: searchtext
                            },
                            async: true,
                            cache: false,
                            success: function(data) {
                                $('#_jsQuickSearchResult').html(data);
                                $searchText.removeClass('ui-autocomplete-loading');
                            },
                            error: function() {
                                $('#_jsQuickSearchResult').html('');
                                $searchText.removeClass('ui-autocomplete-loading');
                            }
                        });
                    },
                    minLength: 3,
                    delay: 250
                });
            },

            SearchScrollEvent: function(apiUrl, viewModel) {
                $(window).scroll(function() {
                    if ($(window).scrollTop() > $('ol.searchResult').height() - 400) {
                        landkredittui.Search.SearchPager(apiUrl, viewModel);
                    }
                });
            },

            SearchPager: function(apiUrl, viewModel) {
                if (!viewModel.pendingRequest()) {
                    viewModel.pendingRequest(true);
                    viewModel.page = parseInt(viewModel.page) + 1;

                    $.ajax({
                        type: 'GET',
                        url: decodeURIComponent(apiUrl),
                        data: {
                            page: viewModel.page,
                        },
                        success: function(result) {
                            var searchItems = 0;
                            ko.utils.arrayForEach($('._jsSearchList li', result),
                                function(entry) {
                                    if ($(entry).children().length > 0) {
                                        $(entry).find('script').remove();
                                        viewModel.searchHits.push(entry);
                                        searchItems++;
                                    }
                                });

                            if (searchItems >= 10) {
                                viewModel.pendingRequest(false);
                            }
                        },
                        error: function() {
                            viewModel.pendingRequest(false);
                        }
                    });
                }
            },
        },

        FixedElement:
        {
            BindElement: function(element, contentContainer, end) {
                if (element.length === 0 || $(window).width() < mobileSwitchWidth) {
                    return;
                }

                this.fixedStart(element);
                this.fixed(element);
                this.fixedEnd(element, contentContainer, end);
            },

            fixedStart: function(element) {
                if ($(window).scrollTop() < $(element).offset().top) {
                    if ($(element).hasClass('fixed')) {
                        $(element).removeClass('fixed');
                        $(element).css('top', '');
                    }
                }
            },

            fixed: function(element) {
                if ($(window).scrollTop() > $(element).offset().top) {
                    if ($(element).height() > maxFixedHeight) {
                        return;
                    }
                    $(element).addClass('fixed');
                    $(element).css('top', '20px');
                }
            },

            fixedEnd: function(element, contentContainer, end) {
                if ($(window).scrollTop() > ($(end).height() - 150)) {
                    if ($(element).hasClass('fixed')) {
                        $(element).removeClass('fixed');
                    }
                    $(contentContainer).css('top', ($(end).height() - 50) - $(element).height());
                } else {
                    $(contentContainer).css('top', '');
                }
            }
        }
    };

    var lkb = window.lkb || {};

    lkb.UI = landkredittui;
    
})(jQuery);;
if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

if (!Element.prototype.matches) {
    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
    Element.prototype.closest = function (s) {
        var el = this;

        do {
            if (Element.prototype.matches.call(el, s)) return el;
            el = el.parentElement || el.parentNode;
        } while (el !== null && el.nodeType === 1);
        return null;
    };
};
var lkb = lkb || {};

$(() => {
    const throttle = (func, delay)=>{
        let prev = 0;
        return (...args) => {
            let now = new Date().getTime();
            if(now - prev> delay){
                prev = now;
                return func(...args);
            }
        }
    }
    
    function setMargin () {
        $('._jsBgContainer').each(function() {
            const moduleMb = 25;
            const minMb = 12*16;
            const $this = $(this);
            const offBottom = $this.offset().top + $this.outerHeight();
            const $firstChild = $($(this).find("._jsOffsetTarget"));
            const childOffset = $firstChild.offset().top + $firstChild.outerHeight();
            const mb = Math.max(childOffset - offBottom + moduleMb, minMb)+"px";
            $this.css('margin-bottom', mb)
        })
    }
    setMargin();

    $(window).on('resize', throttle(setMargin,250));

    function setFullWidthWithoutScrollbar() {
        document.documentElement.style.setProperty('--scrollbar-width', (window.innerWidth - document.documentElement.clientWidth) + "px");
    }

    setFullWidthWithoutScrollbar();

    $(window).on('resize', throttle(setFullWidthWithoutScrollbar,250));

    $('._jsTextExpand').each(function() {
        this.style.setProperty('--height',
            $(this)
                .children()
                .map((_, element) => parseFloat($(element).outerHeight()))
                .toArray()
                .reduce((acc, curr) => acc + curr)
                .toString()
            + "px"
        );
    });

    $('._jsExpandBtn').on('click', function(e) {
        e.preventDefault();
        $(this).closest('._jsTextExpand').toggleClass('expanded');
        $(this).data('state',$(this).data('state') === 'collapsed' ? "expanded" : "collapsed");
        this.innerHTML = $(this).data('state') === 'collapsed' ? $(this).data('text-collapsed') : $(this).data('text-expanded');
    })
    
    const stickyMenu = $('._jsStickyMenu');

    function addFullWidthStickyOnDesktop() {
        const isDesktop = window.matchMedia("only screen and (min-width: 780px)").matches;

        if (isDesktop) {
            stickyMenu.addClass('sticky-links--sm-fullwidth');
        } else {
            stickyMenu.removeClass('sticky-links--sm-fullwidth');
        }
    }
    addFullWidthStickyOnDesktop();
    $(window).on('resize', throttle(addFullWidthStickyOnDesktop, 250));
    
    if (stickyMenu.length) {
        stickyMenu.on('mouseenter focusin', function(e) {
            const hiddenList = $(this).find('._jsList');
            hiddenList
            .attr('aria-hidden', false)
            .addClass('open')
            .find('a').each((_, elem) => {
                $(elem).attr('tabindex','0');
            });
        });

        stickyMenu.on('mouseleave focusout', function(e) {
            $(this).find('._jsList')
            .attr('aria-hidden', true)
            .removeClass('open')
            .find('a').each((_, elem)=> { $(elem).attr('tabindex','-1')});
        });
    }
});

(function ($) {
    const mdMin = 768;

    function accordify (elem = '._jsAccordifyArticle, ._jsAccordifyTeaser') {
        // create accordion of all h2 elements in editor block, 
        // put all content between each h2 inside accordion
        $(elem).find('h2:not([class])').each(function (index, elem) {
            var content = $(elem).nextUntil('h2');
            var section = $.parseHTML('<div class="collapsible-section _jsCollapsibleSection"></div>');
            var header = $.parseHTML("<h4 class=\"collapsible-section__item-heading\">".concat($(elem).text(), "</h4>"));
            var inner = $.parseHTML("<div class=\"collapsible-section__content\" id=\"collapsibleInner-".concat(index, "\"></div>"));
            $(inner).append(content);
            $(section).append(header);
            $(section).append(inner);
            $(this).replaceWith(section);
        });
    }
    accordify();
    
    if ($(window).width() < mdMin) {
        $('._jsCollapsibleSection').each(function () {
            $(this).removeClass('begin-open');
        });
    }

    function createCTAbtn(node) {
        node.find('a.CTAbtn').each(function () {
            var span = $('<span class="CTAbtn"><span></span></span>');
            $(this).before(span);
            span.find('span').append($(this));
        });
    }

    function createVideoWrapper(video) {
        video.each(function () {
            $(this).wrap('<span class="video-container">');
        });
    }

    function toggleId(id) {
        $('#' + id).toggle();
    }

    function hideId(id) {
        $('#' + id).hide();
    }

    $('._jsTeaserLink').hover((e)=> {
        $(e.currentTarget).parent().find('._jsPrimary').addClass('hover');
        }, (e)=> {
        $(e.currentTarget).parent().find('._jsPrimary').removeClass('hover');
    })
    
    //toggle tabindex for links and form elemnts on opening/closing of main menu
    function toggleMainMenu($mainMenuTrigger) {
        if ($mainMenuTrigger.is('.mega-menu-trigger__open')) {
            $('a, button, input, select, textarea')
                .not('.page-header a, .page-header button, .page-header input, _jsMegaMenuContainer a')
                .attr('tabindex', '-1');
            $('#_jsMegaMenuContainer a:first').focus();
            $('.page-header').append('<div class="mega-menu__overlay"></div>');
        } else {
            $('a, button, input, select, textarea').not('.quick-search__button').removeAttr('tabindex');
            $('.mega-menu__overlay').remove();
        }

        $('.page-header').on('click',
            '.mega-menu__overlay',
            function () {
                $('._jsMegaMenuTrigger.mega-menu-trigger__open').trigger('click');
            });
    }

    //lkb.UI.Login.BindElement("._jsMenuLogin", "._jsMobileMenuLink");
    lkb.UI.Fader.BindElement('._jsFader');
    lkb.UI.ContactScheme.BindElement($('._jsAnswerDetails'), $('._jsCustomerFaqQuestion'));
    lkb.UI.Search.QuickSearchFocus('._jsSearchText');
    lkb.UI.Search.QuickSearchFocus2($('.main-search ._jsSearchText2'),
        $('.search-overlay'),
        $('._jsQuickSearchToggler'));
    lkb.UI.Search.QuickSearchFocus2($('.main-search ._jsSearchText2'),
        $('.search-overlay'),
        $('._jsCloseQuickSearch'));

    $(window).on('scroll', function () {
        lkb.UI.FixedElement.BindElement($('._jsPositionFixed'), $('._jsFixedContainer'), $('._jsFixedEnd'));
    });

    //create CTA buttons for certain links
    createCTAbtn($('div#contentWrapper'));

    // wrap youtube videos for responsiveness
    createVideoWrapper($('iframe[src*="youtube.com"]'));
       
    $('[data-fancybox="images"]').fancybox({
        toolbar: false,
        arrows: false,
        infobar: false,
        smallBtn: true,
        touch: false,
        wheel: false,
        keyboard: false
    });

    //toggle main menu
    $('.page-header').on('click',
        '._jsMegaMenuTrigger',
        function (e) {
            const $this = $(this);

            toggleId('_jsMegaMenuContainer');
            toggleId('_jsNav');
            toggleId('_jsMobileSearch');
            $this.toggleClass('mega-menu-trigger__closed').toggleClass('mega-menu-trigger__open');
            $('._jsMenuOpened').toggle();
            $('._jsMenuClosed').toggle();
            toggleMainMenu($this);

            e.preventDefault();
        }).on('keyup',
        function (e) {
            if (e.keyCode === 27) { // escape key
                const $trigger = $('._jsMegaMenuTrigger');
                hideId('_jsMegaMenuContainer');
                hideId('_jsNav');
                hideId('_jsMobileSearch');
                $trigger.addClass('mega-menu-trigger__closed').removeClass('mega-menu-trigger__open').focus();
                $('._jsMenuOpened').hide()
                $('._jsMenuClosed').show();
                toggleMainMenu($trigger);
            }
        });

    $('.page-header').on('click',
        '._jsMobileTrigger',
        function () {
            $('._jsDynamicWrapper').addClass('desktop-only');
        });
    
    $('.page-header').on('click',
        '._jsMobileBackButton',
        function () {
            $('._jsMobileTrigger').removeClass('hidden');
            $('._jsMobileBackButton').addClass('hidden');
            $('._jsNavWrapper').removeClass('desktop-only');
            $('._jsDynamicWrapper').addClass('desktop-only');
        });

    //toggle login menu
    $('.page-header').on('click',
        '._jsLoginMenuTrigger',
        function (event) {
            const $this = $(this);
            toggleId('_jsLoginMenuContainer');
            $('#_jsLoginMenuContainer').toggleClass('active');
            toggleMainMenu($this);
            event.preventDefault();
        }).on('keyup',
        function (event) {
            if (event.keyCode === 27) { // escape key
                const $trigger = $('._jsLoginMenuTrigger');
                hideId('_jsLoginMenuContainer');
                $trigger.addClass('login-menu-trigger__closed').removeClass('login-menu-trigger__open').focus();
                toggleMainMenu($trigger);
            }
        });

    //toggler on megamenu sections on mobile
    const $megaMenu = $('#_jsMegaMenuContainer');
    $megaMenu.on('click',
        '.link-list__heading',
        function () {
            $(this).parent().parent().toggleClass('is-active');
            $(this).toggleClass('is-active');
        });

    $('._jsActiveFilterSelection').on('click',
        function (e) {
            $(this).parents('._jsFilterList').toggleClass('is-open');
            e.preventDefault();
        });

    //questions on pricelist and forms
    $('._js-simple-toggle').on('click',
        '._js-simple-toggle__trigger',
        function (e) {
            var $this = $(this);
            $('._js-simple-toggle__trigger.open').not($this).removeClass('open').next('._js-simple-toggle__content')
                .removeClass('is-visible'); //close open instance
            $this.toggleClass('open').next('._js-simple-toggle__content').toggleClass('is-visible');
            e.preventDefault();
        });
    //deaktivate simple toggle on click outside
    $(document).on('click',
        function (event) {
            if (!$(event.target).closest('._js-simple-toggle').length) {
                $('._js-simple-toggle__trigger').removeClass('open').next('._js-simple-toggle__content')
                    .removeClass('is-visible');
            }
        });

    // Mega Menu dynamic content
    function hideAllMenuItemsExcept(current) {
        let $current = $(current);
        let found = false;

        if ($current) {
            $('._jsNavItem').removeClass('selected');

            if ($current.hasClass('_jsNavItem')) {
                $('._jsNavWrapper').addClass('desktop-only');
                $current.addClass('selected');
            }
        }

        $megaMenu.find('._jsMenuItem').each((_, item) => {
            const $item = $(item);
            const currentText = $current.text().trim();

            if ($item.data('title') === currentText) {
                $item.fadeIn();
                found = true;
                $('._jsNavWrapper').find($('._jsNavItem').each((_, item) => {
                    if ($(item).text().trim() === currentText) {
                        $(item).addClass('selected');
                    }
                }));
                } else {
                    $item.hide();
                }
            });

        if (!found) {
            $megaMenu.find('._jsMenuItem').first().show();
        }
    }

    function hideAllMenuItemsExceptFirst() {
        $megaMenu.find('._jsMenuItem').each((index, item) => {
            if (index > 0) {
                $(item).hide();
            }
        });
    }

    window.hideAllMenuItemsExcept = hideAllMenuItemsExcept;

    hideAllMenuItemsExceptFirst();
    hideAllMenuItemsExcept($('._jsNavSelector .selected'));

    $('._jsNavItem').on('click', function() {
        $('._jsMobileTrigger').addClass('hidden');
        $('._jsMobileBackButton').removeClass('hidden');
        $('._jsDynamicWrapper').removeClass('desktop-only');
    });

    // real estate page
    if ($('body').hasClass('real-estate')) {
        var mapElement = document.getElementById('estate-map');

        var estatePositionLat = $(mapElement).data('position-lat');
        var estatePositionLng = $(mapElement).data('position-lng');

        var realEstateMap = new google.maps.Map(mapElement, {
            zoom: 8,
            center: {
                lat: estatePositionLat,
                lng: estatePositionLng
            }
        });
    }
    
    function selectNavProduct(element, id) {
        $(element).parent().find('._jsNavToggle').removeClass('selected');
        $(element).addClass('selected');
        $(element).parent().parent().find('._jsNavProduct').hide();
        $(element).parent().parent().find(`#nav-product-${id}`).fadeIn();
    }

    window.selectNavProduct = selectNavProduct;

    $(document).on('click', function (e) {
        const target = $(e.target);
        const container = $('#_jsLoginMenuContainer');

        if (!target.parents().addBack().is('.login-menu-trigger') && container.hasClass('active')) {
            const $trigger = $('._jsLoginMenuTrigger');
            hideId('_jsLoginMenuContainer');
            $trigger.addClass('login-menu-trigger__closed').removeClass('login-menu-trigger__open').focus();
            toggleMainMenu($trigger);
            container.toggleClass('active');
        }
    });
    
    const popupTrigger = $("._jsPopupTrigger");
    popupTrigger.each(function (index, elem) {
        const guid = $(this).data('guid');
        const target = $(`#popup-wrapper-${guid}`);
        $(elem).fancybox({
            'onStart': function() { target.removeClass('hidden'); },
            'onClosed': function() { target.addClass('hidden'); }
        })
    });

})(jQuery);;
(function($) {
    $('[data-anchor-menu]').each(function() {
        var useHeadingAsAnchor = $(this).data('anchorMenu');
        var $anchorMenu = $(this);

        if (useHeadingAsAnchor !== false) {
            var $newAnchorMenu = $('<ul />');
            $('article .mainbody h2, article .mainbody h3').each(function(index) {
                var $heading = $(this);
                $heading.attr('id', 'section' + index);
                $newAnchorMenu.append('<li class="' +
                    $heading.prop('tagName').toLowerCase() +
                    '"><a href="#section' +
                    index +
                    '" title="' +
                    $heading.text() +
                    '">' +
                    $heading.text() +
                    '</a></li>');
            });
            $anchorMenu.html($newAnchorMenu);
            $anchorMenu.on('mouseenter mouseleave',
                'a',
                function(event) {
                    $('.mainbody ' + $(this).attr('href')).toggleClass('hover', event.type === 'mouseenter');
                });

        } else {
            $('.anchorMenu').on('mouseenter mouseleave',
                'a',
                function(event) {
                    var anchorName = $(this).attr('href').replace('#', '');

                    $('h2, h3', '.mainbody').filter(function() {
                        return $(this).has('a[name="' + anchorName + '"]').length;
                    }).toggleClass('hover', event.type === 'mouseenter');
                });
        }
    });
})(jQuery);;

/* Provides expand/collapse functionality for each section marked with the
 * _jsCollapsibleSection class.
 *
 * The section is assumed to have two child elements, where the first is
 * assumed to be a heading that will be always visible and contain the
 * expand/collapse trigger, whereas the second represents all the contents
 * to be expanded/collapsed.
 *
 * The script wraps all the heading's contents in a <button> which will
 * act as the trigger. (The heading must therefore contain only phrasing
 * content, e.g. be a valid h3 element, and must additionally contain no
 * interactive content (e.g. links or buttons).)
 *
 * The actual expanding/collapsing is relegated to CSS. To this end, the
 * section will be given the class 'scripted' when the functionality has
 * been set up, and the class 'collapsed' when the contents are to be
 * hidden.
 *
 * The element that represents the contents should have an id attribute,
 * which will be used to mark up the button appropriately.
 */
(function($) {

    /* Sets up a new collapsible section.
     * element: jQuery object of the section whose two children will
     *          be set up as trigger container and hidden/shown content,
     *          respectively.
     */
    var CollapsibleSection = function(element) {
        this.section = element;
        this.heading = element.find('.collapsible-section__item-heading');
        this.contents = this.heading.next();
        this.collapsed = true;
        this.trigger = null;
    };

    /* Set up the given section for expanding/collapsing. Section is
     * collapsed by default.
     */
    CollapsibleSection.prototype.init = function() {
        
        var trigger = document.createElement('button');
        trigger.type = 'button';
        var contentsId = this.contents.attr('id');
        if (typeof contentsId === 'string' && contentsId.length > 0) {
            trigger.setAttribute('aria-controls', contentsId);
        }
        this.heading.wrapInner(trigger);
        /* jQuery seems to make a new copy of the button; when keeping a
         * reference to the original DOM object, modifications to it
         * don't seem to be reflected in the document.
         */
        this.trigger = this.heading.children('button');
        //wrap a span for css help
        this.trigger.wrapInner(document.createElement('span'));
        /* jQuery doesn't seem to keep the click handler either, so
         * adding it after wrapping...
         */

        this.collapsed = !this.section.hasClass('begin-open');
        this.setCollapseState(this.collapsed);

        var thisObject = this;
        this.trigger.on('click',
            function() {
                thisObject.setCollapseState(!thisObject.collapsed);
                
                if (!thisObject.collapsed) {
                    const sectionClasses = $(thisObject.section).attr('class').split(' ').map((e) => { return '.' + e}).toString();
                    $(sectionClasses).removeClass('latest');
                    thisObject.section.addClass('latest');
                }
            });

        this.heading.on('click', 'a',
            function(event) {
                event.preventDefault();
            });
        
        this.section.addClass('scripted');
    };

    /* Switch the section's collapsed state as given.
     * doCollapse: if truthy, the section's contents will be set to
     *             a collapsed state. Otherwise, they will be
     *             expanded.
     */
    CollapsibleSection.prototype.setCollapseState = function(doCollapse) {
        this.section.toggleClass('collapsed', doCollapse);
        this.trigger.attr('aria-expanded', !doCollapse);
        this.contents.attr('aria-hidden', !!doCollapse);
        this.collapsed = doCollapse;
    };

    lkb.collapsiblesection = (function() {
        function collapsibleInit() {
            $('._jsCollapsibleSection').each(function() {
                var collapsibleSection = new CollapsibleSection($(this));
                collapsibleSection.init();
            });
        }

        return {
            collapsibleInit: collapsibleInit
        };
    })();

    lkb.collapsiblesectionsingle = (function() {
        function collapseSingle(section) {
            var collapsibleSection = new CollapsibleSection($(section));
            collapsibleSection.init();
        }

        return {
            collapseSingle: collapseSingle
        };
    })();

    lkb.collapsiblesection.collapsibleInit();

})(jQuery);;
(function ($) {
    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0].toLowerCase());
            vars[hash[0].toLowerCase()] = urlDecode(hash[1]);
        }
        return vars;
    }

    function urlDecode(str) {
        return decodeURIComponent((str + '').replace(/\+/g, '%20'));
    }

    if ($('form.EPiServerForms').length) {
        var urlVars = getUrlVars();
        if (urlVars.length) {
            urlVars.forEach(function(element) {
                if (element === undefined || element === 'undefined' || element === '')
                    return;

                var elementValue = getUrlVars()[element];
                if (elementValue === undefined || elementValue === 'undefined' || elementValue === '')
                    return;

                var elementField = $('.' + element + ' .FormTextbox__Input');
                if (elementField.length) {
                    elementField.val(elementValue);
                    return;
                }

                elementField = $('.' + element + " .FormChoice__Input[value='" + elementValue + "']");
                if (elementField.length) {
                    elementField.prop('checked', true);
                    return;
                }

                elementField = $('.' + element + " .FormSelection select option[value='" + elementValue + "']");
                if (elementField.length) {
                    elementField.prop('selected', true);
                    return;
                }
            });

            var elementValue = urlVars['steg'];
            if (elementValue !== undefined && elementValue === '2') {
                var firstStep = $('.Form__NavigationBar__ProgressIndicator li:first.current');
                var buttonNext = $('form.EPiServerForms button.btnNext');
                if (firstStep.length && buttonNext.length) {
                    window.history.replaceState(null, null, window.location.pathname);
                    buttonNext.click();
                }
            }

            elementValue = urlVars['theme'];
            if (elementValue === undefined || elementValue === 'undefined' || elementValue === '') {
                window.history.replaceState(null, null, window.location.pathname);
            }
        }
    }

})(jQuery);;
var Graph = function (clientId, pointCount, yScale, startDate, dateDiffs) {
    this.container = $('#' + clientId);
    this.maincoordinateSystem = this.getPathData('.mainPath');
    //this.referencecoordinateSystem = this.getPathData('.referencePath');
    this.coordinateSystemWidth = (parseFloat(this.container.find('.coordinateSystem').attr('width'))) / 100;
    this.pointCount = this.maincoordinateSystem.length / 2;
    this.yScale = yScale;
    this.startDate = startDate;
    this.dateDiffs = dateDiffs;
    this.lastX = 0;
    this.lastY = 0;
    this.init();
}

$.extend(Graph.prototype, {
    init: function () {
        var self = this;
        this.container.find('.mouseCanvas').mousemove(function (eventObject) {

            // Temporary disable tooltip until series can show fond index value and accumulated value
            return;

            if (self.lastX == eventObject.clientX && self.lastY == eventObject.clientY) {
                return;
            }
            self.lastX = eventObject.clientX;
            self.lastY = eventObject.clientY;
            var mouseX = eventObject.clientX - $(this).offset().left;
            var xFactor = (self.pointCount - 1) / ((self.coordinateSystemWidth) * (self.container.width() - 4));
            
            var xindex = Math.floor(xFactor * mouseX) * 2;

            if (parseInt(xindex / 2) * 2 != xindex) {
                xindex--;
            }
            if (xindex + 1 > self.maincoordinateSystem.length) {
                xindex = self.maincoordinateSystem.length - 2;
            }

            if (xFactor < 1) {
                var foo = 492 / self.maincoordinateSystem.length - 1;
            }

            

            var infoDate = new Date(self.startDate.getTime());
            var dayDiff = self.dateDiffs[xindex / 2]
            infoDate.setDate(infoDate.getDate() + dayDiff);

            var yMain = self.maincoordinateSystem[xindex + 1];
            //var yReference = self.referencecoordinateSystem[xindex + 1];
            var yMainPos = yMain / self.yScale;
            //var yReferencePos = yReference / self.yScale;            
            var yMax = parseInt($(".yLables text[y='0']").html());

            var textInfo = infoDate.toDateString() + '</br>' +
            '<span>Fondets verdi: </span><em> ' + (yMax - yMain).toFixed(2) + '</em>';
            //'</br><span class="">' + self.container.find('.referenceDescription').text() + ':</span><em>' + (yMax - yReference).toFixed(2) + '</em>';

            self.container.find('.toolTip > div').stop().fadeTo(100, 0.2, function () {
                self.container.find('.toolTip > div').html(textInfo);
                self.container.find('.toolTip > div').fadeTo(100, 1, function () {
                    self.container.find('.toolTip').show();
                });
            });

            self.container.find('.toolTip').stop().animate(
                        {
                            left: mouseX + self.container.offset().left + 115 + 'px',
                            top: yMainPos + self.container.offset().top + 5 + 'px'
                        }, 100);

            self.container.find('.mainMarker')
                            .show()
                            .attr('cx', mouseX)
                            .attr('cy', yMainPos);

            //self.container.find('.referenceMarker')
            //                .show()
            //                .attr('cx', mouseX)
            //                .attr('cy', yReferencePos);
        });
    }
});

$.extend(Graph.prototype, {
    getPathData: function (className) {
        var data = this.container.find(className).attr('d');        
        var dataArray = data.split(',');
        if (dataArray.length < 2) {            
            data = data.replace(/ L /g, ' ').replace(/M /, '');
            dataArray = data.split(' ');
        }
        return dataArray;
    }
});;
/**
 * Step for step guide
 */

const containerAttribute = 'data-guide';
const progressAttribute = 'data-guide-progress';
const paginationAttribute = 'data-guide-pagination';
const placeholderAttribute = 'data-guide-placeholder';
const toggleAttribute = 'data-guide-toggle';
const nextAttribute = 'data-guide-next';
const prevAttribute = 'data-guide-previous';
const controlsAttribute = 'aria-controls';
const expandedAttribute = 'aria-expanded';
const currentAttribute = 'aria-current';
const cloneCssClass = 'is-clone';
const backwardCssClass = 'is-going-backwards';
const hidingCssClass = 'is-being-hidden';
const breakpointCssVar = '--guide-breakpoint';
const durationCssVar = '--guide-transition-duration';


document.querySelectorAll(`[${containerAttribute}]`).forEach((container) => {

    const placeholder = container.querySelector(`[${placeholderAttribute}]`);
    const pagination = container.querySelector(`[${paginationAttribute}]`);
    const buttons = container.querySelectorAll(`[${toggleAttribute}]`);

    // Open first element on desktop
    if (buttons.length > 0 && isDesktop()) {
        toggle(buttons[0]);
    }
    
    // Accordion
    buttons.forEach((button) => {
        button.addEventListener('click', (e) => toggle(e.target));
    });

    // Pagination
    if (pagination) {
        const nextTarget = pagination.querySelector(`[${nextAttribute}]`);
        const prevTarget = pagination.querySelector(`[${prevAttribute}]`);

        if (nextTarget) {
            nextTarget.addEventListener('click', (e) => next(e.target));
        }

        if (prevTarget) {
            prevTarget.addEventListener('click', (e) => prev(e.target));
        }
    }

    // Placeholder pagination
    placeholder.addEventListener('click', (e) => {
        const target = e.target;

        if (target.hasAttribute(nextAttribute)) {
            next(target);
        } else if (target.hasAttribute(prevAttribute)) {
            prev(target);
        }

    });
});

// Toggle item state
function toggle(el) {
    if (!el) {
        return;
    }

    const currentProgress = getProgress(el);

    if (isExpanded(el)) {
        closeAll(el);
        unsetProgress(el);
    } else {
        closeAll(el);
        setProgress(el);
        open(el);
        clone(el, currentProgress);
    }
}

// Close all items
function closeAll(el) {
    const container = el.closest(`[${containerAttribute}]`);
    const placeholder = container.querySelector(`[${placeholderAttribute}]`);

    container.querySelectorAll(`[${toggleAttribute}]`).forEach((item) => {
        close(item);
    });

    // Remove clones
    if (placeholder) {
        const children = placeholder.childNodes;
        const controlsId = el.getAttribute(controlsAttribute);
        const target = controlsId ? document.getElementById(controlsId) : null;
        const duration = getComputedStyle(document.documentElement).getPropertyValue(durationCssVar) || 0;

        if (target && children.length > 0) {
            children.forEach((item) => item.classList.add(hidingCssClass));
            setTimeout(() => {
                children.forEach((item) => item.remove());
            }, duration);
        }
    }
}

// Close single item
function close(el) {
    if (isExpanded(el)) {
        const controlsId = el.getAttribute(controlsAttribute);
        const target = controlsId ? document.getElementById(controlsId) : null;

        if (target) {
            el.setAttribute(expandedAttribute, 'false');
            el.setAttribute(currentAttribute, 'false');
            target.hidden = true;
        }
    }
}

// Open single item
function open(el) {
    if (!isExpanded(el)) {
        const controlsId = el.getAttribute(controlsAttribute);
        const target = controlsId ? document.getElementById(controlsId) : null;

        if (target) {
            target.hidden = false;
            el.setAttribute(expandedAttribute, 'true');
            el.setAttribute(currentAttribute, 'step');
            snapTo(el);
        }
    }
}

// Next item in list
function next(el) {
    const container = el.closest(`[${containerAttribute}]`);
    const items = container.querySelectorAll(`[${toggleAttribute}]`);
    let progress = container.getAttribute(progressAttribute) || -1;

    progress++;
    toggle(items[progress]);
}

// Previous item in list
function prev(el) {
    const container = el.closest(`[${containerAttribute}]`);
    const items = container.querySelectorAll(`[${toggleAttribute}]`);
    let progress = container.getAttribute(progressAttribute);

    if (progress) {
        progress--;
        toggle(items[progress]);
    }
}

// Set progress
function setProgress(el) {
    const container = el.closest(`[${containerAttribute}]`);
    const items = container.querySelectorAll(`[${toggleAttribute}]`);
    let i = 0;

    while (i < items.length) {
        if (items[i] === el) {
            container.setAttribute(progressAttribute, i);
            break;
        }
        i++;
    }

    updatePagination(container, i, items.length);
}

// Get current progress
function getProgress(el) {
    const container = el.closest(`[${containerAttribute}]`);
    const progress = container.getAttribute(progressAttribute) || 0;

    return progress;
}

// Unset progress
function unsetProgress(el) {
    const container = el.closest(`[${containerAttribute}]`);
    
    container.removeAttribute(progressAttribute);
    updatePagination(container);
}

// Update pagination
function updatePagination(container, progress = 0, max = null) {
    if (!container) {
        return;
    }

    const pagination = container.querySelector(`[${paginationAttribute}]`);
    
    if (pagination) {
        const total = (!max ? container.querySelectorAll(`[${toggleAttribute}]`).length : max);
        const next = pagination.querySelector(`[${nextAttribute}]`);
        const prev = pagination.querySelector(`[${prevAttribute}]`);

        // Enable prev-buttons if progress is beyond the first step, if not we disable them
        if (prev) {
            if (progress > 0 && total > 1) {
                prev.disabled = false;
            } else {
                prev.disabled = true;
            }
        }

        // Disable next-buttons if progress is at the last step, if not we enable them
        if (next) {
            if (progress == (total - 1)) {
                next.disabled = true;
            } else {
                next.disabled = false;
            }
        }
    }
}

// Toggle clones
function clone(el, progress = 0) {
    const container = el.closest(`[${containerAttribute}]`);
    const placeholder = container.querySelector(`[${placeholderAttribute}]`);

    if (placeholder) {

        const children = placeholder.childNodes;
        const controlsId = el.getAttribute(controlsAttribute);
        const target = controlsId ? document.getElementById(controlsId) : null;
        const isGoingForwards = (progress > getProgress(el) ? false : true);
        const duration = getComputedStyle(document.documentElement).getPropertyValue(durationCssVar) || 0;

        if (target) {
            // Create clone
            const parent = document.createElement('div');
            parent.classList.add(cloneCssClass);

            if (!isGoingForwards) {
                parent.classList.add(backwardCssClass);
            }

            if (target.hasChildNodes()) {
                target.childNodes.forEach((child) => {
                    let clone = child.cloneNode(true);
                    parent.appendChild(clone);
                });
            }

            if (children.length > 0) {
                children.forEach((item) => item.classList.add(hidingCssClass));
                setTimeout(() => {
                    children.forEach((item) => item.remove());
                    placeholder.appendChild(parent);
                }, duration);
            } else {
                placeholder.appendChild(parent);
            }
        }
    }
}

// Snap to target
function snapTo(el) {
    if (isDesktop()) {
        const top = el.offsetTop;
        el.offsetParent.scrollTo(0, top);
    } else {
        el.scrollIntoView();
    }
}

// Check if element is expanded
function isExpanded(el) {
    return (el.getAttribute(expandedAttribute) === 'true');
}

// Check if viewport matches desktop
function isDesktop() {
    const size = getComputedStyle(document.documentElement).getPropertyValue(breakpointCssVar);

    if (!size) {
        return false;
    }

    const isDesktop = window.matchMedia(`(min-width: ${size})`);
    return isDesktop.matches;
}

;
(function ($) {
    let deleteSupport = true;

    if (typeof DataTransfer === "undefined") {
        deleteSupport = false;
    }

    //jQuery Filestyle and file handling
    const initJFileHandler = function () {
        const $fileElements = $(':file');
        const uploadItemClass = 'FormFileUpload__Item';
        const uploadFileClass = 'FormFileUpload__Filename';
        const uploadRemoveClass = 'remove-file-button';
        const containerClass = '_jsFileListSummary';
        const headingClass = '_jsFileListHeading';
        const listClass = '_jsFileNameList';
        const removeClass = '_jsFileItemRemove';

        //loop through and setup file handling
        $fileElements.each(function (i) {
            const $file = $(this);

            $file.jfilestyle({
                text: $file.data('text'),
                input: true,
                'onChange': function (files) {
                    const $container = $file.parent().find('.' + containerClass);
                    const $heading = $container.find('.' + headingClass);
                    const $list = $container.find('.' + listClass);

                    if (!deleteSupport) {
                        $list.addClass('hide-buttons');
                    }

                    if (files.length === 0) {
                        $heading.hide();
                        $list.hide();
                        return;
                    }

                    $list.empty();

                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];

                        //create new elements, append it to summary-list and clone file input + data
                        $list.append($('<li>')
                            .data('file', files[i])
                            .append($('<div>')
                                .attr('class', uploadItemClass)
                                .append($('<span>')
                                    .attr('class', uploadFileClass)
                                    .append(file.name + ' (' + formatBytes(file.size, 1) + ')'), $('<button>')
                                    .attr({
                                        type: 'button', 
                                        class: uploadRemoveClass + ' ' + removeClass
                                    }).append($container.data('remove-text')))));
                    }
                    
                    $list.data('files', files);
                    $list.data('file-input', $file);

                    //Update summary heading
                    const count = $list.children().length;
                    if (count > 0) {
                        if (count > 1) {
                            $heading.text(count + $container.data('heading'));
                        } else {
                            $heading.text(count + $container.data('heading-singular'));
                        }
                        $heading.show();
                        $list.show();
                    }
                }
            });
        });

        //remove selected item on click
        $('.' + containerClass).on('click', '.' + removeClass,
            function () {
                const $container = $(this).closest('.' + containerClass);
                const $heading = $container.find('.' + headingClass);
                const $list = $container.find('.' + listClass);
                const filesArray = Array.from($list.data('file-input')[0].files);
                const fileToRemove = $(this).closest('li').data('file');
                filesArray.splice(filesArray.indexOf(fileToRemove), 1);

                const files = createFileList(filesArray);

                if (filesArray.length === 0) {
                    $heading.hide();
                    $list.hide();
                }

                $list.data('file-input')[0].files = files;
                $list.data('file-input').trigger('change');
            });
    };

    initJFileHandler();

    function formatBytes(bytes, decimals) {
        if (bytes === 0) return '0 byte';

        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }

    function createFileList(files) {
        const dataTransfer = new DataTransfer();
        for (let index = 0; index < files.length; index++) {
            dataTransfer.items.add(files[index]);
        }

        return dataTransfer.files;
    }
})(jQuery);;
$(function () {
    const breakPoint = 700;
    const viewPort = $(window).width();
    
    const translations = {
        i18n: {
            prev: 'Forrige slide',
            next: 'Neste slide',
            first: "Gå til første slide",
            last: "Gå til siste slide",
            slideX: "Gå til slide %s",
            slideY: "Gå til slide %s",
        }
    }
    
    const options = {
        jumbo: {
            type: 'loop',
            perPage: 1,
            autoplay: true,
            interval: 6000,
            speed: 1000,
            easing: 'cubic-bezier(0.0, 0.0, 0.58, 1.0)',
            classes: {
                arrows: 'splide__arrows splide__arrow--hidden',
                arrow: 'splide__arrow splide__arrow--hidden',
            }
        }
    }
    
    $('._jsJumbo').each(function (_, element) {
        const splide = new Splide(element, { ...options.jumbo, ...translations});

        splide.on('pagination:mounted', function (data) {
            data.list.classList.add('splide__pagination--custom');
            data.items.forEach(function (item) {
                const slideId = $(item.button).attr('aria-controls');
                item.button.innerHTML = String(
                    `<div class='jumbo-progress-bar'><div class='_jsAnimateProgress'></div></div><div class='jumbo-progress__text'>${$('#'+slideId).find('._jsButtonText').text()}</div>`
                );
            });
        });

        splide.on('move', function (newIndex) {
            $(splide.root).find('.jumbo-progress-bar').each(function (index, element) {
                index < newIndex ? $(element).addClass('jumbo-progress-bar--fw') : $(element).removeClass("jumbo-progress-bar--fw");
            })
        });

        splide.on('autoplay:playing', function (rate) {
            $(splide.root).find('.is-active > .jumbo-progress-bar > ._jsAnimateProgress').css("width", rate * 100 +"%");
        });
        
        splide.mount();

    })
});;
var radiobuttons = document.querySelectorAll('.js-radioContent-input[role="radio"]');

radiobuttons.forEach(function(radiobutton) {
    radiobutton.addEventListener('change', function(event) {
        event.preventDefault();

        var parent = radiobutton.closest('.js-radioContent');
        var contentRadiobuttons = parent.querySelectorAll('.js-radioContent-input');
        var contentPanels = parent.querySelectorAll('.js-radioContent-panel');
        var target = parent.querySelector('#'+radiobutton.getAttribute('aria-controls'));

        contentRadiobuttons.forEach(function(element) {
            element.setAttribute('aria-selected', false);
        });
        contentPanels.forEach(function(element) {
            element.setAttribute('aria-hidden', true);
        });

        radiobutton.setAttribute('aria-selected', true);
        target.setAttribute('aria-hidden', false);
    });
});
;
$(() => {
    const scrollBlocks = $('._jsScroll');
    const carousel = $('._jsCarousel');

    const options = {
        scrollBlock: {
            small: {
                breakpoints: {
                    320: {
                        slidesPerView: 1.2,
                        spaceBetween: 8
                    },
                    480: {
                        slidesPerView: 1.5,
                        spaceBetween: 8
                    },
                    768: {
                        slidesPerView: 2.5,
                        spaceBetween: 8
                    },
                    1280: {
                        slidesPerView: 3.5,
                        spaceBetween: 8
                    },
                    1920: {
                        slidesPerView: 4,
                        spaceBetween: 12
                    }
                }

            },
            big: {
                slidesPerView: 1.2,
                spaceBetween: 16,
                breakpoints: {
                    400: {
                        slidesPerView: 1.5,
                        spaceBetween: 8
                    },
                    768: {
                        slidesPerView: 1,
                        spaceBetween: 8
                    },
                    1280: {
                        slidesPerView: 1.25,
                        spaceBetween: 16
                    }
                }
            },
            common: {
                navigation: {
                    nextEl: '.scroll-block__button--next',
                    prevEl: '.scroll-block__button--prev',
                },
                pagination: {
                    el: '.scroll-block__progress',
                    type: 'progressbar',
                    progressbarFillClass: 'scroll-block__fill'
                }
            }
        },
        carousel: {
            main: function (autoPlay, slideSpeed = 0, thumbSwiper = null) {
                return {
                    loop: true,
                    spaceBetween: 10,
                    navigation: {
                        nextEl: ".carousel-block__next",
                        prevEl: ".carousel-block__prev"
                    },
                    thumbs: {swiper: thumbSwiper === null ? null : thumbSwiper},
                    pagination: {
                        el: '.carousel-block__progress',
                        type: 'fraction',
                    },
                    centeredSlides: true,
                    autoplay: autoPlay === 'true' ? {
                        delay: slideSpeed > 0 ? slideSpeed * 1000 : 5000,
                        pauseOnMouseEnter: true
                    } : false,
                }
            },
            thumbs: {
                loop: false,
                spaceBetween: 10,
                slidesPerView: 'auto',
                freeMode: true,
                watchSlidesProgress: true,
                navigation: {
                    nextEl: ".carousel-block__thumb-next",
                    prevEl: ".swiper-button-prev"
                },
            }
        },
        common: {
            a11y: {
                prevSlideMessage: 'Forrige slide',
                nextSlideMessage: 'Neste slide',
                firstSlideMessage: 'Første slide',
                lastSlideMessage: 'Siste slide',
            }
        }
    }

    if (scrollBlocks.length) {
        const bigElementsClasses = ['teaser-block--overlap', 'teaser-block', 'teaser-block--right-image', 'teaser-block--left-image'];
        scrollBlocks.each((_, element) => {
            const big = $(element).find('.swiper-slide:first > *').hasClass(...bigElementsClasses);

            new Swiper(element, big ?
                {...options.scrollBlock.big, ...options.scrollBlock.common, ...options.common} :
                {...options.scrollBlock.small, ...options.scrollBlock.common, ...options.common});
        });
    }

    if (carousel.length) {
        carousel.each((_, element) => {
            const main = $(element).find('._jsCarouselMain');
            const thumbs = $(element).find('._jsCarouselThumbs');
            thumbs.length ? initCarousel(main[0], new Swiper(thumbs[0], {...options.carousel.thumbs, ...options.common})) : initCarousel(main[0]);
        });

        function initCarousel(main, thumbSwiper) {
            const autoPlay = $(main).data('autoslide').toLowerCase();
            const slideSpeed = parseFloat($(main).data('slidespeed'));
            const carousel = new Swiper(main, {...options.carousel.main(autoPlay, slideSpeed, thumbSwiper), ...options.common});
            carousel.on('slideChange', function () {
                $(this.$el).find('.swiper-slide-active > a').attr('tabindex', '-1');
                $(this.$el).find('.swiper-slide-next > a').attr('tabindex', '0');
            });
        }
    }
});
var tabs = document.querySelectorAll('.js-tabbedContent-tab[role="tab"]');

tabs.forEach(function(tab) {
    tab.addEventListener('click', function(event) {
        event.preventDefault();

        var parent = tab.closest('.js-tabbedContent');
        var contentTabs = parent.querySelectorAll('.js-tabbedContent-tab');
        var contentPanels = parent.querySelectorAll('.js-tabbedContent-panel');
        var target = parent.querySelector(tab.getAttribute('href'));

        contentTabs.forEach(function(element) {
            element.setAttribute('aria-selected', false);
        });
        contentPanels.forEach(function(element) {
            element.setAttribute('aria-hidden', true);
        });

        tab.setAttribute('aria-selected', true);
        target.setAttribute('aria-hidden', false);

        history.replaceState(null, null, window.location.pathname);
    });
});

var hash = document.location.hash;

if (hash) {
    tabs.forEach(function(tab) {
        if (tab.getAttribute('href') === hash && tab.offsetParent !== null) {
            tab.click();
        }
    });
};
(function ($) {
    var isDateInputSupported = function (dateInput) {
        return $(dateInput).attr('type') === 'date';
    };

    $('[data-datepick]').each(function() {
        initDatePickerForm(this);
    });

    function initDatePickerForm(dateInput) {
        if (!isDateInputSupported(dateInput)) {

            var dateFrom = new Date($(dateInput).attr("data-min"));
            var dateTo = new Date($(dateInput).attr("data-max"));

            var options = {
                defaultDate: "+1w",
                numberOfMonths: 1,
                minDate: dateFrom,
                maxDate: dateTo
            }

            if ($(dateInput).attr("data-validateage") == 'True') {
                options.changeYear = true;
                options.yearRange = dateFrom.getFullYear() + ":" + dateTo.getFullYear();
            }

            $(dateInput).datepicker(options);
        }
    }
})(jQuery);;
(function ($) {
    if (window.epi) {
        (function (epi) {
            if (!epi.EPiServer || !epi.EPiServer.Forms) {
                return;
            }
            $.extend(true,
                epi.EPiServer.Forms,
                {
                    Validators: {
                        "Landkreditt.Web.Features.Forms.Validators.DateDDMMYYYYNOValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.BankNorwayValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {

                            let factor = 2;
                            let sum = 0;
                            let checkSum = parseInt(fieldValue[fieldValue.length - 1]);
                            for (i = fieldValue.length - 2; i >= 0; i--) {
                                sum += parseInt(fieldValue[i]) * factor;
                                factor += factor == 7 ? -5 : 1;
                            }
                            let calculatedCheckSum = (sum % 11) == 0 ? 0 : 11 - (sum % 11);
                            let validChecksum = calculatedCheckSum === checkSum;

                            const rgx = /^[1-9]\d{3}(\.|\s)?\d{2}(\.|\s)?\d{5}$/;
                            let valid = fieldValue.length === 0 || (rgx.test(fieldValue) && validChecksum);

                            return { isValid: valid, message: validatorMetaData.model.message };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.ZipNorwayValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            const rgx = /^(000[1-9]|0[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9])$/;
                            let valid = fieldValue.length === 0 || rgx.test(fieldValue);
                            return { isValid: valid, message: validatorMetaData.model.message };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.SocialNorwayValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {

                            const rgxFormat = /^(0[1-9]|[1-2][0-9]|31(?!(?:0[2469]|11))|30(?!02))(0[1-9]|1[0-2])(\d{2})\s?(\d{5})$/;
                            const formatValid = fieldValue.length === 0 || rgxFormat.test(fieldValue);

                            const rgx = /[^0-9]/;
                            const personNo = fieldValue.replace(rgx);

                            let birthDate = new Date(personNo.substring(4, 6), personNo.substring(2, 4), personNo.substring(0, 2));

                            const individualNumber = parseInt(personNo.substring(6, 9));
                            const twoDigitYear = birthDate.getFullYear() % 100;

                            if (individualNumber >= 0 && individualNumber <= 499) {
                                birthDate = new Date(1900 + twoDigitYear, birthDate.getMonth(), birthDate.getDate());
                            }
                            if (individualNumber >= 500 && individualNumber <= 749 && twoDigitYear >= 54 && twoDigitYear <= 99) {
                                birthDate = new Date(1800 + twoDigitYear, birthDate.getMonth(), birthDate.getDate());
                            }
                            if (individualNumber >= 500 && individualNumber <= 999 && twoDigitYear >= 0 && twoDigitYear <= 39) {
                                birthDate = new Date(2000 + twoDigitYear, birthDate.getMonth(), birthDate.getDate());
                            }
                            if (individualNumber >= 900 && individualNumber <= 999 && twoDigitYear >= 40 && twoDigitYear <= 99) {
                                birthDate = new Date(1900 + twoDigitYear, birthDate.getMonth(), birthDate.getDate());
                            }

                            let d1 = parseInt(personNo.substring(0, 1));
                            let d2 = parseInt(personNo.substring(1, 2));
                            let m1 = parseInt(personNo.substring(2, 3));
                            let m2 = parseInt(personNo.substring(3, 4));
                            let y1 = parseInt(personNo.substring(4, 5));
                            let y2 = parseInt(personNo.substring(5, 6));
                            let i1 = parseInt(personNo.substring(6, 7));
                            let i2 = parseInt(personNo.substring(7, 8));
                            let i3 = parseInt(personNo.substring(8, 9));

                            let checksum1 = 11 - ((3 * d1 + 7 * d2 + 6 * m1 + 1 * m2 + 8 * y1 + 9 * y2 + 4 * i1 + 5 * i2 + 2 * i3) % 11);
                            let checksum2 = 11 - ((5 * d1 + 4 * d2 + 3 * m1 + 2 * m2 + 7 * y1 + 6 * y2 + 5 * i1 + 4 * i2 + 3 * i3 + 2 * checksum1) % 11);

                            if (checksum1 == 11) {
                                checksum1 = 0;
                            }
                            if (checksum2 == 11) {
                                checksum2 = 0;
                            }

                            let checksum = checksum1 * 10 + checksum2;
                            let controlDigit = parseInt(personNo.substring(9));

                            let checksumValid = checksum === controlDigit;
                            let valid = fieldValue.length === 0 || (checksumValid && formatValid);

                            return { isValid: valid, message: validatorMetaData.model.message };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.AgeValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.GreaterThanValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.LessThanValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.CompareTextsValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.CompareNumbersValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {
                            return { isValid: true };
                        },
                        "Landkreditt.Web.Features.Forms.Validators.TotalFileSizeValidator": function (fieldName,
                            fieldValue,
                            validatorMetaData) {

                            let totalUploadedFileSize = 0;
                            for (i = 0; i < fieldValue.length; i++) {
                                let size = 0;

                                // size on first load. 
                                if (fieldValue[i].size) {
                                    size = fieldValue[i].size;
                                }

                                // file.size on later loads after validations callbacks kick in.
                                if (fieldValue[i].file && fieldValue[i].file.size) {
                                    size = fieldValue[i].file.size;
                                }

                                totalUploadedFileSize += parseInt(size);
                            }

                            return {
                                isValid: totalUploadedFileSize <= parseInt(validatorMetaData.model.additionalAttributes.totalFileSize),
                                message: validatorMetaData.model.message
                            };
                        }
                    }
                });
        })(epi);
    }
})(jQuery);;
