/* Minification failed. Returning unminified contents.
(1358,9-10): run-time error JS1010: Expected identifier: .
(1358,9-10): run-time error JS1195: Expected expression: .
(1359,2-6): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(1388,18-19): run-time error JS1010: Expected identifier: .
(1388,18-19): run-time error JS1195: Expected expression: .
(1467,7-8): run-time error JS1010: Expected identifier: .
(1467,7-8): run-time error JS1195: Expected expression: .
(1494,7-8): run-time error JS1010: Expected identifier: .
(1494,7-8): run-time error JS1195: Expected expression: .
(1509,11-12): run-time error JS1010: Expected identifier: .
(1509,11-12): run-time error JS1195: Expected expression: .
(1513,11-12): run-time error JS1010: Expected identifier: .
(1513,11-12): run-time error JS1195: Expected expression: .
(1521,7-8): run-time error JS1010: Expected identifier: .
(1521,7-8): run-time error JS1195: Expected expression: .
(1955,7-8): run-time error JS1010: Expected identifier: .
(1955,7-8): run-time error JS1195: Expected expression: .
 */
var elementFactory = {
    getBodyTag: function () {
        if (this.fields.bodyTag == null) {
            this.fields.bodyTag = $("body");
        }
        return this.fields.bodyTag;
    },
    getTopArea: function () {
        if (this.fields.topArea == null) {
            this.fields.topArea = $("#top-area");
        }
        return this.fields.topArea;
    },
    getTopMenu: function () {
        if (this.fields.topMenu == null) {
            this.fields.topMenu = $(".topmenu");
        }
        return this.fields.topMenu;
    },
    getSubMenu: function () {
        if (this.fields.subMenu == null) {
            this.fields.subMenu = $(".submenu");
        }
        return this.fields.subMenu;
    },
    getMainMenuHolder: function () {
        if (this.fields.mainMenuHolder == null) {
            this.fields.mainMenuHolder = $("ul.navbar-nav");
        }
        return this.fields.mainMenuHolder;
    },
    getBreadcrumbs: function () {
        if (this.fields.breadcrumbs == null) {
            this.fields.breadcrumbs = $("#breadcrumbs");
        }
        return this.fields.breadcrumbs;
    },
    getBackgroundCover: function () {
        if (this.fields.backgroundCover == null) {
            this.fields.backgroundCover = $(".background-cover");
        }
        return this.fields.backgroundCover;
    },
    getButtonPuffBlockContainer: function () {
        if (this.fields.buttonPuffBlockContainer == null) {
            this.fields.buttonPuffBlockContainer = $(".buttonpuffblock");
        }
        return this.fields.buttonPuffBlockContainer;
    },
    getRssContainer: function () {
        if (this.fields.rssContainer == null) {
            this.fields.rssContainer = $(".rss-container");
        }
        return this.fields.rssContainer;
    },
    getTagPuffContainer: function () {
        if (this.fields.tagpuffContainer == null) {
            this.fields.tagpuffContainer = $(".tagpuff");
        }
        return this.fields.tagpuffContainer;
    },
    fields: {
        bodyTag: null,
        topArea: null,
        topMenu:  null,
        subMenu: null,
        mainMenuHolder: null,
        breadcrumbs: null,
        backgroundCover: null,
        buttonPuffBlockContainer: null,
        rssContainer: null,
        tagpuffContainer: null
    }
};
;
var helpers = {
    isInEditMode: function () {
        if (elementFactory.getBodyTag().data("isineditmode") == "True") {
            return true;
        }
        return false;
    },

    isAuthenticated: function () {
        if (elementFactory.getBodyTag().data("isauthenticated") == "True") {
            return true;
        }
        return false;
    },

    scrollToSelector: function (selector, correction) {
        $('html, body').animate({
            scrollTop: $(selector).last().offset().top - correction
        }, 1000);
    },    

    getBrowserWidth: function(){
        if(window.innerWidth < 768){
            // Extra Small Device
            return "xs";
        } else if(window.innerWidth < 991){
            // Small Device
            return "sm"
        } else if(window.innerWidth < 1199){
            // Medium Device
            return "md"
        } else {
            // Large Device
            return "lg"
        }
    }
};
;
var global = {
    init: function () {
        //Print
        $('#print-button a').on("click", function (e) {
            e.preventDefault();
            window.print();
        });

        //other SLU websites
        if (!helpers.isInEditMode()) {
            $('.popup-modal').magnificPopup({
                type: 'inline',
                preloader: false,
                modal: true
            });
            $(document).on('click', '.popup-modal-dismiss', function (e) {
                e.preventDefault();
                $.magnificPopup.close();
            });
        }

        //tooltip
        $('.tooltip').tooltipster({
            animation: 'fade',
            delay: 200,
            position: 'bottom-right',
            maxWidth: 280,
            content: $('#image-tex-to-fetch').text()
        });

        //Copokie link function
        var element = document.getElementById("cookiesettings");
        if (element) {
            element.onclick = function (event) {
                return klaro.show();
            }
        }
    }
}
////TODO: bryta ut?
var customEventHandler = {
    trigger: function (eventType, eventMessage) {
        $.event.trigger({
            type: eventType,
            message: eventMessage,
            time: new Date()
        });
    },
    subscribe: function (eventType, callback) {
        $(document).on(eventType, function (e) {
            callback(e.message);
        });
    }
};
;
var contactHandler = {
    init: function () {
        this.attachEvents();
    },
    attachEvents: function () {

        var imageData = null;

        $("#attachment").on("change", function () {
            var file = document.getElementById("attachment").files[0];
            if (file) {
                var rdr = new FileReader();
                rdr.onloadend = function (e) {
                    imageData = e.target.result;
                    imageData = imageData.split(',')[1];
                };
                rdr.readAsDataURL(file);
            }
        });

        $('#contactform').validate({            
            errorClass: 'validation-error',
            rules: {
                txtName: {
                    required: true
                },
                txtEmail: {
                    required: true,
                    email: true
                },
                fileAttachment: {
                    extension: "jpg|jpeg|png|pdf",
                    maxsize: 2097152 //1048576: 1MB, 2097152: 2MB, 4194304: 4MB
                }
            },
            messages: {
                txtName: {
                    required: $('#contactform').find('#name').data("error-message")
                },
                txtEmail: {
                    required: $('#contactform').find('#email').data("error-message"),
                    email: $('#contactform').find('#email').data("error-message2")
                },
                fileAttachment: {
                    extension: $('#contactform').find('#attachment').data("error-message-filetype"),
                    maxsize: $('#contactform').find('#attachment').data("error-message-filesize")
                }
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element);
                error.addClass("field-validation-error");
            },
            submitHandler: function (form) {
                var formData = contactHandler.createformData(form, imageData);
                contactHandler.submitcontactForm(formData);
            }
        });

        $(".open-contact-form").on("click", function (e) {
            e.preventDefault();
            var container = $('.contact-form');
            container.slideToggle();
            $(this).find(".fa-angle-down, .fa-angle-up").toggleClass("fa-angle-down fa-angle-up");
        });
    },

    createformData: function (formvalues, imageData) {
        var formData = {
            Name: formvalues.name.value,
            Email: formvalues.email.value,
            Message: formvalues.message.value,
            ContentId: formvalues.contentId.value,
            UserName: formvalues.userName.value,
            ContextLanguage: formvalues.contextLanguage.value,
            FileName: formvalues.attachment.files.length > 0 ? formvalues.attachment.files[0].name : null,
            MediaType: formvalues.attachment.files.length > 0 ? formvalues.attachment.files[0].type : null,
            Attachment: imageData
        };

        return formData;
    },

    submitcontactForm: function (formData) {
        ajaxHandler.submitForm(contactHandler.apiUrl.url, formData, function (data) {
            var container = $('.contact-form');
            if (data.StatusOk) {
                container.find('#contactform').hide();
            }
            container.find('#result').html(data.Message);
            container.find('#result').show();
        });
    },

    apiUrl: {
        url: "/api/contactform/post"
    }
};
;
var megamenuHandler = {
    init: function () {
        this.attachEvents();

    },
    attachEvents: function () {

        $(".close-menu").hide();

        $(document).on('click', '.yamm .dropdown-menu', function (e) {
            e.stopPropagation()
        })

        $(document).on('click', '.dropdown.yamm-fw > a', function (e)
        {
            var w = $('body').innerWidth();

            if(w > 992 )
            {
                e.preventDefault();
                $(".dropdown.yamm-fw.open").not($(this).parent("li")).removeClass("open");
                $(this).parent("li").toggleClass("open");
            }
        });

        elementFactory.getMainMenuHolder().find("li").each(function () {
            if ($(this).has("a")) {
                $(this).on("click", function (e) {
                    if (!$(this).hasClass("open")) {
                        elementFactory.getBodyTag().addClass("open-menu opened");
                    }
                    else {
                        if (!elementFactory.getBodyTag().hasClass("keep-open-menu"))
                        {
                            elementFactory.getBackgroundCover().hide();
                            elementFactory.getBodyTag().removeClass("open-menu");
                        }
                    }

                    elementFactory.getBodyTag().removeClass("keep-open-menu");
                });
            }

            if ($(this).has("ul")) {
                $(this).find("ul").on("click", function (e) {
                    elementFactory.getBodyTag().addClass("keep-open-menu");                    
                });
            }
        });
        elementFactory.getBackgroundCover().on("click", function () {
            $(this).hide();
            elementFactory.getBodyTag().removeClass("open-menu");
            elementFactory.getBodyTag().removeClass("opened");
            $(".dropdown.yamm-fw.open").removeClass("open");
        });
        elementFactory.getTopArea().on("click", function () {
            elementFactory.getBackgroundCover().hide();
            elementFactory.getBodyTag().removeClass("open-menu");
            elementFactory.getBodyTag().removeClass("opened");
            $(".dropdown.yamm-fw.open").removeClass("open");
        });
        elementFactory.getBreadcrumbs().on("click", function () {
            elementFactory.getBackgroundCover().hide();
            elementFactory.getBodyTag().removeClass("open-menu");
            elementFactory.getBodyTag().removeClass("opened");
            $(".dropdown.yamm-fw.open").removeClass("open");
        });
        elementFactory.getTopMenu().on("click", function () {
            if (!elementFactory.getBodyTag().hasClass("opened")) {
                elementFactory.getBackgroundCover().hide();
                elementFactory.getBodyTag().removeClass("open-menu");
            }
            elementFactory.getBodyTag().removeClass("opened");            
           
        });
        elementFactory.getSubMenu().on("click", function () {
            if (!elementFactory.getBodyTag().hasClass("opened")) {
                elementFactory.getBackgroundCover().hide();
                elementFactory.getBodyTag().removeClass("open-menu");
            }
            elementFactory.getBodyTag().removeClass("opened");
           
        });

    }
};
//var height = elementFactory.getButtonPuffBlockContainer().height();

var clickableDivHandler = {

    initButtonPuffBlocks: function () {
        elementFactory.getButtonPuffBlockContainer().each(function () {
            clickableDivHandler.addTitle($(this));
            clickableDivHandler.animate($(this));
            clickableDivHandler.makeClickable($(this));            
        });

        //clickableDivHandler.setSameHeight($(this));
        //clickableDivHandler.setSameHeight();
    },

    initTagPuffs: function () {
        elementFactory.getTagPuffContainer().each(function () {
            //alert('d');
            //clickableDivHandler.addTitle($(this));
            clickableDivHandler.makeClickable($(this));
        });
    },
    addTitle: function (container) {
        if (container.find("a").length) {
            container.attr('title', container.find("a:first").attr("title"));
        }
    },
    animate: function (container) {
        if (window.matchMedia("(min-width: 768px)").matches) {
            container.on("hover",
                function () {
                    $(this).css("background", "#ddd");
                },
                function () {
                    $(this).css("background", "");
                }
            );
        }
    },
    makeClickable: function (container) {
        container.on("click", function () {
            if ($(this).find("a").length) {
                window.location.href = $(this).find("a:first").attr("href");
            }
        });
    }
}
;
var SmartphoneMenuHandler = {
    init: function () {
        this.attachEvents();
    },
    attachEvents: function ()
    {
        $(".navbar-toggle").on("click", function ()
        {
            $("header").addClass("non-sticky");
            $(".links-button, .search-button").hide();
            $(".quicksearch-container").removeClass("open");

            if ($(".submenu").length > 0)
            {
                
                SmartphoneMenuHandler.setTopMenuStartingPoint();
                $(".topmenu .menu-positioner").removeClass("center-pos").addClass("left-pos");
                                
                // leta upp den sida man är på
                var currentMenuItem = $(".submenu").find("[data-menuitemid='" + $("body").data("currentid") + "']");
               
                if (currentMenuItem.length > 0)
                {
                    $(".submenu .menu-positioner").removeClass("center-pos").removeClass("left-pos").addClass("right-pos");
                    currentMenuItem.parents(".menu-positioner").removeClass("right-pos").addClass("left-pos");
                    currentMenuItem.parents(".menu-positioner").first().addClass("center-pos").removeClass("left-pos").removeClass("right-pos");
                }
                else
                {
                    $(".submenu #navbar-collapse-grid > .menu-positioner").addClass("center-pos").removeClass("right-pos").removeClass("left-pos");
                }
                $(".topmenu #navbar-collapse-grid").fadeIn();
                $(".submenu #navbar-collapse-grid").fadeIn();
            }
            else
            {                
                var currentMenuItem = $(".topmenu #navbar-collapse-grid").find("[data-menuitemid='" + $("body").data("currentid") + "']");
                
                if(currentMenuItem.length > 0)
                {
                    $(".topmenu #navbar-collapse-grid .menu-positioner").removeClass("center-pos").removeClass("left-pos").addClass("right-pos");
                    SmartphoneMenuHandler.setTopMenuStartingPoint;
                    currentMenuItem.parents(".menu-positioner").removeClass("center-pos").removeClass("right-pos").addClass("left-pos");
                    currentMenuItem.parents(".menu-positioner").first().addClass("center-pos").removeClass("left-pos").removeClass("right-pos");
                }
                else
                {
                    SmartphoneMenuHandler.setTopMenuStartingPoint;                    
                }
                $(".topmenu #navbar-collapse-grid").fadeIn();
            }
        });
        
        // close the menu
        $(".smartphone-header-button.close-button").on("click", function ()
        {
            $(".topmenu #navbar-collapse-grid, .submenu #navbar-collapse-grid").fadeOut();
            $(".links-button, .search-button").show();
            $("#links-collapse").hide();
            $(".quicksearch-container").removeClass("open");
            $("header").removeClass("non-sticky");
        });

        $(".to-top-menu").on("click", function () {
            // se till så att roten visas
            $(".submenu .center-pos").toggleClass("center-pos right-pos");            
            $(".topmenu #navbar-collapse-grid > .left-pos").toggleClass("left-pos center-pos");

            SmartphoneMenuHandler.setTopMenuStartingPoint();

            setTimeout(SmartphoneMenuHandler.slideMenu, 400);
        });

        $(".smartphone-header-button.search-button").on("click", function () {
            $(".quicksearch-container").toggleClass("open");
            
            //$(".quicksearch-container.open").sticky({ topSpacing: 0 });
            
            $(this).toggleClass("active");
        });

        $(".open-sub-menu.level-3").on("click", function ()
        {
            $(this).parents(".nav.navbar-nav").removeClass("center-pos").addClass("left-pos");
            $(this).next(".dropdown-menu").addClass("center-pos").removeClass("right-pos");
        });

        $(".open-sub-menu.level-4").on("click", function () {
            $(this).parents(".dropdown-menu").toggleClass("left-pos center-pos");
            $(this).next(".dropdown-menu-level-4").toggleClass("center-pos right-pos");          
        });

        $(".back-button").on("click", function ()
        {
            $(this).parents(".center-pos").first().removeClass("center-pos").addClass("right-pos");
            $(this).parents(".left-pos").first().removeClass("left-pos").addClass("center-pos");                        
        });

        $(".links-button").on("click", function ()
        {
            $("header").addClass("non-sticky");
            $(".links-button").hide();
            $(".topmenu #links-collapse").fadeIn();

            $(".topmenu #links-collapse").removeClass("right-pos").removeClass("left-pos").addClass("center-pos");
            $(".topmenu #links-collapse > .menu-positioner").removeClass("right-pos").removeClass("left-pos").addClass("center-pos");
            $(".topmenu #links-collapse > .menu-positioner .menu-positioner").removeClass("center-pos").removeClass("left-pos").addClass("right-pos");

        });
    },
    slideMenu : function ()
    {
        $(".submenu #navbar-collapse-grid").hide();
    },
    setTopMenuStartingPoint : function()
    {
        $(".topmenu #navbar-collapse-grid .menu-positioner:not(.navbar-nav)").addClass("no-animation");
        $(".topmenu .menu-positioner").removeClass("center-pos").removeClass("left-pos").addClass("right-pos");        
        $(".topmenu #navbar-collapse-grid > .menu-positioner").removeClass("right-pos").addClass("center-pos");
        
        $(".topmenu #navbar-collapse-grid .menu-positioner").removeClass("no-animation"); 
    }
};
var ajaxHandler = {
    getRssReaderDataItems: function (currentContentId, cacheKey, language, callBack) {
        $.ajax({
            type: "GET",
            url: "/api/rssreaderdata/" + currentContentId + "/" + cacheKey + "/" + language,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                callBack(data);
            },
            error: function () {
                var container = elementFactory.getRssContainer();
                container.empty();
                container.append("<span>Kan inte läsa in RSS-källan</span>");
            }
        });
    },
    search: function (apiUrl, searchFilter, shouldCache, callBack, extraCallback, type) {

        if (!type)
            type = "GET";

        $('main.content-wrapper').on('keydown', function (e) {
            e.preventDefault();
        });

        $('.loading').show();

        $.ajax({
            type: type,
            url: apiUrl,
            contentType: "application/json; charset=utf-8",
            data: searchFilter,
            dataType: "json",
            async: true,
            cache: shouldCache,
            success: function (data) {
              callBack(data);
                if (typeof extraCallback === 'function') {
                    extraCallback();
                }
            },
            complete: function () {
                $('.loading').hide();
                $('main.content-wrapper').off('keydown');
            }
        });
    },
    submitForm: function (apiUrl, formData, callBack) {
        $('.loading').show();
        $.ajax({
            type: "POST",
            url: apiUrl,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formData),
            dataType: "json",
            async: false,
            success: function (data) {
                $('.loading').hide();
                callBack(data);
            },
            error: function (data) {
                $('.loading').hide();
                callBack(data);
            }
        });
    },
    apiUrl: {
        global: "/api/globalsearch",
        tag: "/api/tagsearch",
        occasions: "/api/coursesearch/searchoccasions",
        listPageSearch: '/listPageSearch'
    }
}
;
var clientSearchHelper = {
    createGlobalSearchFilter: function (searchQuery, sectionFilterArray, skip, take, cache, sortOrder, language, site) {
        var searchFilter = {
            SearchQuery: searchQuery,
            SectionFilters: sectionFilterArray,
            Skip: skip,
            Take: take,
            Cache: cache
        };
        if (sortOrder !== '') {
            searchFilter.SortOrder = sortOrder;
        }
        if (language !== '') {
            searchFilter.Language = language;
        }
        if (site !== '') {
            searchFilter.Site = site;
        }
        return searchFilter;
    },

    createTagSearchFilter: function (categoyId, skip, take, cache, site) {
        var searchFilter = {
            CategoryId: categoyId,
            Skip: skip,
            Take: take,
            Cache: cache,
            Site: site
        };
        return searchFilter;
    }
};;
var globalSearch = {
    init: function () {
        globalSearch.paging.pagingCount = $("#search-form").data("pagingcount");
        globalSearch.paging.pagingPage = $("#search-form").data("pagingpage");
        globalSearch.paging.pagingQueryStringName = $("#search-form").data("pagingquerystringname");
        //this.spellCheck(); //not used at the moment
        this.attachEvents();
        this.autoComplete("#search");
        var queryStringHandler = new QueryStringHandler();

        var sortorder = queryStringHandler.getParameterByName("sortorder");
        if (sortorder != null && sortorder.length > 0) {
            var $sortorderelement = $(".sort-order[data-order='" + sortorder + "']");
            $(".sort-order").removeClass("active");
            $(".sort-order").find(".radio").removeClass("active");
            $sortorderelement.addClass("active");
            $sortorderelement.find(".radio").addClass("active");
        }

        var sitefilter = queryStringHandler.getParameterByName("site");
        if (sitefilter != null && sitefilter.length > 0) {
            var $sitefilterelement = $(".site-filter[data-site='" + sitefilter + "']");
            $sitefilterelement.addClass('site-filter--active');
        }
    },
    ongoingSearch: false,
    attachEvents: function () {
        $(".load-more").on("click", function (e) {
            e.preventDefault();
            if (globalSearch.ongoingSearch === true) {
                return;
            }
            globalSearch.ongoingSearch = true;
            globalSearch.search(globalSearch.paging.pagingCount * globalSearch.paging.pagingPage, function () {
                helpers.scrollToSelector(".paging-position", 0);
                globalSearch.paging.pagingPage++;
                var urlParameters = globalSearch.getUrlParameters();
                //try catch because old IE browsers does not support history.pushState and the script fails
                try {
                    window.history.pushState("", "page " + globalSearch.paging.pagingPage, urlParameters);
                } catch (err) {
                    //Don't need to handle this error
                }
                globalSearch.ongoingSearch = false;
            });
        });
        $(".sort-order").on("click", function () {
            $(".sort-order").find(".radio").removeClass("active");
            $(this).find(".radio").addClass("active");
            var clickedSortOrder = $(this);
            if (clickedSortOrder.hasClass("active")) {
                return;
            }
            clickedSortOrder.addClass("active");
            $(".sort-order").not(clickedSortOrder).removeClass("active");
            globalSearch.updateUrl();
            globalSearch.search(0);
        });

        $('.site-filter a').on("click", function () {
            var clickedSiteFilterLink = $(this);
            if (clickedSiteFilterLink.parent().hasClass('site-filter--active')) {
                return;
            }
            clickedSiteFilterLink.parent().addClass('site-filter--active');
            $(".site-filter").not(clickedSiteFilterLink.parent()).removeClass('site-filter--active');
            globalSearch.updateUrl();
            globalSearch.search(0);
        });
    },
    updateUrl: function () {
        var urlParameters = globalSearch.getUrlParameters();
        try {
            window.history.pushState("", "page search", urlParameters);
        } catch (err) {
            //Don't need to handle this error
        }
    },
    getUrlParameters: function () {
        var urlParameters = [];
        var queryParameterValue = $("#search").val();
        if (queryParameterValue) {
            urlParameters.push("searchQuery=" + queryParameterValue);
        }
        if (globalSearch.paging.pagingPage > 1) {
            urlParameters.push(globalSearch.paging.pagingQueryStringName + "=" + globalSearch.paging.pagingPage);
        }
        var selectedSortOrder = globalSearch.getSelectedSortOrder();
        if (selectedSortOrder) {
            urlParameters.push("sortOrder=" + selectedSortOrder);
        }
        var selectedSiteOrder = globalSearch.getSelectedSite();
        if (selectedSortOrder) {
            urlParameters.push("site=" + selectedSiteOrder);
        }
        var url = window.location.search;
        var indexOfUrlQuery = url.indexOf("?");
        var hasUrlParameters = indexOfUrlQuery !== -1;
        if (hasUrlParameters === true) {
            url = url.substring(0, indexOfUrlQuery);
        }
        if (urlParameters.length > 0) {
            url += "?";
            urlParameters.forEach(function (item, index) {
                if (index === 0) {
                    url += item;
                } else {
                    url += "&" + item;
                }
            });
        }
        return url;
    },
    getSelectedSortOrder: function () {
        var sortOrder = $.trim($("#search-sort-orders ul li.active").data("order"));
        return sortOrder;
    },
    getSelectedSite: function () {
        var siteFilter = $.trim($("#site-filters li.site-filter--active").data("site"));
        return siteFilter;
    },
    search: function (skip, extraCallback) {
        //build sectionFilterArray from active facets
        var sectionFilterArray = [];

        //create searchFilter object
        var searchFilter = clientSearchHelper.createGlobalSearchFilter(
            $("#search").val(),
            sectionFilterArray,
            skip,
            globalSearch.paging.pagingCount,
            false,
            $.trim($("#search-sort-orders ul li.active").data("order")),
            $.trim($("#search-form").data("lang")),
            $.trim($("#site-filters li.site-filter--active").data("site"))
        );

        //perform ajax search and present result in callBack
        ajaxHandler.search(ajaxHandler.apiUrl.global, searchFilter, true, function (data) {
            //update total matching
            $("#no-of-search-results .total-matching").text(data.TotalMatching);
            var localizedsite = $.trim($("#site-filters li.site-filter--active").data("localizedsite"));
            $('.on-site').text(localizedsite);

            var resultContainer = $("#search-results .result-list");
            //clear hits and reset paging if a new search (not paging) is performed (skip = 0)
            if (skip === 0) {
                resultContainer.empty();
                globalSearch.paging.pagingPage = 1;
            }
            //get underscore template and populate hits
            var template = _.template($("#global-search-result-template").html());
            resultContainer.append(template({ searchHits: data.Results }));

            //show/hide load more button depending on if total match count is more or less than skip + paging count
            if (data.TotalMatching > skip + globalSearch.paging.pagingCount) {
                $(".load-more").show();
            } else {
                $(".load-more").hide();
            }
        },
		extraCallback
		);
    },
    autoComplete: function (selector) {       
        $(selector).autocomplete({
            source: function (request, response) {
                $.ajax(
                    {
                        url: '/find/rest/autocomplete/get/' + request.term + '?size=5',
                        success: function (data) {
                            $.each(data.Hits, function (index, value) {
                                response($.map(data.Hits, function (item) {
                                    return {
                                        label: item.Query,
                                        value: item.Query
                                    };
                                }));

                            })
                        }
                    })
            },
            minLength: 2
        }).keydown(function (e) {
            if (e.keyCode === 13) {
                $(this).closest('form').trigger('submit');
            }
        });
    },
    spellCheck: function () {
        //not used at the moment but code left for future use
        var searchTerm = $("#search").val();
        if (searchTerm == "") {
            return;
        }
       
        $.get('/en/find/rest/spellcheck/get/' + searchTerm + '?size=3')
            .done(function (data) {
                var template = _.template($("#spellcheck-template").html());
                $("#spellcheck").html(template({ spellChecks: data.Hits }));
            });
    },
    paging: {
        pagingPage: 1,
        pagingCount: 10
    }
};

//////////////////Todo: bryta ut?
function QueryStringHandler() {
    var self = this;

    customEventHandler.subscribe("update-querystring", function (queryStringToUpdate) {
        var updatedUrl = queryStringToUpdate.value != '' ?
			self.getUrlWithUpdatedQueryString(queryStringToUpdate.key, queryStringToUpdate.value)
			: self.getUrlWithUpdatedQueryString(queryStringToUpdate.key);
        self.pushState(queryStringToUpdate.key, updatedUrl);
    });
};

QueryStringHandler.prototype.pushState = function (title, url) {
    //try catch because old IE browsers does not support history.pushState and the script fails
    try {
        window.history.pushState("", title, url);
    } catch (err) {
        //Don't need to handle this error
    }
};

QueryStringHandler.prototype.getUrlWithUpdatedQueryString = function (key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
		hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null)
                url += '#' + hash[1];
            return url;
        }
    } else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null)
                url += '#' + hash[1];
            return url;
        } else
            return url;
    }
};

QueryStringHandler.prototype.getParameterByName = function (name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
		results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


var tagSearch = {
    init: function () {
        tagSearch.paging.pagingCount = $("#tag-page").data("pagingcount");
        tagSearch.paging.pagingPage = $("#tag-page").data("pagingpage");
        tagSearch.paging.pagingCount = $("#tag-page").data("pagingcount");
        tagSearch.paging.pagingQueryStringName = $("#tag-page").data("pagingquerystringname");
        tagSearch.categoryId = $("#tag-page").data("categoryid");
        this.attachEvents();
        var queryStringHandler = new QueryStringHandler();
    },
    ongoingSearch: false,
    attachEvents: function () {
        $(".load-more").on("click", function (e) {
            e.preventDefault();
            if (tagSearch.ongoingSearch === true) {
                return;
            }
            tagSearch.ongoingSearch = true;
            tagSearch.search(tagSearch.paging.pagingCount * tagSearch.paging.pagingPage, function () {
                helpers.scrollToSelector(".paging-position", 0);
                tagSearch.paging.pagingPage++;
                var urlParameters = tagSearch.getUrlParameters();
                //try catch because old IE browsers does not support history.pushState and the script fails
                try {
                    window.history.pushState("", "page " + tagSearch.paging.pagingPage, urlParameters);
                } catch (err) {
                    //Don't need to handle this error
                }
                tagSearch.ongoingSearch = false;

                clickableDivHandler.initTagPuffs();
            });
        });
    },
    updateUrl: function () {
        var urlParameters = tagSearch.getUrlParameters();
        try {
            window.history.pushState("", "tag search", urlParameters);
        } catch (err) {
            //Don't need to handle this error
        }
    },
    getUrlParameters: function () {
        var urlParameters = [];
        urlParameters.push("catId=" + tagSearch.categoryId);
        if (tagSearch.paging.pagingPage > 1) {
            urlParameters.push(tagSearch.paging.pagingQueryStringName + "=" + tagSearch.paging.pagingPage);
        }

        var url = window.location.search;
        var indexOfUrlQuery = url.indexOf("?");
        var hasUrlParameters = indexOfUrlQuery !== -1;
        if (hasUrlParameters === true) {
            url = url.substring(0, indexOfUrlQuery);
        }
        if (urlParameters.length > 0) {
            url += "?";
            urlParameters.forEach(function (item, index) {
                if (index === 0) {
                    url += item;
                } else {
                    url += "&" + item;
                }
            });
        }
        return url;
    },
    search: function (skip, extraCallback) {
        //build sectionFilterArray from active facets
        var sectionFilterArray = [];
        var searchFilter = clientSearchHelper.createTagSearchFilter(
            tagSearch.categoryId,
            skip,
            tagSearch.paging.pagingCount,
            false,
            $.trim($("#tagLoadButton").data("site"))
            );
        //perform ajax search and present result in callBack
        ajaxHandler.search(ajaxHandler.apiUrl.tag, searchFilter, true, function (data) {

            var resultContainer = $(".tag-result");
            //clear hits and reset paging if a new search (not paging) is performed (skip = 0)
            if (skip === 0) {
                resultContainer.empty();
                tagSearch.paging.pagingPage = 1;
            }
            //get underscore template and populate hits
            var template = _.template($("#tag-search-result-template").html());
            resultContainer.append(template( { searchHits: data.TagResults }));

            //show/hide load more button depending on if total match count is more or less than skip + paging count
            if (data.TotalMatching > skip + tagSearch.paging.pagingCount) {
                $(".load-more").show();
            } else {
                $(".load-more").hide();
            }
        },
		extraCallback
		);
    },
    paging: {
        pagingPage: 1,
        pagingCount: 12
    }
};
;
var courseSearchHelper = {
    createCourseSearchFilter: function (searchQuery, skip, take, courseFilters, isResearchSearch, language, sortOrder) {
        var searchFilter = {
            SearchQuery: searchQuery,
            IsResearchSearch: isResearchSearch,
            Skip: skip,
            Take: take,
            CourseFilters: courseFilters,
            Language: language,
            sortOrder: sortOrder
        };
        
        return searchFilter;
    }
};;
var $tabs = $('.js-course-search-tab');

var courseSearch = {
    selectedFilters: [],
    sortBy: '',
    init: function () {
        this.attachEvents();
        courseSearch.updateNoOfSelectedFilters();
        courseSearch.setSortOrder();
    },
    attachEvents: function () {
        $(".course-search-header__search, .js-search").on('submit', function (e) {
            e.preventDefault();
            courseSearch.search();
        });

        $('.js-search-filter-toggler').on("click", function (e) {
            e.preventDefault();
            courseSearch.toggleFilter();
        });

        $('.js-course-search-filter').on('change', function (e) {
            e.preventDefault();
            courseSearch.filterChanged($(this));
        });

        $tabs.on("click", function (e) {
            e.preventDefault();
            courseSearch.toggleTab($(this));
        });

        $('input[name="course-search-sorting"]').on('change', function (e) {
            e.preventDefault();
            courseSearch.setSortOrder();
        });

        $('.js-clear').on("click", function (e) {
            e.preventDefault();
            $('.course-search-filter-area__body').trigger('reset');
            courseSearch.clearFilters();
            courseSearch.setSortBy();
            courseSearch.updateUrl();
            courseSearch.updateNoOfSelectedFilters();
        })
    },
    clearFilters: function () {
        var $searchFilters = $('.js-course-search-filter');
        $searchFilters.each(function () {
            $(this).val("-1").removeClass('course-search-filter-block__select--selected');
        });
    },
    setSortBy: function () {
        $('input:radio[name=course-search-sorting]').filter('[value=startdate]').prop('checked', true);
        courseSearch.setSortOrder();
    },

    getSelectedFilters: function () {
        var selectedFilters = [];
        $('.course-search-filter-block__select--selected').each(function () {
            selectedFilters.push({ id: $(this).attr('id'), value: $(this).val() });
        });
        courseSearch.selectedFilters = selectedFilters;
    },
    search: function () {
        courseSearch.getSelectedFilters();
        var isResearchSearch = $('#CurrentPage_IsResearchSearch').val(),
            resultContainerNonScheduled = $("#search-results-non-scheduled"),
            numberOfScheduledCourses = 0,
            numberOfNonScheduledCourses = 0;

        //create searchFilter object
        var searchFilter = courseSearchHelper.createCourseSearchFilter(
            $("#search").val(),
            skip = 0,
            1,
            courseSearch.selectedFilters,
            isResearchSearch,
            $('html').attr('lang'),
            courseSearch.sortBy
        );        
        //perform ajax search and present result in callBack
        ajaxHandler.search(ajaxHandler.apiUrl.occasions, searchFilter, false,
            function (data) {

                var resultContainerScheduled = $("#search-results-scheduled"),
                    numberOfScheduledCoursesContainer = $("#scheduled"),
                    numberOfNonScheduledCoursesContainer = $("#nonscheduled");

                resultContainerScheduled.empty();
                resultContainerNonScheduled.empty();

                if (data.ResearchHits.length > 0) {
                    numberOfScheduledCourses = courseSearch.getSearchResult(data.ResearchHits, resultContainerScheduled, numberOfScheduledCoursesContainer, skip);
                }
                else {
                    numberOfScheduledCoursesContainer.text("0");
                }

                if (data.NonResearchHits.length > 0) {    
                    numberOfNonScheduledCourses = courseSearch.getSearchResult(data.NonResearchHits, resultContainerNonScheduled, numberOfNonScheduledCoursesContainer, skip);
                }
                else {
                    numberOfNonScheduledCoursesContainer.text("0");
                }

                if (data.ResearchHits.length > 0 || data.NonResearchHits.length > 0) {
                    $tabs.removeClass('hidden');
                }
                else {
                    $tabs.addClass('hidden');
                }
                $('.course-search-header__hits-info').removeClass('hidden');
                $("#active-search-no-hits").text(numberOfScheduledCourses + numberOfNonScheduledCourses);
            },
            function () {                
            });

        courseSearch.updateUrl();
        if ($('.course-search-filter-area__header').hasClass('course-search-filter-area__header--open')) {
            courseSearch.toggleFilter();
        }
        $('html, body').animate({
            scrollTop: $('.course-search-header').offset().top
        }, 200);
        $("#active-search-query").text($("#search").val());
    },

    getSearchResult: function (data, resultContainer, numberOfSearchresultsContainer, skip) {
        //clear hits and reset paging if a new search (not paging) is performed (skip = 0)
        if (skip === 0) {
            resultContainer.empty();
        }
        //get underscore template and populate hits
        var template = _.template($("#course-search-result-template").html());
        resultContainer.append(template({ searchHits: data }));
        numberOfSearchresultsContainer.text(data.length);
        return data.length ? data.length : 0;
    },
    updateUrl: function () {
        var urlParameters = courseSearch.getUrlParameters();
        try {
            window.history.pushState("", "page search", urlParameters);
        } catch (err) {
            //Don't need to handle this error
        }
    },

    getUrlParameters: function () {
        var urlParameters = [];

        var queryParameterValue = $("#search").val();
        if (queryParameterValue) {
            urlParameters.push("SearchQuery=" + encodeURIComponent(queryParameterValue));
        }
        courseSearch.selectedFilters.forEach(function (filter, index) {
            urlParameters.push(filter.id + "=" + filter.value)
        });
        if (courseSearch.sortBy) {
            urlParameters.push("SortBy=" + courseSearch.sortBy);
        }
        var url = window.location.search;
        var indexOfUrlQuery = url.indexOf("?");
        var hasUrlParameters = indexOfUrlQuery !== -1;
        if (hasUrlParameters === true) {
            url = url.substring(0, indexOfUrlQuery);
        }
        if (urlParameters.length > 0) {
            url += "?";
            urlParameters.forEach(function (item, index) {
                if (index === 0) {
                    url += item;
                } else {
                    url += "&" + item;
                }
            });
        }
        return url;
    },

    toggleFilter: function () {
        var $courseSearchFilterBody = $('.course-search-filter-area__body'),
            $courseSearchFilterHead = $('.course-search-filter-area__header');
        const COURSE_SEARCH_FILTER_HEAD_OPEN = 'course-search-filter-area__header--open';

        if ($courseSearchFilterHead.hasClass(COURSE_SEARCH_FILTER_HEAD_OPEN)) {
            $courseSearchFilterHead.attr('aria-expanded', 'false');
        }
        else {
            $courseSearchFilterHead.attr('aria-expanded', 'true');
        }
        $courseSearchFilterHead.toggleClass(COURSE_SEARCH_FILTER_HEAD_OPEN);
        $courseSearchFilterBody.slideToggle();
    },
    filterChanged: function ($filterElement) {
        if ($filterElement.val() !== '-1') {
            $filterElement.addClass('course-search-filter-block__select--selected');
        }
        else {
            $filterElement.removeClass('course-search-filter-block__select--selected');
        }

        courseSearch.updateNoOfSelectedFilters();
        courseSearch.getSelectedFilters();
    },
    updateNoOfSelectedFilters: function () {
        const HIDDEN_CLASS = 'hidden';
        var $selectedFilters = $('.course-search-filter-block__select--selected'),
            $noOfSelectedFilterText = $('.js-filter');

        if ($selectedFilters.length !== 0) {
            $noOfSelectedFilterText.text($selectedFilters.length);
            $('.js-hide-selected').removeClass(HIDDEN_CLASS);
        }
        else {
            $noOfSelectedFilterText.text('');
            $('.js-hide-selected').addClass(HIDDEN_CLASS);
        }
    },
    toggleTab: function ($clickedTab) {
        const OPEN_TAB_CLASS_DESKTOP = 'course-search-tab-area__single-tab--open',
            OPEN_TAB_CLASS_MOBILE = 'course-search-tab-area__single-tab--open-xs',
            HIDDEN_RESULT_CLASS_DESKTOP = 'course-search-result--hidden',
            HIDDEN_RESULT_CLASS_MOBILE = 'course-search-result--hidden-xs';

        var clickedTarget = $('a', $clickedTab).data('target'),
            $courseSearchResults = $('.course-search-result'),
            $courseResultListToShow = $("#" + clickedTarget),
            $tabs = $('.course-search-tab-area__single-tab');

        if (window.innerWidth < 480) {
            if ($clickedTab.hasClass(OPEN_TAB_CLASS_MOBILE)) {
                $clickedTab.toggleClass(OPEN_TAB_CLASS_MOBILE);
                $courseResultListToShow.toggleClass(HIDDEN_RESULT_CLASS_MOBILE);
            }
            else {
                $tabs.removeClass(OPEN_TAB_CLASS_MOBILE);
                $clickedTab.addClass(OPEN_TAB_CLASS_MOBILE);
                $courseSearchResults.addClass(HIDDEN_RESULT_CLASS_MOBILE);
                $courseResultListToShow.removeClass(HIDDEN_RESULT_CLASS_MOBILE);
            }
        }
        else {
            if (!$clickedTab.hasClass(OPEN_TAB_CLASS_DESKTOP)) {
                $tabs.removeClass(OPEN_TAB_CLASS_DESKTOP);
                $clickedTab.addClass(OPEN_TAB_CLASS_DESKTOP);
                $courseSearchResults.addClass(HIDDEN_RESULT_CLASS_DESKTOP);
                $courseResultListToShow.removeClass(HIDDEN_RESULT_CLASS_DESKTOP);
            }
        }
    },
    setSortOrder: function () {
        var $checked = $('input[name="course-search-sorting"]:checked');
        $('.js-sort').text($checked.next('label').text().trim());
        courseSearch.sortBy = $checked.val();
        $('.js-hide-sort').removeClass("hidden");
    }
};
var rssHandler = {

    populateRssDataItem: function (currentContentId, language) {
        var emptyTmpl = $("#rss-reader-template").html();

        var container = elementFactory.getRssContainer();
        ajaxHandler.getRssReaderDataItems(currentContentId, elementFactory.getBodyTag().data("gck"), language, function (data) {
            container.empty();
            var tmpl = _.template(emptyTmpl);
            var filledTmpl = tmpl({ rssItems: data });
            container.append(filledTmpl);
        });
    }
};
var accordionHandler = {
    init: function () {
        $('.accordion-item__heading-text').replaceWith(function () {
            var btnAttrs = {};
            $.each(this.attributes, function (i, attr) {
                btnAttrs[attr.nodeName] = attr.nodeValue;
            });
            btnAttrs['aria-expanded'] = $(this).parents('.accordion-item--active').length ? 'true' : 'false';
            return $('<button />', btnAttrs)
                .append($(this).contents(), $('<span />', { 'aria-hidden': 'true' })
                    .addClass('accordion-item__toggle-icon fal fa-' + ($(this).parents('.accordion-item--active').length ? 'chevron-up' : 'chevron-down'))
                )
                .toggleClass('accordion-item__heading-text accordion-item__heading-button');
        });
        $('.accordion-item__content').each(function () {
            if (!$(this).parents('.accordion-item--active').length) {
                $(this).hide();
            }
        });
        $('.accordion-item').on('click', '.accordion-item__heading-button', function (e) {
            e.preventDefault();
            accordionHandler.toggleAccordionSection($(this));
        });
    },
    toggleAccordionSection: function ($controlObj) {
        $controlObj.closest('.accordion-item').children('.accordion-item__content').toggle();
        $controlObj.attr('aria-expanded', function () {
            return $(this).attr('aria-expanded') !== 'true';
        });
        $controlObj.closest('.accordion-item').toggleClass('accordion-item--active');
        $controlObj.children('.accordion-item__toggle-icon').toggleClass('fa-chevron-up fa-chevron-down');
    }
};
;
var main = {
    init: function () {
        global.init();
        megamenuHandler.init();
        startBlockDropDownHandler.init();
        clickableDivHandler.initButtonPuffBlocks();
        SmartphoneMenuHandler.init();

        if (helpers.isAuthenticated()) {
            contactHandler.init();
        }

        if (!helpers.isInEditMode()) {
            accordionHandler.init();
            tabsHandler.init();
        }
    }
}
;
/*!
 *  @preserve
 * 
 * Readmore.js plugin
 * Author: @jed_foster
 * Project home: jedfoster.com/Readmore.js
 * Version: 3.0.0-beta-1
 * Licensed under the MIT license
 * 
 * Debounce function from davidwalsh.name/javascript-debounce-function
 */
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("Readmore", [], factory);
	else if(typeof exports === 'object')
		exports["Readmore"] = factory();
	else
		root["Readmore"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ({

/***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js":
/*!***************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
  \***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

module.exports = _classCallCheck;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/createClass.js":
/*!************************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
  \************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

module.exports = _createClass;

/***/ }),

/***/ "./node_modules/@babel/runtime/helpers/typeof.js":
/*!*******************************************************!*\
  !*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }

function _typeof(obj) {
  if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
    module.exports = _typeof = function _typeof(obj) {
      return _typeof2(obj);
    };
  } else {
    module.exports = _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
    };
  }

  return _typeof(obj);
}

module.exports = _typeof;

/***/ }),

/***/ "./src/readmore.js":
/*!*************************!*\
  !*** ./src/readmore.js ***!
  \*************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__);



var uniqueIdCounter = 0;
var isCssEmbeddedFor = []; // from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md

(function removePolyfill(arr) {
  arr.forEach(function (item) {
    if (Object.prototype.hasOwnProperty.call(item, 'remove')) {
      return;
    }

    Object.defineProperty(item, 'remove', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function remove() {
        if (this.parentNode !== null) {
          this.parentNode.removeChild(this);
        }
      }
    });
  });
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);

function forEach(arr, callback, scope) {
  for (var i = 0; i < arr.length; i += 1) {
    callback.call(scope, arr[i], i);
  }
}

function extend() {
  for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
    objects[_key] = arguments[_key];
  }

  var hasProp = {}.hasOwnProperty;
  var child = objects[0];
  var parent = objects[1];

  if (objects.length > 2) {
    var args = [];
    Object.keys(objects).forEach(function (key) {
      args.push(objects[key]);
    });

    while (args.length > 2) {
      var c1 = args.shift();
      var p1 = args.shift();
      args.unshift(extend(c1, p1));
    }

    child = args.shift();
    parent = args.shift();
  }

  if (parent) {
    Object.keys(parent).forEach(function (key) {
      if (hasProp.call(parent, key)) {
        if (_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2___default()(parent[key]) === 'object') {
          child[key] = child[key] || {};
          child[key] = extend(child[key], parent[key]);
        } else {
          child[key] = parent[key];
        }
      }
    });
  }

  return child;
}

function debounce(func, wait, immediate) {
  var timeout;
  return function debouncedFunc() {
    var _this = this;

    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    var callNow = immediate && !timeout;

    var later = function later() {
      timeout = null;
      if (!immediate) func.apply(_this, args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(this, args);
  };
}

function uniqueId() {
  uniqueIdCounter += 1;
  return "rmjs-".concat(uniqueIdCounter);
}

function setBoxHeights(element) {
  element.style.height = 'auto';
  var expandedHeight = parseInt(element.getBoundingClientRect().height, 10);
  var cssMaxHeight = parseInt(window.getComputedStyle(element).maxHeight, 10);
  var defaultHeight = parseInt(element.readmore.defaultHeight, 10); // Store our measurements.

  element.readmore.expandedHeight = expandedHeight;
  element.readmore.maxHeight = cssMaxHeight;
  element.readmore.collapsedHeight = cssMaxHeight || element.readmore.collapsedHeight || defaultHeight;
  element.style.maxHeight = 'none';
}

function createElementFromString(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString;
  return div.firstChild;
}

function embedCSS(selector, options) {
  if (!isCssEmbeddedFor[selector]) {
    var styles = '';

    if (options.embedCSS && options.blockCSS !== '') {
      styles += "".concat(selector, " + [data-readmore-toggle], ").concat(selector, "[data-readmore] {\n        ").concat(options.blockCSS, "\n      }");
    } // Include the transition CSS even if embedCSS is false


    styles += "".concat(selector, "[data-readmore] {\n      transition: height ").concat(options.speed, "ms;\n      overflow: hidden;\n    }");

    (function (d, u) {
      var css = d.createElement('style');
      css.type = 'text/css';

      if (css.styleSheet) {
        css.styleSheet.cssText = u;
      } else {
        css.appendChild(d.createTextNode(u));
      }

      d.getElementsByTagName('head')[0].appendChild(css);
    })(document, styles);

    isCssEmbeddedFor[selector] = true;
  }
}

function buildToggle(link, element, scope) {
  function clickHandler(event) {
    this.toggle(element, event);
  }

  var text = link;

  if (typeof link === 'function') {
    text = link(element);
  }

  var toggleLink = createElementFromString(text);
  toggleLink.setAttribute('data-readmore-toggle', element.id);
  toggleLink.setAttribute('aria-controls', element.id);
  toggleLink.addEventListener('click', clickHandler.bind(scope));
  return toggleLink;
}

function isEnvironmentSupported() {
  return typeof window !== 'undefined' && typeof document !== 'undefined' && !!document.querySelectorAll && !!window.addEventListener;
}

var resizeBoxes = debounce(function () {
  var elements = document.querySelectorAll('[data-readmore]');
  forEach(elements, function (element) {
    var expanded = element.getAttribute('aria-expanded') === 'true';
    setBoxHeights(element);
    element.style.height = "".concat(expanded ? element.readmore.expandedHeight : element.readmore.collapsedHeight, "px");
  });
}, 100);
var defaults = {
  speed: 100,
  collapsedHeight: 200,
  heightMargin: 16,
  moreLink: '<a href="#">Read More</a>',
  lessLink: '<a href="#">Close</a>',
  embedCSS: true,
  blockCSS: 'display: block; width: 100%;',
  startOpen: false,
  sourceOrder: 'after',
  // callbacks
  blockProcessed: function blockProcessed() {},
  beforeToggle: function beforeToggle() {},
  afterToggle: function afterToggle() {}
};

var Readmore =
/*#__PURE__*/
function () {
  function Readmore() {
    var _this2 = this;

    _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Readmore);

    if (!isEnvironmentSupported()) return;

    for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      args[_key3] = arguments[_key3];
    }

    var selector = args[0],
        options = args[1];
    var elements;

    if (typeof selector === 'string') {
      elements = document.querySelectorAll(selector);
    } else if (selector.nodeName) {
      elements = [selector]; // emulate a NodeList by casting a single Node as an array
    } else {
      elements = selector;
    } // After all that, if we _still_ don't have iteratable NodeList, bail out.


    if (!elements.length) return;
    this.options = extend({}, defaults, options);

    if (typeof selector === 'string') {
      embedCSS(selector, this.options);
    } else {
      // Instances need distinct selectors so they don't stomp on each other.
      this.instanceSelector = ".".concat(uniqueId());
      embedCSS(this.instanceSelector, this.options);
    } // Need to resize boxes when the page has fully loaded.


    window.addEventListener('load', resizeBoxes);
    window.addEventListener('resize', resizeBoxes);
    this.elements = [];
    forEach(elements, function (element) {
      if (_this2.instanceSelector) {
        element.classList.add(_this2.instanceSelector.substr(1));
      }

      var expanded = _this2.options.startOpen;
      element.readmore = {
        defaultHeight: _this2.options.collapsedHeight,
        heightMargin: _this2.options.heightMargin
      };
      setBoxHeights(element);
      var heightMargin = element.readmore.heightMargin;

      if (element.getBoundingClientRect().height <= element.readmore.collapsedHeight + heightMargin) {
        if (typeof _this2.options.blockProcessed === 'function') {
          _this2.options.blockProcessed(element, false);
        }

        return;
      }

      element.setAttribute('data-readmore', '');
      element.setAttribute('aria-expanded', expanded);
      element.id = element.id || uniqueId();
      var toggleLink = expanded ? _this2.options.lessLink : _this2.options.moreLink;
      var toggleElement = buildToggle(toggleLink, element, _this2);
      element.parentNode.insertBefore(toggleElement, _this2.options.sourceOrder === 'before' ? element : element.nextSibling);
      element.style.height = "".concat(expanded ? element.readmore.expandedHeight : element.readmore.collapsedHeight, "px");

      if (typeof _this2.options.blockProcessed === 'function') {
        _this2.options.blockProcessed(element, true);
      }

      _this2.elements.push(element);
    });
  } // Signature when called internally by the toggleLink click handler:
  //   toggle(element, event)
  //
  // When called externally by an instance,
  // e.g. readmoreDemo.toggle(document.querySelector('article:nth-of-type(1)')):
  //   toggle(elementOrQuerySelector)


  _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Readmore, [{
    key: "toggle",
    value: function toggle() {
      var _this3 = this;

      var el = arguments.length <= 0 ? undefined : arguments[0];

      var toggleElement = function toggleElement(element) {
        var trigger = document.querySelector("[aria-controls=\"".concat(element.id, "\"]"));
        var expanded = element.getBoundingClientRect().height <= element.readmore.collapsedHeight;
        var newHeight = expanded ? element.readmore.expandedHeight : element.readmore.collapsedHeight; // Fire beforeToggle callback
        // Since we determined the new "expanded" state above we're now out of sync
        // with our true current state, so we need to flip the value of `expanded`

        if (typeof _this3.options.beforeToggle === 'function') {
          var shouldContinueToggle = _this3.options.beforeToggle(trigger, element, !expanded); // if the beforeToggle callback returns false, stop toggling


          if (shouldContinueToggle === false) {
            return;
          }
        }

        element.style.height = "".concat(newHeight, "px");

        var transitionendHandler = function transitionendHandler(transitionEvent) {
          // Fire afterToggle callback
          if (typeof _this3.options.afterToggle === 'function') {
            _this3.options.afterToggle(trigger, element, expanded);
          }

          transitionEvent.stopPropagation();
          element.setAttribute('aria-expanded', expanded);
          element.removeEventListener('transitionend', transitionendHandler, false);
        };

        element.addEventListener('transitionend', transitionendHandler, false);

        if (_this3.options.speed < 1) {
          transitionendHandler.call(_this3, {
            target: element
          });
        }

        var toggleLink = expanded ? _this3.options.lessLink : _this3.options.moreLink;

        if (!toggleLink) {
          trigger.remove();
        } else if (trigger && trigger.parentNode) {
          trigger.parentNode.replaceChild(buildToggle(toggleLink, element, _this3), trigger);
        }
      };

      if (typeof el === 'string') {
        el = document.querySelectorAll(el);
      }

      if (!el) {
        throw new Error('Element MUST be either an HTML node or querySelector string');
      }

      var event = arguments.length <= 1 ? undefined : arguments[1];

      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }

      if (_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2___default()(el) === 'object' && !el.nodeName) {
        // element is likely a NodeList
        forEach(el, toggleElement);
      } else {
        toggleElement(el);
      }
    }
  }, {
    key: "destroy",
    value: function destroy(selector) {
      var _this4 = this;

      var elements;

      if (!selector) {
        elements = this.elements; // eslint-disable-line
      } else if (typeof selector === 'string') {
        elements = document.querySelectorAll(selector);
      } else if (selector.nodeName) {
        elements = [selector]; // emulate a NodeList by casting a single Node as an array
      } else {
        elements = selector;
      }

      forEach(elements, function (element) {
        if (_this4.elements.indexOf(element) === -1) {
          return;
        }

        _this4.elements = _this4.elements.filter(function (el) {
          return el !== element;
        });

        if (_this4.instanceSelector) {
          element.classList.remove(_this4.instanceSelector.substr(1));
        }

        delete element.readmore;
        element.style.height = 'initial';
        element.style.maxHeight = 'initial';
        element.removeAttribute('data-readmore');
        element.removeAttribute('aria-expanded');
        var trigger = document.querySelector("[aria-controls=\"".concat(element.id, "\"]"));

        if (trigger) {
          trigger.remove();
        }

        if (element.id.indexOf('rmjs-') !== -1) {
          element.removeAttribute('id');
        }
      });
      delete this;
    }
  }]);

  return Readmore;
}();

Readmore.VERSION = "3.0.0-beta-1";
/* harmony default export */ __webpack_exports__["default"] = (Readmore);

/***/ }),

/***/ 0:
/*!*******************************!*\
  !*** multi ./src/readmore.js ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(/*! ./src/readmore.js */"./src/readmore.js");


/***/ })

/******/ })["default"];
});
//# sourceMappingURL=readmore.js.map;

var isPrinting = false;
(function () {
    var beforePrint = function () {
        //console.log('Functionality to run before printing.');
        isPrinting = true;
        updateTables();
    };
    var afterPrint = function () {
        //console.log('Functionality to run after printing');
        isPrinting = false;
        updateTables();
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function (mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

var switched = [];
var widths = [];
var elements = [];
$(document).ready(function ()
{
    // GET WIDTHS OF TABLES WHEN PAGE LOADS
    $(".content-area table:not(#id_matrix)").each(function (i, element) {
        widths[i] = $(element).width();
        elements[i] = $(element);
    });
});
    
var updateTables = function ()
{
    $(elements).each(function (i, element) {

        if (($(element).parents("div").width() < widths[i]) || $(window).width() <= 1024) // IF TABLE IS WIDER THAN ITS CONTAINING PARENT, MAKE IT RESPONSIVE
        {
            if ($("tbody th", this).length > 0) // IF IT'S A TABLE WITH LEFT COLUMN HEADER, MAKE IT STICKY
            {
                if (!switched[i] && !isPrinting) {
                    //console.log("inte switched och splittar table");
                    $(this).toggleClass("responsive");
                    splitTable($(element));
                    switched[i] = true;
                }
            }
            else // IF NOT, LET'S MAKE IT A BOOTSTRAP TABLE
            {
                if (!switched[i] && !isPrinting)
                {
                    //console.log("icke switched och skriver inte ut bootstrap");
                    $(this).toggleClass("table");
                    $(this).wrap("<div class='table-responsive'>");
                    switched[i] = true;
                }
            }
        }
        else // REVERSE SWITCHED TABLES
        {
            if ($("tbody th", this).length > 0) 
            {
                if (switched[i] || isPrinting)
                {
                    //console.log("switched och skriver ut sticky");
                    $(this).toggleClass("responsive");
                    unsplitTable($(element));
                    switched[i] = false;
                }
            }
            else
            {
                if (switched[i] || isPrinting)
                {
                    //console.log("switched och skriver ut bootstrap");
                    $(this).toggleClass("table");
                    var parent = $(this).parent("div.table-responsive");
                    $(this).insertBefore($(this).parent("div.table-responsive"));
                    parent.remove();
                    switched[i] = false;
                }
            }
        }

    });
};
   
  $(window).on("load", updateTables);
  $(window).on("redraw",function(){switched=false;updateTables();}); // An event to listen for
  $(window).on("resize", updateTables);
   
	
	function splitTable(original)
	{
		original.wrap("<div class='table-wrapper' />");
		
		var copy = original.clone();
		copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
		copy.removeClass("responsive");
		
		original.closest(".table-wrapper").append(copy);
		copy.wrap("<div class='pinned' />");
		original.wrap("<div class='scrollable' />");

    //setCellHeights(original, copy);
	}
	
	function unsplitTable(original) {
    original.closest(".table-wrapper").find(".pinned").remove();
    original.unwrap();
    original.unwrap();
	}

  function setCellHeights(original, copy) {
    var tr = original.find('tr'),
        tr_copy = copy.find('tr'),
        heights = [];

    tr.each(function (index) {
      var self = $(this),
          tx = self.find('th, td');

      tx.each(function () {
        var height = $(this).outerHeight(true);
        heights[index] = heights[index] || 0;
        if (height > heights[index]) heights[index] = height;
      });

    });

    tr_copy.each(function (index) {
      $(this).height(heights[index]);
    });
  }


;
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define('underscore', factory) :
            (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (function () {
                var current = global._;
                var exports = global._ = factory();
                exports.noConflict = function () { global._ = current; return exports; };
            }()));
}(this, (function () {
    //     Underscore.js 1.13.1
    //     https://underscorejs.org
    //     (c) 2009-2021 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.

    // Current version.
    var VERSION = '1.13.1';

    // Establish the root object, `window` (`self`) in the browser, `global`
    // on the server, or `this` in some virtual machines. We use `self`
    // instead of `window` for `WebWorker` support.
    var root = typeof self == 'object' && self.self === self && self ||
        typeof global == 'object' && global.global === global && global ||
        Function('return this')() ||
        {};

    // Save bytes in the minified (but not gzipped) version:
    var ArrayProto = Array.prototype, ObjProto = Object.prototype;
    var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;

    // Create quick reference variables for speed access to core prototypes.
    var push = ArrayProto.push,
        slice = ArrayProto.slice,
        toString = ObjProto.toString,
        hasOwnProperty = ObjProto.hasOwnProperty;

    // Modern feature detection.
    var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
        supportsDataView = typeof DataView !== 'undefined';

    // All **ECMAScript 5+** native function implementations that we hope to use
    // are declared here.
    var nativeIsArray = Array.isArray,
        nativeKeys = Object.keys,
        nativeCreate = Object.create,
        nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;

    // Create references to these builtin functions because we override them.
    var _isNaN = isNaN,
        _isFinite = isFinite;

    // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
    var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
    var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
        'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

    // The largest integer that can be represented exactly.
    var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

    // Some functions take a variable number of arguments, or a few expected
    // arguments at the beginning and then a variable number of values to operate
    // on. This helper accumulates all remaining arguments past the function’s
    // argument length (or an explicit `startIndex`), into an array that becomes
    // the last argument. Similar to ES6’s "rest parameter".
    function restArguments(func, startIndex) {
        startIndex = startIndex == null ? func.length - 1 : +startIndex;
        return function () {
            var length = Math.max(arguments.length - startIndex, 0),
                rest = Array(length),
                index = 0;
            for (; index < length; index++) {
                rest[index] = arguments[index + startIndex];
            }
            switch (startIndex) {
                case 0: return func.call(this, rest);
                case 1: return func.call(this, arguments[0], rest);
                case 2: return func.call(this, arguments[0], arguments[1], rest);
            }
            var args = Array(startIndex + 1);
            for (index = 0; index < startIndex; index++) {
                args[index] = arguments[index];
            }
            args[startIndex] = rest;
            return func.apply(this, args);
        };
    }

    // Is a given variable an object?
    function isObject(obj) {
        var type = typeof obj;
        return type === 'function' || type === 'object' && !!obj;
    }

    // Is a given value equal to null?
    function isNull(obj) {
        return obj === null;
    }

    // Is a given variable undefined?
    function isUndefined(obj) {
        return obj === void 0;
    }

    // Is a given value a boolean?
    function isBoolean(obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    }

    // Is a given value a DOM element?
    function isElement(obj) {
        return !!(obj && obj.nodeType === 1);
    }

    // Internal function for creating a `toString`-based type tester.
    function tagTester(name) {
        var tag = '[object ' + name + ']';
        return function (obj) {
            return toString.call(obj) === tag;
        };
    }

    var isString = tagTester('String');

    var isNumber = tagTester('Number');

    var isDate = tagTester('Date');

    var isRegExp = tagTester('RegExp');

    var isError = tagTester('Error');

    var isSymbol = tagTester('Symbol');

    var isArrayBuffer = tagTester('ArrayBuffer');

    var isFunction = tagTester('Function');

    // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
    // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
    var nodelist = root.document && root.document.childNodes;
    if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
        isFunction = function (obj) {
            return typeof obj == 'function' || false;
        };
    }

    var isFunction$1 = isFunction;

    var hasObjectTag = tagTester('Object');

    // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
    // In IE 11, the most common among them, this problem also applies to
    // `Map`, `WeakMap` and `Set`.
    var hasStringTagBug = (
        supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
    ),
        isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));

    var isDataView = tagTester('DataView');

    // In IE 10 - Edge 13, we need a different heuristic
    // to determine whether an object is a `DataView`.
    function ie10IsDataView(obj) {
        return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
    }

    var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);

    // Is a given value an array?
    // Delegates to ECMA5's native `Array.isArray`.
    var isArray = nativeIsArray || tagTester('Array');

    // Internal function to check whether `key` is an own property name of `obj`.
    function has$1(obj, key) {
        return obj != null && hasOwnProperty.call(obj, key);
    }

    var isArguments = tagTester('Arguments');

    // Define a fallback version of the method in browsers (ahem, IE < 9), where
    // there isn't any inspectable "Arguments" type.
    (function () {
        if (!isArguments(arguments)) {
            isArguments = function (obj) {
                return has$1(obj, 'callee');
            };
        }
    }());

    var isArguments$1 = isArguments;

    // Is a given object a finite number?
    function isFinite$1(obj) {
        return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
    }

    // Is the given value `NaN`?
    function isNaN$1(obj) {
        return isNumber(obj) && _isNaN(obj);
    }

    // Predicate-generating function. Often useful outside of Underscore.
    function constant(value) {
        return function () {
            return value;
        };
    }

    // Common internal logic for `isArrayLike` and `isBufferLike`.
    function createSizePropertyCheck(getSizeProperty) {
        return function (collection) {
            var sizeProperty = getSizeProperty(collection);
            return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
        }
    }

    // Internal helper to generate a function to obtain property `key` from `obj`.
    function shallowProperty(key) {
        return function (obj) {
            return obj == null ? void 0 : obj[key];
        };
    }

    // Internal helper to obtain the `byteLength` property of an object.
    var getByteLength = shallowProperty('byteLength');

    // Internal helper to determine whether we should spend extensive checks against
    // `ArrayBuffer` et al.
    var isBufferLike = createSizePropertyCheck(getByteLength);

    // Is a given value a typed array?
    var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
    function isTypedArray(obj) {
        // `ArrayBuffer.isView` is the most future-proof, so use it when available.
        // Otherwise, fall back on the above regular expression.
        return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) :
            isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
    }

    var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);

    // Internal helper to obtain the `length` property of an object.
    var getLength = shallowProperty('length');

    // Internal helper to create a simple lookup structure.
    // `collectNonEnumProps` used to depend on `_.contains`, but this led to
    // circular imports. `emulatedSet` is a one-off solution that only works for
    // arrays of strings.
    function emulatedSet(keys) {
        var hash = {};
        for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
        return {
            contains: function (key) { return hash[key]; },
            push: function (key) {
                hash[key] = true;
                return keys.push(key);
            }
        };
    }

    // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
    // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
    // needed.
    function collectNonEnumProps(obj, keys) {
        keys = emulatedSet(keys);
        var nonEnumIdx = nonEnumerableProps.length;
        var constructor = obj.constructor;
        var proto = isFunction$1(constructor) && constructor.prototype || ObjProto;

        // Constructor is a special case.
        var prop = 'constructor';
        if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop);

        while (nonEnumIdx--) {
            prop = nonEnumerableProps[nonEnumIdx];
            if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
                keys.push(prop);
            }
        }
    }

    // Retrieve the names of an object's own properties.
    // Delegates to **ECMAScript 5**'s native `Object.keys`.
    function keys(obj) {
        if (!isObject(obj)) return [];
        if (nativeKeys) return nativeKeys(obj);
        var keys = [];
        for (var key in obj) if (has$1(obj, key)) keys.push(key);
        // Ahem, IE < 9.
        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    }

    // Is a given array, string, or object empty?
    // An "empty" object has no enumerable own-properties.
    function isEmpty(obj) {
        if (obj == null) return true;
        // Skip the more expensive `toString`-based type checks if `obj` has no
        // `.length`.
        var length = getLength(obj);
        if (typeof length == 'number' && (
            isArray(obj) || isString(obj) || isArguments$1(obj)
        )) return length === 0;
        return getLength(keys(obj)) === 0;
    }

    // Returns whether an object has a given set of `key:value` pairs.
    function isMatch(object, attrs) {
        var _keys = keys(attrs), length = _keys.length;
        if (object == null) return !length;
        var obj = Object(object);
        for (var i = 0; i < length; i++) {
            var key = _keys[i];
            if (attrs[key] !== obj[key] || !(key in obj)) return false;
        }
        return true;
    }

    // If Underscore is called as a function, it returns a wrapped object that can
    // be used OO-style. This wrapper holds altered versions of all functions added
    // through `_.mixin`. Wrapped objects may be chained.
    function _$1(obj) {
        if (obj instanceof _$1) return obj;
        if (!(this instanceof _$1)) return new _$1(obj);
        this._wrapped = obj;
    }

    _$1.VERSION = VERSION;

    // Extracts the result from a wrapped and chained object.
    _$1.prototype.value = function () {
        return this._wrapped;
    };

    // Provide unwrapping proxies for some methods used in engine operations
    // such as arithmetic and JSON stringification.
    _$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value;

    _$1.prototype.toString = function () {
        return String(this._wrapped);
    };

    // Internal function to wrap or shallow-copy an ArrayBuffer,
    // typed array or DataView to a new view, reusing the buffer.
    function toBufferView(bufferSource) {
        return new Uint8Array(
            bufferSource.buffer || bufferSource,
            bufferSource.byteOffset || 0,
            getByteLength(bufferSource)
        );
    }

    // We use this string twice, so give it a name for minification.
    var tagDataView = '[object DataView]';

    // Internal recursive comparison function for `_.isEqual`.
    function eq(a, b, aStack, bStack) {
        // Identical objects are equal. `0 === -0`, but they aren't identical.
        // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
        if (a === b) return a !== 0 || 1 / a === 1 / b;
        // `null` or `undefined` only equal to itself (strict comparison).
        if (a == null || b == null) return false;
        // `NaN`s are equivalent, but non-reflexive.
        if (a !== a) return b !== b;
        // Exhaust primitive checks
        var type = typeof a;
        if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
        return deepEq(a, b, aStack, bStack);
    }

    // Internal recursive comparison function for `_.isEqual`.
    function deepEq(a, b, aStack, bStack) {
        // Unwrap any wrapped objects.
        if (a instanceof _$1) a = a._wrapped;
        if (b instanceof _$1) b = b._wrapped;
        // Compare `[[Class]]` names.
        var className = toString.call(a);
        if (className !== toString.call(b)) return false;
        // Work around a bug in IE 10 - Edge 13.
        if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
            if (!isDataView$1(b)) return false;
            className = tagDataView;
        }
        switch (className) {
            // These types are compared by value.
            case '[object RegExp]':
            // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
            case '[object String]':
                // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
                // equivalent to `new String("5")`.
                return '' + a === '' + b;
            case '[object Number]':
                // `NaN`s are equivalent, but non-reflexive.
                // Object(NaN) is equivalent to NaN.
                if (+a !== +a) return +b !== +b;
                // An `egal` comparison is performed for other numeric values.
                return +a === 0 ? 1 / +a === 1 / b : +a === +b;
            case '[object Date]':
            case '[object Boolean]':
                // Coerce dates and booleans to numeric primitive values. Dates are compared by their
                // millisecond representations. Note that invalid dates with millisecond representations
                // of `NaN` are not equivalent.
                return +a === +b;
            case '[object Symbol]':
                return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
            case '[object ArrayBuffer]':
            case tagDataView:
                // Coerce to typed array so we can fall through.
                return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
        }

        var areArrays = className === '[object Array]';
        if (!areArrays && isTypedArray$1(a)) {
            var byteLength = getByteLength(a);
            if (byteLength !== getByteLength(b)) return false;
            if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
            areArrays = true;
        }
        if (!areArrays) {
            if (typeof a != 'object' || typeof b != 'object') return false;

            // Objects with different constructors are not equivalent, but `Object`s or `Array`s
            // from different frames are.
            var aCtor = a.constructor, bCtor = b.constructor;
            if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor &&
                isFunction$1(bCtor) && bCtor instanceof bCtor)
                && ('constructor' in a && 'constructor' in b)) {
                return false;
            }
        }
        // Assume equality for cyclic structures. The algorithm for detecting cyclic
        // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

        // Initializing stack of traversed objects.
        // It's done here since we only need them for objects and arrays comparison.
        aStack = aStack || [];
        bStack = bStack || [];
        var length = aStack.length;
        while (length--) {
            // Linear search. Performance is inversely proportional to the number of
            // unique nested structures.
            if (aStack[length] === a) return bStack[length] === b;
        }

        // Add the first object to the stack of traversed objects.
        aStack.push(a);
        bStack.push(b);

        // Recursively compare objects and arrays.
        if (areArrays) {
            // Compare array lengths to determine if a deep comparison is necessary.
            length = a.length;
            if (length !== b.length) return false;
            // Deep compare the contents, ignoring non-numeric properties.
            while (length--) {
                if (!eq(a[length], b[length], aStack, bStack)) return false;
            }
        } else {
            // Deep compare objects.
            var _keys = keys(a), key;
            length = _keys.length;
            // Ensure that both objects contain the same number of properties before comparing deep equality.
            if (keys(b).length !== length) return false;
            while (length--) {
                // Deep compare each member
                key = _keys[length];
                if (!(has$1(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
            }
        }
        // Remove the first object from the stack of traversed objects.
        aStack.pop();
        bStack.pop();
        return true;
    }

    // Perform a deep comparison to check if two objects are equal.
    function isEqual(a, b) {
        return eq(a, b);
    }

    // Retrieve all the enumerable property names of an object.
    function allKeys(obj) {
        if (!isObject(obj)) return [];
        var keys = [];
        for (var key in obj) keys.push(key);
        // Ahem, IE < 9.
        if (hasEnumBug) collectNonEnumProps(obj, keys);
        return keys;
    }

    // Since the regular `Object.prototype.toString` type tests don't work for
    // some types in IE 11, we use a fingerprinting heuristic instead, based
    // on the methods. It's not great, but it's the best we got.
    // The fingerprint method lists are defined below.
    function ie11fingerprint(methods) {
        var length = getLength(methods);
        return function (obj) {
            if (obj == null) return false;
            // `Map`, `WeakMap` and `Set` have no enumerable keys.
            var keys = allKeys(obj);
            if (getLength(keys)) return false;
            for (var i = 0; i < length; i++) {
                if (!isFunction$1(obj[methods[i]])) return false;
            }
            // If we are testing against `WeakMap`, we need to ensure that
            // `obj` doesn't have a `forEach` method in order to distinguish
            // it from a regular `Map`.
            return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
        };
    }

    // In the interest of compact minification, we write
    // each string in the fingerprints only once.
    var forEachName = 'forEach',
        hasName = 'has',
        commonInit = ['clear', 'delete'],
        mapTail = ['get', hasName, 'set'];

    // `Map`, `WeakMap` and `Set` each have slightly different
    // combinations of the above sublists.
    var mapMethods = commonInit.concat(forEachName, mapTail),
        weakMapMethods = commonInit.concat(mapTail),
        setMethods = ['add'].concat(commonInit, forEachName, hasName);

    var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');

    var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');

    var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');

    var isWeakSet = tagTester('WeakSet');

    // Retrieve the values of an object's properties.
    function values(obj) {
        var _keys = keys(obj);
        var length = _keys.length;
        var values = Array(length);
        for (var i = 0; i < length; i++) {
            values[i] = obj[_keys[i]];
        }
        return values;
    }

    // Convert an object into a list of `[key, value]` pairs.
    // The opposite of `_.object` with one argument.
    function pairs(obj) {
        var _keys = keys(obj);
        var length = _keys.length;
        var pairs = Array(length);
        for (var i = 0; i < length; i++) {
            pairs[i] = [_keys[i], obj[_keys[i]]];
        }
        return pairs;
    }

    // Invert the keys and values of an object. The values must be serializable.
    function invert(obj) {
        var result = {};
        var _keys = keys(obj);
        for (var i = 0, length = _keys.length; i < length; i++) {
            result[obj[_keys[i]]] = _keys[i];
        }
        return result;
    }

    // Return a sorted list of the function names available on the object.
    function functions(obj) {
        var names = [];
        for (var key in obj) {
            if (isFunction$1(obj[key])) names.push(key);
        }
        return names.sort();
    }

    // An internal function for creating assigner functions.
    function createAssigner(keysFunc, defaults) {
        return function (obj) {
            var length = arguments.length;
            if (defaults) obj = Object(obj);
            if (length < 2 || obj == null) return obj;
            for (var index = 1; index < length; index++) {
                var source = arguments[index],
                    keys = keysFunc(source),
                    l = keys.length;
                for (var i = 0; i < l; i++) {
                    var key = keys[i];
                    if (!defaults || obj[key] === void 0) obj[key] = source[key];
                }
            }
            return obj;
        };
    }

    // Extend a given object with all the properties in passed-in object(s).
    var extend = createAssigner(allKeys);

    // Assigns a given object with all the own properties in the passed-in
    // object(s).
    // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
    var extendOwn = createAssigner(keys);

    // Fill in a given object with default properties.
    var defaults = createAssigner(allKeys, true);

    // Create a naked function reference for surrogate-prototype-swapping.
    function ctor() {
        return function () { };
    }

    // An internal function for creating a new object that inherits from another.
    function baseCreate(prototype) {
        if (!isObject(prototype)) return {};
        if (nativeCreate) return nativeCreate(prototype);
        var Ctor = ctor();
        Ctor.prototype = prototype;
        var result = new Ctor;
        Ctor.prototype = null;
        return result;
    }

    // Creates an object that inherits from the given prototype object.
    // If additional properties are provided then they will be added to the
    // created object.
    function create(prototype, props) {
        var result = baseCreate(prototype);
        if (props) extendOwn(result, props);
        return result;
    }

    // Create a (shallow-cloned) duplicate of an object.
    function clone(obj) {
        if (!isObject(obj)) return obj;
        return isArray(obj) ? obj.slice() : extend({}, obj);
    }

    // Invokes `interceptor` with the `obj` and then returns `obj`.
    // The primary purpose of this method is to "tap into" a method chain, in
    // order to perform operations on intermediate results within the chain.
    function tap(obj, interceptor) {
        interceptor(obj);
        return obj;
    }

    // Normalize a (deep) property `path` to array.
    // Like `_.iteratee`, this function can be customized.
    function toPath$1(path) {
        return isArray(path) ? path : [path];
    }
    _$1.toPath = toPath$1;

    // Internal wrapper for `_.toPath` to enable minification.
    // Similar to `cb` for `_.iteratee`.
    function toPath(path) {
        return _$1.toPath(path);
    }

    // Internal function to obtain a nested property in `obj` along `path`.
    function deepGet(obj, path) {
        var length = path.length;
        for (var i = 0; i < length; i++) {
            if (obj == null) return void 0;
            obj = obj[path[i]];
        }
        return length ? obj : void 0;
    }

    // Get the value of the (deep) property on `path` from `object`.
    // If any property in `path` does not exist or if the value is
    // `undefined`, return `defaultValue` instead.
    // The `path` is normalized through `_.toPath`.
    function get(object, path, defaultValue) {
        var value = deepGet(object, toPath(path));
        return isUndefined(value) ? defaultValue : value;
    }

    // Shortcut function for checking if an object has a given property directly on
    // itself (in other words, not on a prototype). Unlike the internal `has`
    // function, this public version can also traverse nested properties.
    function has(obj, path) {
        path = toPath(path);
        var length = path.length;
        for (var i = 0; i < length; i++) {
            var key = path[i];
            if (!has$1(obj, key)) return false;
            obj = obj[key];
        }
        return !!length;
    }

    // Keep the identity function around for default iteratees.
    function identity(value) {
        return value;
    }

    // Returns a predicate for checking whether an object has a given set of
    // `key:value` pairs.
    function matcher(attrs) {
        attrs = extendOwn({}, attrs);
        return function (obj) {
            return isMatch(obj, attrs);
        };
    }

    // Creates a function that, when passed an object, will traverse that object’s
    // properties down the given `path`, specified as an array of keys or indices.
    function property(path) {
        path = toPath(path);
        return function (obj) {
            return deepGet(obj, path);
        };
    }

    // Internal function that returns an efficient (for current engines) version
    // of the passed-in callback, to be repeatedly applied in other Underscore
    // functions.
    function optimizeCb(func, context, argCount) {
        if (context === void 0) return func;
        switch (argCount == null ? 3 : argCount) {
            case 1: return function (value) {
                return func.call(context, value);
            };
            // The 2-argument case is omitted because we’re not using it.
            case 3: return function (value, index, collection) {
                return func.call(context, value, index, collection);
            };
            case 4: return function (accumulator, value, index, collection) {
                return func.call(context, accumulator, value, index, collection);
            };
        }
        return function () {
            return func.apply(context, arguments);
        };
    }

    // An internal function to generate callbacks that can be applied to each
    // element in a collection, returning the desired result — either `_.identity`,
    // an arbitrary callback, a property matcher, or a property accessor.
    function baseIteratee(value, context, argCount) {
        if (value == null) return identity;
        if (isFunction$1(value)) return optimizeCb(value, context, argCount);
        if (isObject(value) && !isArray(value)) return matcher(value);
        return property(value);
    }

    // External wrapper for our callback generator. Users may customize
    // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
    // This abstraction hides the internal-only `argCount` argument.
    function iteratee(value, context) {
        return baseIteratee(value, context, Infinity);
    }
    _$1.iteratee = iteratee;

    // The function we call internally to generate a callback. It invokes
    // `_.iteratee` if overridden, otherwise `baseIteratee`.
    function cb(value, context, argCount) {
        if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context);
        return baseIteratee(value, context, argCount);
    }

    // Returns the results of applying the `iteratee` to each element of `obj`.
    // In contrast to `_.map` it returns an object.
    function mapObject(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        var _keys = keys(obj),
            length = _keys.length,
            results = {};
        for (var index = 0; index < length; index++) {
            var currentKey = _keys[index];
            results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
    }

    // Predicate-generating function. Often useful outside of Underscore.
    function noop() { }

    // Generates a function for a given object that returns a given property.
    function propertyOf(obj) {
        if (obj == null) return noop;
        return function (path) {
            return get(obj, path);
        };
    }

    // Run a function **n** times.
    function times(n, iteratee, context) {
        var accum = Array(Math.max(0, n));
        iteratee = optimizeCb(iteratee, context, 1);
        for (var i = 0; i < n; i++) accum[i] = iteratee(i);
        return accum;
    }

    // Return a random integer between `min` and `max` (inclusive).
    function random(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }

    // A (possibly faster) way to get the current timestamp as an integer.
    var now = Date.now || function () {
        return new Date().getTime();
    };

    // Internal helper to generate functions for escaping and unescaping strings
    // to/from HTML interpolation.
    function createEscaper(map) {
        var escaper = function (match) {
            return map[match];
        };
        // Regexes for identifying a key that needs to be escaped.
        var source = '(?:' + keys(map).join('|') + ')';
        var testRegexp = RegExp(source);
        var replaceRegexp = RegExp(source, 'g');
        return function (string) {
            string = string == null ? '' : '' + string;
            return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
        };
    }

    // Internal list of HTML entities for escaping.
    var escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
    };

    // Function for escaping strings to HTML interpolation.
    var _escape = createEscaper(escapeMap);

    // Internal list of HTML entities for unescaping.
    var unescapeMap = invert(escapeMap);

    // Function for unescaping strings from HTML interpolation.
    var _unescape = createEscaper(unescapeMap);

    // By default, Underscore uses ERB-style template delimiters. Change the
    // following template settings to use alternative delimiters.
    var templateSettings = _$1.templateSettings = {
        evaluate: /<%([\s\S]+?)%>/g,
        interpolate: /<%=([\s\S]+?)%>/g,
        escape: /<%-([\s\S]+?)%>/g
    };

    // When customizing `_.templateSettings`, if you don't want to define an
    // interpolation, evaluation or escaping regex, we need one that is
    // guaranteed not to match.
    var noMatch = /(.)^/;

    // Certain characters need to be escaped so that they can be put into a
    // string literal.
    var escapes = {
        "'": "'",
        '\\': '\\',
        '\r': 'r',
        '\n': 'n',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
    };

    var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;

    function escapeChar(match) {
        return '\\' + escapes[match];
    }

    // In order to prevent third-party code injection through
    // `_.templateSettings.variable`, we test it against the following regular
    // expression. It is intentionally a bit more liberal than just matching valid
    // identifiers, but still prevents possible loopholes through defaults or
    // destructuring assignment.
    var bareIdentifier = /^\s*(\w|\$)+\s*$/;

    // JavaScript micro-templating, similar to John Resig's implementation.
    // Underscore templating handles arbitrary delimiters, preserves whitespace,
    // and correctly escapes quotes within interpolated code.
    // NB: `oldSettings` only exists for backwards compatibility.
    function template(text, settings, oldSettings) {
        if (!settings && oldSettings) settings = oldSettings;
        settings = defaults({}, settings, _$1.templateSettings);

        // Combine delimiters into one regular expression via alternation.
        var matcher = RegExp([
            (settings.escape || noMatch).source,
            (settings.interpolate || noMatch).source,
            (settings.evaluate || noMatch).source
        ].join('|') + '|$', 'g');

        // Compile the template source, escaping string literals appropriately.
        var index = 0;
        var source = "__p+='";
        text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
            source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
            index = offset + match.length;

            if (escape) {
                source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
            } else if (interpolate) {
                source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
            } else if (evaluate) {
                source += "';\n" + evaluate + "\n__p+='";
            }

            // Adobe VMs need the match returned to produce the correct offset.
            return match;
        });
        source += "';\n";

        var argument = settings.variable;
        if (argument) {
            // Insure against third-party code injection. (CVE-2021-23358)
            if (!bareIdentifier.test(argument)) throw new Error(
                'variable is not a bare identifier: ' + argument
            );
        } else {
            // If a variable is not specified, place data values in local scope.
            source = 'with(obj||{}){\n' + source + '}\n';
            argument = 'obj';
        }

        source = "var __t,__p='',__j=Array.prototype.join," +
            "print=function(){__p+=__j.call(arguments,'');};\n" +
            source + 'return __p;\n';

        var render;
        try {
            render = new Function(argument, '_', source);
        } catch (e) {
            e.source = source;
            throw e;
        }

        var template = function (data) {
            return render.call(this, data, _$1);
        };

        // Provide the compiled source as a convenience for precompilation.
        template.source = 'function(' + argument + '){\n' + source + '}';

        return template;
    }

    // Traverses the children of `obj` along `path`. If a child is a function, it
    // is invoked with its parent as context. Returns the value of the final
    // child, or `fallback` if any child is undefined.
    function result(obj, path, fallback) {
        path = toPath(path);
        var length = path.length;
        if (!length) {
            return isFunction$1(fallback) ? fallback.call(obj) : fallback;
        }
        for (var i = 0; i < length; i++) {
            var prop = obj == null ? void 0 : obj[path[i]];
            if (prop === void 0) {
                prop = fallback;
                i = length; // Ensure we don't continue iterating.
            }
            obj = isFunction$1(prop) ? prop.call(obj) : prop;
        }
        return obj;
    }

    // Generate a unique integer id (unique within the entire client session).
    // Useful for temporary DOM ids.
    var idCounter = 0;
    function uniqueId(prefix) {
        var id = ++idCounter + '';
        return prefix ? prefix + id : id;
    }

    // Start chaining a wrapped Underscore object.
    function chain(obj) {
        var instance = _$1(obj);
        instance._chain = true;
        return instance;
    }

    // Internal function to execute `sourceFunc` bound to `context` with optional
    // `args`. Determines whether to execute a function as a constructor or as a
    // normal function.
    function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
        if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
        var self = baseCreate(sourceFunc.prototype);
        var result = sourceFunc.apply(self, args);
        if (isObject(result)) return result;
        return self;
    }

    // Partially apply a function by creating a version that has had some of its
    // arguments pre-filled, without changing its dynamic `this` context. `_` acts
    // as a placeholder by default, allowing any combination of arguments to be
    // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
    var partial = restArguments(function (func, boundArgs) {
        var placeholder = partial.placeholder;
        var bound = function () {
            var position = 0, length = boundArgs.length;
            var args = Array(length);
            for (var i = 0; i < length; i++) {
                args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
            }
            while (position < arguments.length) args.push(arguments[position++]);
            return executeBound(func, bound, this, this, args);
        };
        return bound;
    });

    partial.placeholder = _$1;

    // Create a function bound to a given object (assigning `this`, and arguments,
    // optionally).
    var bind = restArguments(function (func, context, args) {
        if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
        var bound = restArguments(function (callArgs) {
            return executeBound(func, bound, context, this, args.concat(callArgs));
        });
        return bound;
    });

    // Internal helper for collection methods to determine whether a collection
    // should be iterated as an array or as an object.
    // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
    // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
    var isArrayLike = createSizePropertyCheck(getLength);

    // Internal implementation of a recursive `flatten` function.
    function flatten$1(input, depth, strict, output) {
        output = output || [];
        if (!depth && depth !== 0) {
            depth = Infinity;
        } else if (depth <= 0) {
            return output.concat(input);
        }
        var idx = output.length;
        for (var i = 0, length = getLength(input); i < length; i++) {
            var value = input[i];
            if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
                // Flatten current level of array or arguments object.
                if (depth > 1) {
                    flatten$1(value, depth - 1, strict, output);
                    idx = output.length;
                } else {
                    var j = 0, len = value.length;
                    while (j < len) output[idx++] = value[j++];
                }
            } else if (!strict) {
                output[idx++] = value;
            }
        }
        return output;
    }

    // Bind a number of an object's methods to that object. Remaining arguments
    // are the method names to be bound. Useful for ensuring that all callbacks
    // defined on an object belong to it.
    var bindAll = restArguments(function (obj, keys) {
        keys = flatten$1(keys, false, false);
        var index = keys.length;
        if (index < 1) throw new Error('bindAll must be passed function names');
        while (index--) {
            var key = keys[index];
            obj[key] = bind(obj[key], obj);
        }
        return obj;
    });

    // Memoize an expensive function by storing its results.
    function memoize(func, hasher) {
        var memoize = function (key) {
            var cache = memoize.cache;
            var address = '' + (hasher ? hasher.apply(this, arguments) : key);
            if (!has$1(cache, address)) cache[address] = func.apply(this, arguments);
            return cache[address];
        };
        memoize.cache = {};
        return memoize;
    }

    // Delays a function for the given number of milliseconds, and then calls
    // it with the arguments supplied.
    var delay = restArguments(function (func, wait, args) {
        return setTimeout(function () {
            return func.apply(null, args);
        }, wait);
    });

    // Defers a function, scheduling it to run after the current call stack has
    // cleared.
    var defer = partial(delay, _$1, 1);

    // Returns a function, that, when invoked, will only be triggered at most once
    // during a given window of time. Normally, the throttled function will run
    // as much as it can, without ever going more than once per `wait` duration;
    // but if you'd like to disable the execution on the leading edge, pass
    // `{leading: false}`. To disable execution on the trailing edge, ditto.
    function throttle(func, wait, options) {
        var timeout, context, args, result;
        var previous = 0;
        if (!options) options = {};

        var later = function () {
            previous = options.leading === false ? 0 : now();
            timeout = null;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        };

        var throttled = function () {
            var _now = now();
            if (!previous && options.leading === false) previous = _now;
            var remaining = wait - (_now - previous);
            context = this;
            args = arguments;
            if (remaining <= 0 || remaining > wait) {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                previous = _now;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            } else if (!timeout && options.trailing !== false) {
                timeout = setTimeout(later, remaining);
            }
            return result;
        };

        throttled.cancel = function () {
            clearTimeout(timeout);
            previous = 0;
            timeout = context = args = null;
        };

        return throttled;
    }

    // When a sequence of calls of the returned function ends, the argument
    // function is triggered. The end of a sequence is defined by the `wait`
    // parameter. If `immediate` is passed, the argument function will be
    // triggered at the beginning of the sequence instead of at the end.
    function debounce(func, wait, immediate) {
        var timeout, previous, args, result, context;

        var later = function () {
            var passed = now() - previous;
            if (wait > passed) {
                timeout = setTimeout(later, wait - passed);
            } else {
                timeout = null;
                if (!immediate) result = func.apply(context, args);
                // This check is needed because `func` can recursively invoke `debounced`.
                if (!timeout) args = context = null;
            }
        };

        var debounced = restArguments(function (_args) {
            context = this;
            args = _args;
            previous = now();
            if (!timeout) {
                timeout = setTimeout(later, wait);
                if (immediate) result = func.apply(context, args);
            }
            return result;
        });

        debounced.cancel = function () {
            clearTimeout(timeout);
            timeout = args = context = null;
        };

        return debounced;
    }

    // Returns the first function passed as an argument to the second,
    // allowing you to adjust arguments, run code before and after, and
    // conditionally execute the original function.
    function wrap(func, wrapper) {
        return partial(wrapper, func);
    }

    // Returns a negated version of the passed-in predicate.
    function negate(predicate) {
        return function () {
            return !predicate.apply(this, arguments);
        };
    }

    // Returns a function that is the composition of a list of functions, each
    // consuming the return value of the function that follows.
    function compose() {
        var args = arguments;
        var start = args.length - 1;
        return function () {
            var i = start;
            var result = args[start].apply(this, arguments);
            while (i--) result = args[i].call(this, result);
            return result;
        };
    }

    // Returns a function that will only be executed on and after the Nth call.
    function after(times, func) {
        return function () {
            if (--times < 1) {
                return func.apply(this, arguments);
            }
        };
    }

    // Returns a function that will only be executed up to (but not including) the
    // Nth call.
    function before(times, func) {
        var memo;
        return function () {
            if (--times > 0) {
                memo = func.apply(this, arguments);
            }
            if (times <= 1) func = null;
            return memo;
        };
    }

    // Returns a function that will be executed at most one time, no matter how
    // often you call it. Useful for lazy initialization.
    var once = partial(before, 2);

    // Returns the first key on an object that passes a truth test.
    function findKey(obj, predicate, context) {
        predicate = cb(predicate, context);
        var _keys = keys(obj), key;
        for (var i = 0, length = _keys.length; i < length; i++) {
            key = _keys[i];
            if (predicate(obj[key], key, obj)) return key;
        }
    }

    // Internal function to generate `_.findIndex` and `_.findLastIndex`.
    function createPredicateIndexFinder(dir) {
        return function (array, predicate, context) {
            predicate = cb(predicate, context);
            var length = getLength(array);
            var index = dir > 0 ? 0 : length - 1;
            for (; index >= 0 && index < length; index += dir) {
                if (predicate(array[index], index, array)) return index;
            }
            return -1;
        };
    }

    // Returns the first index on an array-like that passes a truth test.
    var findIndex = createPredicateIndexFinder(1);

    // Returns the last index on an array-like that passes a truth test.
    var findLastIndex = createPredicateIndexFinder(-1);

    // Use a comparator function to figure out the smallest index at which
    // an object should be inserted so as to maintain order. Uses binary search.
    function sortedIndex(array, obj, iteratee, context) {
        iteratee = cb(iteratee, context, 1);
        var value = iteratee(obj);
        var low = 0, high = getLength(array);
        while (low < high) {
            var mid = Math.floor((low + high) / 2);
            if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
        }
        return low;
    }

    // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
    function createIndexFinder(dir, predicateFind, sortedIndex) {
        return function (array, item, idx) {
            var i = 0, length = getLength(array);
            if (typeof idx == 'number') {
                if (dir > 0) {
                    i = idx >= 0 ? idx : Math.max(idx + length, i);
                } else {
                    length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
                }
            } else if (sortedIndex && idx && length) {
                idx = sortedIndex(array, item);
                return array[idx] === item ? idx : -1;
            }
            if (item !== item) {
                idx = predicateFind(slice.call(array, i, length), isNaN$1);
                return idx >= 0 ? idx + i : -1;
            }
            for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
                if (array[idx] === item) return idx;
            }
            return -1;
        };
    }

    // Return the position of the first occurrence of an item in an array,
    // or -1 if the item is not included in the array.
    // If the array is large and already in sort order, pass `true`
    // for **isSorted** to use binary search.
    var indexOf = createIndexFinder(1, findIndex, sortedIndex);

    // Return the position of the last occurrence of an item in an array,
    // or -1 if the item is not included in the array.
    var lastIndexOf = createIndexFinder(-1, findLastIndex);

    // Return the first value which passes a truth test.
    function find(obj, predicate, context) {
        var keyFinder = isArrayLike(obj) ? findIndex : findKey;
        var key = keyFinder(obj, predicate, context);
        if (key !== void 0 && key !== -1) return obj[key];
    }

    // Convenience version of a common use case of `_.find`: getting the first
    // object containing specific `key:value` pairs.
    function findWhere(obj, attrs) {
        return find(obj, matcher(attrs));
    }

    // The cornerstone for collection functions, an `each`
    // implementation, aka `forEach`.
    // Handles raw objects in addition to array-likes. Treats all
    // sparse array-likes as if they were dense.
    function each(obj, iteratee, context) {
        iteratee = optimizeCb(iteratee, context);
        var i, length;
        if (isArrayLike(obj)) {
            for (i = 0, length = obj.length; i < length; i++) {
                iteratee(obj[i], i, obj);
            }
        } else {
            var _keys = keys(obj);
            for (i = 0, length = _keys.length; i < length; i++) {
                iteratee(obj[_keys[i]], _keys[i], obj);
            }
        }
        return obj;
    }

    // Return the results of applying the iteratee to each element.
    function map(obj, iteratee, context) {
        iteratee = cb(iteratee, context);
        var _keys = !isArrayLike(obj) && keys(obj),
            length = (_keys || obj).length,
            results = Array(length);
        for (var index = 0; index < length; index++) {
            var currentKey = _keys ? _keys[index] : index;
            results[index] = iteratee(obj[currentKey], currentKey, obj);
        }
        return results;
    }

    // Internal helper to create a reducing function, iterating left or right.
    function createReduce(dir) {
        // Wrap code that reassigns argument variables in a separate function than
        // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
        var reducer = function (obj, iteratee, memo, initial) {
            var _keys = !isArrayLike(obj) && keys(obj),
                length = (_keys || obj).length,
                index = dir > 0 ? 0 : length - 1;
            if (!initial) {
                memo = obj[_keys ? _keys[index] : index];
                index += dir;
            }
            for (; index >= 0 && index < length; index += dir) {
                var currentKey = _keys ? _keys[index] : index;
                memo = iteratee(memo, obj[currentKey], currentKey, obj);
            }
            return memo;
        };

        return function (obj, iteratee, memo, context) {
            var initial = arguments.length >= 3;
            return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
        };
    }

    // **Reduce** builds up a single result from a list of values, aka `inject`,
    // or `foldl`.
    var reduce = createReduce(1);

    // The right-associative version of reduce, also known as `foldr`.
    var reduceRight = createReduce(-1);

    // Return all the elements that pass a truth test.
    function filter(obj, predicate, context) {
        var results = [];
        predicate = cb(predicate, context);
        each(obj, function (value, index, list) {
            if (predicate(value, index, list)) results.push(value);
        });
        return results;
    }

    // Return all the elements for which a truth test fails.
    function reject(obj, predicate, context) {
        return filter(obj, negate(cb(predicate)), context);
    }

    // Determine whether all of the elements pass a truth test.
    function every(obj, predicate, context) {
        predicate = cb(predicate, context);
        var _keys = !isArrayLike(obj) && keys(obj),
            length = (_keys || obj).length;
        for (var index = 0; index < length; index++) {
            var currentKey = _keys ? _keys[index] : index;
            if (!predicate(obj[currentKey], currentKey, obj)) return false;
        }
        return true;
    }

    // Determine if at least one element in the object passes a truth test.
    function some(obj, predicate, context) {
        predicate = cb(predicate, context);
        var _keys = !isArrayLike(obj) && keys(obj),
            length = (_keys || obj).length;
        for (var index = 0; index < length; index++) {
            var currentKey = _keys ? _keys[index] : index;
            if (predicate(obj[currentKey], currentKey, obj)) return true;
        }
        return false;
    }

    // Determine if the array or object contains a given item (using `===`).
    function contains(obj, item, fromIndex, guard) {
        if (!isArrayLike(obj)) obj = values(obj);
        if (typeof fromIndex != 'number' || guard) fromIndex = 0;
        return indexOf(obj, item, fromIndex) >= 0;
    }

    // Invoke a method (with arguments) on every item in a collection.
    var invoke = restArguments(function (obj, path, args) {
        var contextPath, func;
        if (isFunction$1(path)) {
            func = path;
        } else {
            path = toPath(path);
            contextPath = path.slice(0, -1);
            path = path[path.length - 1];
        }
        return map(obj, function (context) {
            var method = func;
            if (!method) {
                if (contextPath && contextPath.length) {
                    context = deepGet(context, contextPath);
                }
                if (context == null) return void 0;
                method = context[path];
            }
            return method == null ? method : method.apply(context, args);
        });
    });

    // Convenience version of a common use case of `_.map`: fetching a property.
    function pluck(obj, key) {
        return map(obj, property(key));
    }

    // Convenience version of a common use case of `_.filter`: selecting only
    // objects containing specific `key:value` pairs.
    function where(obj, attrs) {
        return filter(obj, matcher(attrs));
    }

    // Return the maximum element (or element-based computation).
    function max(obj, iteratee, context) {
        var result = -Infinity, lastComputed = -Infinity,
            value, computed;
        if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
            obj = isArrayLike(obj) ? obj : values(obj);
            for (var i = 0, length = obj.length; i < length; i++) {
                value = obj[i];
                if (value != null && value > result) {
                    result = value;
                }
            }
        } else {
            iteratee = cb(iteratee, context);
            each(obj, function (v, index, list) {
                computed = iteratee(v, index, list);
                if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
                    result = v;
                    lastComputed = computed;
                }
            });
        }
        return result;
    }

    // Return the minimum element (or element-based computation).
    function min(obj, iteratee, context) {
        var result = Infinity, lastComputed = Infinity,
            value, computed;
        if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
            obj = isArrayLike(obj) ? obj : values(obj);
            for (var i = 0, length = obj.length; i < length; i++) {
                value = obj[i];
                if (value != null && value < result) {
                    result = value;
                }
            }
        } else {
            iteratee = cb(iteratee, context);
            each(obj, function (v, index, list) {
                computed = iteratee(v, index, list);
                if (computed < lastComputed || computed === Infinity && result === Infinity) {
                    result = v;
                    lastComputed = computed;
                }
            });
        }
        return result;
    }

    // Sample **n** random values from a collection using the modern version of the
    // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    // If **n** is not specified, returns a single random element.
    // The internal `guard` argument allows it to work with `_.map`.
    function sample(obj, n, guard) {
        if (n == null || guard) {
            if (!isArrayLike(obj)) obj = values(obj);
            return obj[random(obj.length - 1)];
        }
        var sample = isArrayLike(obj) ? clone(obj) : values(obj);
        var length = getLength(sample);
        n = Math.max(Math.min(n, length), 0);
        var last = length - 1;
        for (var index = 0; index < n; index++) {
            var rand = random(index, last);
            var temp = sample[index];
            sample[index] = sample[rand];
            sample[rand] = temp;
        }
        return sample.slice(0, n);
    }

    // Shuffle a collection.
    function shuffle(obj) {
        return sample(obj, Infinity);
    }

    // Sort the object's values by a criterion produced by an iteratee.
    function sortBy(obj, iteratee, context) {
        var index = 0;
        iteratee = cb(iteratee, context);
        return pluck(map(obj, function (value, key, list) {
            return {
                value: value,
                index: index++,
                criteria: iteratee(value, key, list)
            };
        }).sort(function (left, right) {
            var a = left.criteria;
            var b = right.criteria;
            if (a !== b) {
                if (a > b || a === void 0) return 1;
                if (a < b || b === void 0) return -1;
            }
            return left.index - right.index;
        }), 'value');
    }

    // An internal function used for aggregate "group by" operations.
    function group(behavior, partition) {
        return function (obj, iteratee, context) {
            var result = partition ? [[], []] : {};
            iteratee = cb(iteratee, context);
            each(obj, function (value, index) {
                var key = iteratee(value, index, obj);
                behavior(result, value, key);
            });
            return result;
        };
    }

    // Groups the object's values by a criterion. Pass either a string attribute
    // to group by, or a function that returns the criterion.
    var groupBy = group(function (result, value, key) {
        if (has$1(result, key)) result[key].push(value); else result[key] = [value];
    });

    // Indexes the object's values by a criterion, similar to `_.groupBy`, but for
    // when you know that your index values will be unique.
    var indexBy = group(function (result, value, key) {
        result[key] = value;
    });

    // Counts instances of an object that group by a certain criterion. Pass
    // either a string attribute to count by, or a function that returns the
    // criterion.
    var countBy = group(function (result, value, key) {
        if (has$1(result, key)) result[key]++; else result[key] = 1;
    });

    // Split a collection into two arrays: one whose elements all pass the given
    // truth test, and one whose elements all do not pass the truth test.
    var partition = group(function (result, value, pass) {
        result[pass ? 0 : 1].push(value);
    }, true);

    // Safely create a real, live array from anything iterable.
    var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
    function toArray(obj) {
        if (!obj) return [];
        if (isArray(obj)) return slice.call(obj);
        if (isString(obj)) {
            // Keep surrogate pair characters together.
            return obj.match(reStrSymbol);
        }
        if (isArrayLike(obj)) return map(obj, identity);
        return values(obj);
    }

    // Return the number of elements in a collection.
    function size(obj) {
        if (obj == null) return 0;
        return isArrayLike(obj) ? obj.length : keys(obj).length;
    }

    // Internal `_.pick` helper function to determine whether `key` is an enumerable
    // property name of `obj`.
    function keyInObj(value, key, obj) {
        return key in obj;
    }

    // Return a copy of the object only containing the allowed properties.
    var pick = restArguments(function (obj, keys) {
        var result = {}, iteratee = keys[0];
        if (obj == null) return result;
        if (isFunction$1(iteratee)) {
            if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
            keys = allKeys(obj);
        } else {
            iteratee = keyInObj;
            keys = flatten$1(keys, false, false);
            obj = Object(obj);
        }
        for (var i = 0, length = keys.length; i < length; i++) {
            var key = keys[i];
            var value = obj[key];
            if (iteratee(value, key, obj)) result[key] = value;
        }
        return result;
    });

    // Return a copy of the object without the disallowed properties.
    var omit = restArguments(function (obj, keys) {
        var iteratee = keys[0], context;
        if (isFunction$1(iteratee)) {
            iteratee = negate(iteratee);
            if (keys.length > 1) context = keys[1];
        } else {
            keys = map(flatten$1(keys, false, false), String);
            iteratee = function (value, key) {
                return !contains(keys, key);
            };
        }
        return pick(obj, iteratee, context);
    });

    // Returns everything but the last entry of the array. Especially useful on
    // the arguments object. Passing **n** will return all the values in
    // the array, excluding the last N.
    function initial(array, n, guard) {
        return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
    }

    // Get the first element of an array. Passing **n** will return the first N
    // values in the array. The **guard** check allows it to work with `_.map`.
    function first(array, n, guard) {
        if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
        if (n == null || guard) return array[0];
        return initial(array, array.length - n);
    }

    // Returns everything but the first entry of the `array`. Especially useful on
    // the `arguments` object. Passing an **n** will return the rest N values in the
    // `array`.
    function rest(array, n, guard) {
        return slice.call(array, n == null || guard ? 1 : n);
    }

    // Get the last element of an array. Passing **n** will return the last N
    // values in the array.
    function last(array, n, guard) {
        if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
        if (n == null || guard) return array[array.length - 1];
        return rest(array, Math.max(0, array.length - n));
    }

    // Trim out all falsy values from an array.
    function compact(array) {
        return filter(array, Boolean);
    }

    // Flatten out an array, either recursively (by default), or up to `depth`.
    // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
    function flatten(array, depth) {
        return flatten$1(array, depth, false);
    }

    // Take the difference between one array and a number of other arrays.
    // Only the elements present in just the first array will remain.
    var difference = restArguments(function (array, rest) {
        rest = flatten$1(rest, true, true);
        return filter(array, function (value) {
            return !contains(rest, value);
        });
    });

    // Return a version of the array that does not contain the specified value(s).
    var without = restArguments(function (array, otherArrays) {
        return difference(array, otherArrays);
    });

    // Produce a duplicate-free version of the array. If the array has already
    // been sorted, you have the option of using a faster algorithm.
    // The faster algorithm will not work with an iteratee if the iteratee
    // is not a one-to-one function, so providing an iteratee will disable
    // the faster algorithm.
    function uniq(array, isSorted, iteratee, context) {
        if (!isBoolean(isSorted)) {
            context = iteratee;
            iteratee = isSorted;
            isSorted = false;
        }
        if (iteratee != null) iteratee = cb(iteratee, context);
        var result = [];
        var seen = [];
        for (var i = 0, length = getLength(array); i < length; i++) {
            var value = array[i],
                computed = iteratee ? iteratee(value, i, array) : value;
            if (isSorted && !iteratee) {
                if (!i || seen !== computed) result.push(value);
                seen = computed;
            } else if (iteratee) {
                if (!contains(seen, computed)) {
                    seen.push(computed);
                    result.push(value);
                }
            } else if (!contains(result, value)) {
                result.push(value);
            }
        }
        return result;
    }

    // Produce an array that contains the union: each distinct element from all of
    // the passed-in arrays.
    var union = restArguments(function (arrays) {
        return uniq(flatten$1(arrays, true, true));
    });

    // Produce an array that contains every item shared between all the
    // passed-in arrays.
    function intersection(array) {
        var result = [];
        var argsLength = arguments.length;
        for (var i = 0, length = getLength(array); i < length; i++) {
            var item = array[i];
            if (contains(result, item)) continue;
            var j;
            for (j = 1; j < argsLength; j++) {
                if (!contains(arguments[j], item)) break;
            }
            if (j === argsLength) result.push(item);
        }
        return result;
    }

    // Complement of zip. Unzip accepts an array of arrays and groups
    // each array's elements on shared indices.
    function unzip(array) {
        var length = array && max(array, getLength).length || 0;
        var result = Array(length);

        for (var index = 0; index < length; index++) {
            result[index] = pluck(array, index);
        }
        return result;
    }

    // Zip together multiple lists into a single array -- elements that share
    // an index go together.
    var zip = restArguments(unzip);

    // Converts lists into objects. Pass either a single array of `[key, value]`
    // pairs, or two parallel arrays of the same length -- one of keys, and one of
    // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
    function object(list, values) {
        var result = {};
        for (var i = 0, length = getLength(list); i < length; i++) {
            if (values) {
                result[list[i]] = values[i];
            } else {
                result[list[i][0]] = list[i][1];
            }
        }
        return result;
    }

    // Generate an integer Array containing an arithmetic progression. A port of
    // the native Python `range()` function. See
    // [the Python documentation](https://docs.python.org/library/functions.html#range).
    function range(start, stop, step) {
        if (stop == null) {
            stop = start || 0;
            start = 0;
        }
        if (!step) {
            step = stop < start ? -1 : 1;
        }

        var length = Math.max(Math.ceil((stop - start) / step), 0);
        var range = Array(length);

        for (var idx = 0; idx < length; idx++, start += step) {
            range[idx] = start;
        }

        return range;
    }

    // Chunk a single array into multiple arrays, each containing `count` or fewer
    // items.
    function chunk(array, count) {
        if (count == null || count < 1) return [];
        var result = [];
        var i = 0, length = array.length;
        while (i < length) {
            result.push(slice.call(array, i, i += count));
        }
        return result;
    }

    // Helper function to continue chaining intermediate results.
    function chainResult(instance, obj) {
        return instance._chain ? _$1(obj).chain() : obj;
    }

    // Add your own custom functions to the Underscore object.
    function mixin(obj) {
        each(functions(obj), function (name) {
            var func = _$1[name] = obj[name];
            _$1.prototype[name] = function () {
                var args = [this._wrapped];
                push.apply(args, arguments);
                return chainResult(this, func.apply(_$1, args));
            };
        });
        return _$1;
    }

    // Add all mutator `Array` functions to the wrapper.
    each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function (name) {
        var method = ArrayProto[name];
        _$1.prototype[name] = function () {
            var obj = this._wrapped;
            if (obj != null) {
                method.apply(obj, arguments);
                if ((name === 'shift' || name === 'splice') && obj.length === 0) {
                    delete obj[0];
                }
            }
            return chainResult(this, obj);
        };
    });

    // Add all accessor `Array` functions to the wrapper.
    each(['concat', 'join', 'slice'], function (name) {
        var method = ArrayProto[name];
        _$1.prototype[name] = function () {
            var obj = this._wrapped;
            if (obj != null) obj = method.apply(obj, arguments);
            return chainResult(this, obj);
        };
    });

    // Named Exports

    var allExports = {
        __proto__: null,
        VERSION: VERSION,
        restArguments: restArguments,
        isObject: isObject,
        isNull: isNull,
        isUndefined: isUndefined,
        isBoolean: isBoolean,
        isElement: isElement,
        isString: isString,
        isNumber: isNumber,
        isDate: isDate,
        isRegExp: isRegExp,
        isError: isError,
        isSymbol: isSymbol,
        isArrayBuffer: isArrayBuffer,
        isDataView: isDataView$1,
        isArray: isArray,
        isFunction: isFunction$1,
        isArguments: isArguments$1,
        isFinite: isFinite$1,
        isNaN: isNaN$1,
        isTypedArray: isTypedArray$1,
        isEmpty: isEmpty,
        isMatch: isMatch,
        isEqual: isEqual,
        isMap: isMap,
        isWeakMap: isWeakMap,
        isSet: isSet,
        isWeakSet: isWeakSet,
        keys: keys,
        allKeys: allKeys,
        values: values,
        pairs: pairs,
        invert: invert,
        functions: functions,
        methods: functions,
        extend: extend,
        extendOwn: extendOwn,
        assign: extendOwn,
        defaults: defaults,
        create: create,
        clone: clone,
        tap: tap,
        get: get,
        has: has,
        mapObject: mapObject,
        identity: identity,
        constant: constant,
        noop: noop,
        toPath: toPath$1,
        property: property,
        propertyOf: propertyOf,
        matcher: matcher,
        matches: matcher,
        times: times,
        random: random,
        now: now,
        escape: _escape,
        unescape: _unescape,
        templateSettings: templateSettings,
        template: template,
        result: result,
        uniqueId: uniqueId,
        chain: chain,
        iteratee: iteratee,
        partial: partial,
        bind: bind,
        bindAll: bindAll,
        memoize: memoize,
        delay: delay,
        defer: defer,
        throttle: throttle,
        debounce: debounce,
        wrap: wrap,
        negate: negate,
        compose: compose,
        after: after,
        before: before,
        once: once,
        findKey: findKey,
        findIndex: findIndex,
        findLastIndex: findLastIndex,
        sortedIndex: sortedIndex,
        indexOf: indexOf,
        lastIndexOf: lastIndexOf,
        find: find,
        detect: find,
        findWhere: findWhere,
        each: each,
        forEach: each,
        map: map,
        collect: map,
        reduce: reduce,
        foldl: reduce,
        inject: reduce,
        reduceRight: reduceRight,
        foldr: reduceRight,
        filter: filter,
        select: filter,
        reject: reject,
        every: every,
        all: every,
        some: some,
        any: some,
        contains: contains,
        includes: contains,
        include: contains,
        invoke: invoke,
        pluck: pluck,
        where: where,
        max: max,
        min: min,
        shuffle: shuffle,
        sample: sample,
        sortBy: sortBy,
        groupBy: groupBy,
        indexBy: indexBy,
        countBy: countBy,
        partition: partition,
        toArray: toArray,
        size: size,
        pick: pick,
        omit: omit,
        first: first,
        head: first,
        take: first,
        initial: initial,
        last: last,
        rest: rest,
        tail: rest,
        drop: rest,
        compact: compact,
        flatten: flatten,
        without: without,
        uniq: uniq,
        unique: uniq,
        union: union,
        intersection: intersection,
        difference: difference,
        unzip: unzip,
        transpose: unzip,
        zip: zip,
        object: object,
        range: range,
        chunk: chunk,
        mixin: mixin,
        'default': _$1
    };

    // Default Export

    // Add all of the Underscore functions to the wrapper object.
    var _ = mixin(allExports);
    // Legacy Node.js API.
    _._ = _;

    return _;

})));
//# sourceMappingURL=underscore-umd.js.map;
+function(t,e,r){"use strict";var i={calc:!1};e.fn.rrssb=function(t){var i=e.extend({description:r,emailAddress:r,emailBody:r,emailSubject:r,image:r,title:r,url:r},t);for(var s in i)i.hasOwnProperty(s)&&i[s]!==r&&(i[s]=n(i[s]));i.url!==r&&(e(this).find(".rrssb-facebook a").attr("href","https://www.facebook.com/sharer/sharer.php?u="+i.url),e(this).find(".rrssb-tumblr a").attr("href","http://tumblr.com/share/link?url="+i.url+(i.title!==r?"&name="+i.title:"")+(i.description!==r?"&description="+i.description:"")),e(this).find(".rrssb-linkedin a").attr("href","http://www.linkedin.com/shareArticle?mini=true&url="+i.url+(i.title!==r?"&title="+i.title:"")+(i.description!==r?"&summary="+i.description:"")),e(this).find(".rrssb-twitter a").attr("href","https://twitter.com/intent/tweet?text="+(i.description!==r?i.description:"")+"%20"+i.url),e(this).find(".rrssb-hackernews a").attr("href","https://news.ycombinator.com/submitlink?u="+i.url+(i.title!==r?"&text="+i.title:"")),e(this).find(".rrssb-reddit a").attr("href","http://www.reddit.com/submit?url="+i.url+(i.description!==r?"&text="+i.description:"")+(i.title!==r?"&title="+i.title:"")),e(this).find(".rrssb-googleplus a").attr("href","https://plus.google.com/share?url="+(i.description!==r?i.description:"")+"%20"+i.url),e(this).find(".rrssb-pinterest a").attr("href","http://pinterest.com/pin/create/button/?url="+i.url+(i.image!==r?"&amp;media="+i.image:"")+(i.description!==r?"&amp;description="+i.description:"")),e(this).find(".rrssb-pocket a").attr("href","https://getpocket.com/save?url="+i.url),e(this).find(".rrssb-github a").attr("href",i.url)),i.emailAddress!==r&&e(this).find(".rrssb-email a").attr("href","mailto:"+i.emailAddress+"?"+(i.emailSubject!==r?"subject="+i.emailSubject:"")+(i.emailBody!==r?"&amp;body="+i.emailBody:""))};var s=function(){var t=e("<div>"),r=["calc","-webkit-calc","-moz-calc"];e("body").append(t);for(var s=0;s<r.length;s++)if(t.css("width",r[s]+"(1px)"),1===t.width()){i.calc=r[s];break}t.remove()},n=function(t){if(t!==r&&null!==t){if(null===t.match(/%[0-9a-f]{2}/i))return encodeURIComponent(t);t=decodeURIComponent(t),n(t)}},a=function(){e(".rrssb-buttons").each(function(t){var r=e(this),i=e("li:visible",r),s=i.length,n=100/s;i.css("width",n+"%").attr("data-initwidth",n)})},l=function(){e(".rrssb-buttons").each(function(t){var r=e(this),i=r.width(),s=e("li",r).not(".small").first().width();s>170&&e("li.small",r).length<1?r.addClass("large-format"):r.removeClass("large-format"),200>i?r.removeClass("small-format").addClass("tiny-format"):r.removeClass("tiny-format")})},o=function(){e(".rrssb-buttons").each(function(t){var r=e(this),i=e("li",r),s=i.filter(".small"),n=0,a=0,l=s.first(),o=parseFloat(l.attr("data-size"))+55,c=s.length;if(c===i.length){var d=42*c,m=r.width();m>d+o&&(r.removeClass("small-format"),s.first().removeClass("small"),h())}else{i.not(".small").each(function(t){var r=e(this),i=parseFloat(r.attr("data-size"))+55,s=parseFloat(r.width());n+=s,a+=i});var u=n-a;u>o&&(l.removeClass("small"),h())}})},c=function(t){e(".rrssb-buttons").each(function(t){var r=e(this),i=e("li",r);e(i.get().reverse()).each(function(t,r){var s=e(this);if(s.hasClass("small")===!1){var n=parseFloat(s.attr("data-size"))+55,a=parseFloat(s.width());if(n>a){var l=i.not(".small").last();e(l).addClass("small"),h()}}--r||o()})}),t===!0&&m(h)},h=function(){e(".rrssb-buttons").each(function(t){var r,s,n,l,o,c=e(this),h=e("li",c),d=h.filter(".small"),m=d.length;m>0&&m!==h.length?(c.removeClass("small-format"),d.css("width","42px"),n=42*m,r=h.not(".small").length,s=100/r,o=n/r,i.calc===!1?(l=(c.innerWidth()-1)/r-o,l=Math.floor(1e3*l)/1e3,l+="px"):l=i.calc+"("+s+"% - "+o+"px)",h.not(".small").css("width",l)):m===h.length?(c.addClass("small-format"),a()):(c.removeClass("small-format"),a())}),l()},d=function(){e(".rrssb-buttons").each(function(t){e(this).addClass("rrssb-"+(t+1))}),s(),a(),e(".rrssb-buttons li .rrssb-text").each(function(t){var r=e(this),i=r.width();r.closest("li").attr("data-size",i)}),c(!0)},m=function(t){e(".rrssb-buttons li.small").removeClass("small"),c(),t()},u=function(e,i,s,n){var a=t.screenLeft!==r?t.screenLeft:screen.left,l=t.screenTop!==r?t.screenTop:screen.top,o=t.innerWidth?t.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width,c=t.innerHeight?t.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,h=o/2-s/2+a,d=c/3-n/3+l,m=t.open(e,i,"scrollbars=yes, width="+s+", height="+n+", top="+d+", left="+h);t.focus&&m.focus()},f=function(){var t={};return function(e,r,i){i||(i="Don't call this twice without a uniqueId"),t[i]&&clearTimeout(t[i]),t[i]=setTimeout(e,r)}}();e(document).ready(function(){e(document).on("click",".rrssb-buttons a.popup",{},function(t){var r=e(this);u(r.attr("href"),r.find(".rrssb-text").html(),580,470),t.preventDefault()}),e(t).on("resize", function(){m(h),f(function(){m(h)},200,"finished resizing")}),d()}),t.rrssbInit=d}(window,jQuery);;
var tabsHandler = {
    i: 0,
    init: function () {
        this.i = $('.tabs-container__tab-item--active').index();
        if (this.i == -1) {
            $('.tabs-container__tab-item').first().addClass('tabs-container__tab-item--active');
            this.i = 0;
        }
        $('.tabs-container__tab-item-link').attr({
            'aria-selected': 'false',
            'tabindex': -1
        });
        $($('.tabs-container__tab-item-link').get(this.i)).attr({
            'aria-selected': 'true',
            'tabindex': 0
        });
        $('.tab-panel').hide();
        $($('.tab-panel').get(this.i)).show().addClass('tab-panel--visible');
        this.bindEvents();
    },
    bindEvents: function () {
        $('.tabs-container__tab-item-link').on({
            keydown: function (e) {
                if (37 <= e.keyCode && e.keyCode <= 40) {
                    if (e.keyCode == 37 || e.keyCode == 38) tabsHandler.i = (tabsHandler.i > 0) ? tabsHandler.i - 1 : $('.tabs-container__tab-item').length - 1;
                    else if (e.keyCode == 39 || e.keyCode == 40) tabsHandler.i = (tabsHandler.i < $('.tabs-container__tab-item').length - 1) ? tabsHandler.i + 1 : 0;
                    $($('.tabs-container__tab-item-link').get(tabsHandler.i)).trigger("click");
                    e.preventDefault();
                }
            },
            click: function (e) {
                tabsHandler.i = $.inArray(this, $('.tabs-container__tab-item-link').get());
                tabsHandler.setActive();
                e.preventDefault();
            }
        });
    },
    setActive: function () {
        $('.tabs-container__tab-item-link').attr({
            'aria-selected': 'false',
            'tabindex': -1
        });
        $('.tabs-container__tab-item').removeClass('tabs-container__tab-item--active');
        $('.tab-panel').hide().removeClass('tab-panel--visible');
        $($('.tabs-container__tab-item-link').get(this.i)).attr({
            'aria-selected': 'true',
            'tabindex': 0
        }).trigger("focus");
        $($('.tabs-container__tab-item').get(this.i)).addClass('tabs-container__tab-item--active');
        $($($('.tabs-container__tab-item-link').get(this.i)).attr('href')).show().addClass('tab-panel--visible');
    }
};
;
///// <reference path="../../../../../scripts/typings/jquery/jquery.d.ts" />
var ContentArea = /** @class */ (function () {
    function ContentArea($contentArea) {
        var self = this;
        self.$contentArea = $contentArea;
        self.$blocks = self.$contentArea.find(".block > div");
    }
    /* Discover which blocks belongs to the same row by using the offset top value.
     * If block has the same offset top value it belongs to the same row .
     * Then each row will get the same height. */
    ContentArea.prototype.setBlockRowsEqualHeight = function () {
        var self = this;
        var blockRow = new ContentAreaBlockRow();
        $.each(self.$blocks, function (e, block) {
            if (blockRow.offsetTop === 0) {
                blockRow.offsetTop = $(block).offset().top;
            }
            if (self.isNewRow($(block), blockRow)) {
                self.setEqualHeight(blockRow.$blocks, blockRow.highestBlock);
                blockRow = new ContentAreaBlockRow();
                blockRow.offsetTop = $(block).offset().top;
                blockRow.highestBlock = $(block).outerHeight(true);
            }
            if (blockRow.highestBlock < $(block).outerHeight(true)) {
                blockRow.highestBlock = $(block).outerHeight(true);
            }
            blockRow.$blocks.push(block);
        });
        self.setEqualHeight(blockRow.$blocks, blockRow.highestBlock);
    };
    ContentArea.prototype.isNewRow = function (currentBlock, blockRow) {
        return blockRow.offsetTop !== 0 && blockRow.offsetTop !== currentBlock.offset().top;
    };
    ContentArea.prototype.setEqualHeight = function (blocks, height) {
        if (blocks.length > 1) { // We only need to set height on blocks if it is more than one on a row
            $.each(blocks, function (e, item) {
                $(item).outerHeight(height);
            });
        }
    };
    ContentArea.prototype.resetBlocksHeight = function () {
        this.$blocks.css("height", "auto");
    };
    return ContentArea;
}());
;
var ContentAreaBlockRow = /** @class */ (function () {
    function ContentAreaBlockRow() {
        this.offsetTop = 0;
        this.$blocks = [];
        this.highestBlock = 0;
    }
    return ContentAreaBlockRow;
}());
;
var ContentAreasHeightAdjuster = /** @class */ (function () {
    function ContentAreasHeightAdjuster() {
        var self = this;
        //self.customEventHandler = new CustomEventHandler();
        var contentAreas = [];
        $.each($(".content-area-with-equal-block-height"), function (e, contentArea) {
            var blocksInContentArea = $(contentArea).children(".block").children("div");
            if (blocksInContentArea.length > 1) { // Only content areas with more than 1 block is neccessery
                contentAreas.push(new ContentArea($(contentArea)));
            }
        });
        // todo: byt ut mot generell klass när den finns
        // Set equal heights when window is loadad (with all images etc)
        $(window)
            .on("load", function () {
            contentAreas.forEach(function (contentArea) {
                contentArea.setBlockRowsEqualHeight();
            });
        });
        // todo: byt ut mot generell klass när den finns
        window.onresize = function () {
            clearTimeout(self.resizedTimeout);
            self.resizedTimeout = setTimeout(function () {
                contentAreas.forEach(function (contentArea) {
                    self.resetHeightAndUpdateBlockHeights(contentArea);
                });
            }, 100);
        };
       customEventHandler.subscribe("update-content-area-height-adjuster", function () {
            contentAreas.forEach(function (contentArea) {
                self.resetHeightAndUpdateBlockHeights(contentArea);
            });
        });
    }
    ContentAreasHeightAdjuster.prototype.resetHeightAndUpdateBlockHeights = function (contentArea) {
        contentArea.resetBlocksHeight();
        contentArea.setBlockRowsEqualHeight();
    };
    return ContentAreasHeightAdjuster;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    var contentAreasHeightAdjuster = new ContentAreasHeightAdjuster();
});
;
var startBlockDropDownHandler = {
    init: function () {
        $('#startContentLeft').hide();
        $('#startContentRight').hide();
        $('.startblock__dropdown-button').on('click', function (e) {
            e.preventDefault();
            startBlockDropDownHandler.toggleAllActive($(this));
            startBlockDropDownHandler.toggleDropDownContent($(this));
        });
        $(document).on('click keyup', function (e) {
            if (!$(e.target).parents('.startblock__dropdown').length || e.keyCode === 27) {
                startBlockDropDownHandler.toggleAllActive();
            }
        });
    },
    toggleDropDownContent: function ($controlObj) {
        $controlObj.next('.startblock__dropdown-content').toggle();
        $controlObj.toggleClass('button-startblock--active');
        $controlObj.attr('aria-expanded', ($controlObj.attr('aria-expanded') == "false" ? true : false));
        $controlObj.find('.button-startblock__toggle-icon').toggleClass('fa-plus-circle fa-minus-circle');
    },
    toggleAllActive: function ($controlObj) {
        $('.startblock__dropdown-button').not($controlObj).each(function () {
            if ($(this).hasClass('button-startblock--active')) {
                startBlockDropDownHandler.toggleDropDownContent($(this));
            }
        });
    }
}
;
var flexsliderHandler = {
    init: function () {
        if ($('.flexslider').length > 0 && $('.flexslider').find('.slides > .imagesliderblock').length > 1) {
            $('.flexslider').flexslider({
                selector: '.slides > .imagesliderblock',
                //animation: "slide",
                //pauseOnAction: true,
                //pauseOnHover: true,
                //pausePlay: true,
                //pauseInvisible: true,
                //slideshowSpeed: 7000,
                //animationSpeed: 600,
                touch: true,
                slideshow: false,
            });
        }
    },   
};
;
////const { data } = require("jquery");

var dataListHandler = {

    /*************************************************************/
    options: {},
    /*************************************************************/
    currentPageIdx: 1,
    /*************************************************************/
    init: function (opt) {

        dataListHandler.options = $.extend({
            language: 'sv',
            performInitSearch: false,
            resultPageSize: 10,
            sortOrder: 'Relevance',
            $searchQueryInput: $(),
            $searchFilterContainer: $(),
            $searchResultContainer: $(),
            $searchResultCountContainer: $(),
            $activeFiltersContainer: $(),
            $showMoreButton: $(),
            $searchButton: $(),
            $resetButton: $(),
            $xmlDownloadLink: $(),
            onPageLoaded: function (response) {},
            localization: {
                resetFilters: 'Rensa alla filter',
                freeText: 'Fritext',
                filterResultHeading: {
                    intro: 'Aktuell filtrering ger',
                    hit: ' träff',
                    hits: ' träffar',
                    nohits: ' inga träffar'
                }
            }
        }, opt);

        //on click enter in seach input
        dataListHandler.options.$searchQueryInput.keyup(function (e) {
            if (e.keyCode == 13) {
                dataListHandler.search({ replaceResult: true });
                e.preventDefault();
            }
        });

        //on click search button
        dataListHandler.options.$searchButton.on('click', function (e) {
            dataListHandler.search({ replaceResult: true });
            e.preventDefault();
        });

        //on click reset button
        dataListHandler.options.$resetButton.on('click', function (e) {
            dataListHandler.search({ searchQuery: '', replaceResult: true });
            e.preventDefault();
        });

        //on click show-more button
        dataListHandler.options.$showMoreButton.on('click', function (e) {
            dataListHandler.search({
                skip: dataListHandler.currentPageIdx * dataListHandler.options.resultPageSize,
                onsuccess: function () {
                    $('article h1 a', $('.collection').last()).first().focus();
                }

            });
            dataListHandler.currentPageIdx++;
            e.preventDefault();
        });

        //seach on init?
        if (dataListHandler.options.performInitSearch) {
            dataListHandler.search({ isInit: true });
        }

        //hide/show reset button on keyup in query input
        dataListHandler.options.$searchQueryInput.on('keyup', function (e) {
            dataListHandler.displayResetQueryButton(dataListHandler.options.$searchQueryInput.val());
        });
    },
    /*************************************************************/
    search: function (options) {

        var pageIdxtmp = dataListHandler.getPageIndexFromUrl();
        var initSkip = pageIdxtmp ? pageIdxtmp - 1 : 0;

        options = $.extend({
            isInit: false,
            searchQuery: '',
            sortOrder: dataListHandler.options.sortOrder,
            replaceResult: false,
            resetFilters: false,
            allowUrlParams: false,
            language: dataListHandler.options.language,
            skip: initSkip * dataListHandler.options.resultPageSize,
            take: dataListHandler.options.resultPageSize,
            searchQuery: dataListHandler.options.$searchQueryInput.val(),
            onsuccess: function () {}
        }, options);

        searchFilter = {
            SearchQuery: options.searchQuery,
            SectionFilters: [],
            FilterAcc: options.resetFilters ? [] : dataListHandler.getFilterSelection(options.allowUrlParams),
            Skip: options.skip,
            Take: options.take,
            Cache: false,
            SortOrder: options.sortOrder,
            Language: options.language,
            //Site: "www.slu.se",
            ContextContentId: $('body').data('currentid'),
            IncludeMediaHits: false
        };

        //console.log('filter, options', searchFilter, options);

        //convert searchfilter object to base64 string to simplify passing it to controller
        // searchFilter -> stringify -> encode -> to base64 --- decode in reverse in controller
        var searchFilterB64 = btoa(encodeURIComponent(JSON.stringify(searchFilter)));
        var searchFilter64 = { searchFilterB64: searchFilterB64 };

        dataListHandler.setXmlDownloadParameter(searchFilterB64, searchFilter.ContextContentId);

        ajaxHandler.search(ajaxHandler.apiUrl.listPageSearch, searchFilter64, true, function (response) {

            dataListHandler.options.$searchQueryInput.val(options.searchQuery);
            dataListHandler.displayResetQueryButton(dataListHandler.options.$searchQueryInput.val());

            if (options.isInit) {
                //console.log('isinit', response.Data);
                dataListHandler.renderFilters(response.Data.FacetGroupOptions);

                // AT THIS MOMENT ALL FILTERS HAS BEEN RENDERED.
                // IF SEARCH QUERY AND/OR FILTERS ARE PASSED IN QUERY STRING, UPDATE SEARCH RESULT WITH THOSE VALUES APPLIED.

                var filters = dataListHandler.getFiltersFromUrl();
                var query = dataListHandler.getQueryFromUrl();
                var pageIdx = dataListHandler.getPageIndexFromUrl();
                //console.log('pageIdx if', pageIdx);
                dataListHandler.currentPageIdx = pageIdx ? pageIdx : 1;
                //console.log('currodx', dataListHandler.currentPageIdx);

                if (filters.length > 0 || query) {
                    dataListHandler.search({
                        searchQuery: query,
                        replaceResult: true,
                        resetFilters: false,
                        skip: 0,
                        take: dataListHandler.currentPageIdx * dataListHandler.options.resultPageSize,
                        allowUrlParams: true,
                        onsuccess: options.onsuccess
                    });
                    return;
                }
            }
            else {
                dataListHandler.updateFilters(response.Data.FacetGroupOptions, options.resetFilters);
                //true if search result from query string params (pageindex > 1)
                if (response.Data.Results.length > dataListHandler.options.resultPageSize) {
                    //console.log('pageidx else: len,ressize', response.Data.Results.length, dataListHandler.options.resultPageSize);
                    dataListHandler.currentPageIdx = response.Data.Results.length / dataListHandler.options.resultPageSize;
                    //console.log('curridx', dataListHandler.currentPageIdx);
                }
                //update url
                dataListHandler.setUrlParameter("q", options.searchQuery);
                dataListHandler.setUrlParameter("p", dataListHandler.currentPageIdx);
                dataListHandler.setUrlParameter("f", btoa(dataListHandler.getFilterSelection().join(';')));
            }

            //fix, hide result count if no filter
            if (searchFilter.FilterAcc.length > 0 || !(!searchFilter.SearchQuery)) {
                dataListHandler.options.$searchResultCountContainer.show();
            }
            else {
                dataListHandler.options.$searchResultCountContainer.hide();
            }

            //append search result
            dataListHandler.renderResults(response.FormattedSearchResult, options.replaceResult);

            //hide/show show-more-link 
            //console.log('idx,respagesize, total', dataListHandler.currentPageIdx, dataListHandler.options.resultPageSize, response.Data.TotalMatching);
            dataListHandler.displayShowMoreButton((dataListHandler.currentPageIdx * dataListHandler.options.resultPageSize) < response.Data.TotalMatching);

            //create "pills" for each selected filter
            dataListHandler.updateActiveFiltersView(response.Data.FacetGroupOptions);

            dataListHandler.setResultCount(response.Data.TotalMatching);

            //
            options.onsuccess(response);
            dataListHandler.options.onPageLoaded(response);

        }, null, "GET");

    },
    /*************************************************************/
    renderResults: function (resultsHtml, replace) {

        if (replace) {
            dataListHandler.currentPageIdx = 1;
            dataListHandler.options.$searchResultContainer.empty();
        }
        
        dataListHandler.options.$searchResultContainer.append(resultsHtml);
    },
    /*************************************************************/
    renderFilters: function (facetGroups) {
        $.each(facetGroups, function (idx1, facetGroup) {
            if (!facetGroup.Facets || facetGroup.Facets.length < 2) {
                //console.log('no facet');
                return;
            }
                

            var containerId = 'filter-container-' + facetGroup.Index;
            var accordionHeadingId = 'accordion-heading-' + facetGroup.Index;
            var accordionContentId = 'accordion-content-' + facetGroup.Index;

            $('<div id="' + containerId + '" data-filter-group="' + facetGroup.GroupFieldName + '" class="accordion-item accordion-item--slim accordion-item--narrow accordion-item--active">' +
                '<h2 class="accordion-item__heading">' +
                    '<span aria-controls="' + accordionContentId + '" class="accordion-item__heading-text" id="' + accordionHeadingId + '">' +
                        '<span class="accordion-item__heading-icon fal fa-sliders-h fa-fw" aria-hidden="true"></span>' +
                facetGroup.GroupName +
                (!facetGroup.Description ? '' : '<span class="accordion-item__tooltip" title="' + facetGroup.Description + '"><i class="fas fa-info-circle"></i></span>') +
                    '</span>' +
                '</h2>' +
                '<div aria-labelledby="' + accordionHeadingId + '" class="accordion-item__content" id="' + accordionContentId + '">' +
                    '<ul class="facet-group"></ul>' +
                '</div>' +
            '</div>')
            .appendTo(dataListHandler.options.$searchFilterContainer);

            var $filterContainer = $('#' + containerId + ' ul');

            $.each(facetGroup.Facets, function (idx2, facet) {
                $('<li id="' + facet.ID + '-container" class="facet-group__facet-item">' +
                    '<label for="' + facet.ID + '" class="facet-group__facet-label">' +
                    '<input id="' + facet.ID + '" class="facet-group__facet-input" name="' + facetGroup.GroupFieldName + '" value="' + facet.Key + '" data-label="' + facet.Name + '" type="' + facetGroup.DisplayMode + '"' + (facet.Selected ? ' checked="checked"' : '') + ' />' +
                        facet.Name +
                        '<span class="facet-group__facet-count">' + facet.Count + '</span>' +
                    '</label >' +
                '</li>')
                .appendTo($filterContainer);
            });

            if (facetGroup.DisplayMode == 'radio') {
                //add 'dummy' radio to use as show-all-option
                $('<input name="' + facetGroup.GroupFieldName + '" value="0" type="radio" checked="checked" class="show-all facet-group__show-all" />').appendTo($filterContainer);
            }            
        });

        $('input.show-all:radio').on('focus', function () {
            $('input:radio[name="' + $(this).attr('name') + '"]:not(.show-all)').first().focus();
        });

        //TODO: tyhm0001 - temp (flytta)
        $('.accordion-item__tooltip').tooltipster({
            animation: 'fade',
            theme: 'custom-theme',
            delay: 200,
            position: 'bottom-left',
            trigger: 'hover',
            maxWidth: 280,
        });

        accordionHandler.init();

        //on click input
        $('div.accordion-item input').off('change').on('change', function (e) {

            var $this = $(this);

            dataListHandler.search({
                replaceResult: true,
                onsuccess: function () {
                    $this.focus();
                }
            });
        });
    },
    /*************************************************************/
    updateFilters: function (facetGroups, resetSelections) {

        $('label span', dataListHandler.options.$searchFilterContainer).text('0');
        //$('input:not(:text)', dataListHandler.options.$searchFilterContainer).prop('disabled', 'disabled');

        $('input:not(:text):not(.show-all)', dataListHandler.options.$searchFilterContainer).each(function (idx, inp) {
            $(inp).prop('disabled', 'disabled');
            $(inp).closest('li').addClass('facet-group__facet-item--disabled');
        });

        if (resetSelections) {
            $('input:checkbox', dataListHandler.options.$searchFilterContainer).prop('checked', false);
            $('input.show-all').prop('checked', true)
        }

        $.each(facetGroups, function (idx1, facetGroup) {
            $.each(facetGroup.Facets, function (idx2, facet) {
                var $inp = $('#' + facet.ID);

                $inp.prop('disabled', null);
                $inp.closest('li').removeClass('facet-group__facet-item--disabled');

                $('#' + facet.ID + '-container label span').text(facet.Count);

                if (facet.Selected) {
                    $inp.prop('checked', true);
                }
            });
        });

        //fix, make sure selected inputs not disabled
        $('#search-filter-container input:checked').prop('disabled', false);
    },
    /*************************************************************/
    updateActiveFiltersView: function (facetGroups) {

        //remove existing active filters
        dataListHandler.options.$activeFiltersContainer.empty();
        dataListHandler.options.$activeFiltersContainer.hide();

        $.each($('input:not(:disabled):checked:not(.show-all)', dataListHandler.options.$searchFilterContainer), function (idx, inp) {
            var gn = $('.accordion-item__heading-button', $(inp).closest('.accordion-item')).text();
            $('<li class="page-tags__list-item page-tags__list-item--active">' +
                '<button class="page-tags__item-button" href="#" data-filter-selector="#' + $(inp).attr('id') + '"><span>' + gn + '</span>' + $(inp).data('label') + '</button>' +
            '</li>')
            .appendTo(dataListHandler.options.$activeFiltersContainer);
        });

        //add remove-search-query button?
        if (dataListHandler.options.$searchQueryInput.val()) {
            $('<li class="page-tags__list-item page-tags__list-item--active">' +
                '<button class="page-tags__item-button remove-query" href="#">' + dataListHandler.options.localization.freeText + ': ' + dataListHandler.options.$searchQueryInput.val() + '</button>' +
            '</li>')
            .prependTo(dataListHandler.options.$activeFiltersContainer);
        }

        //add remove-all-filters button?
        if ($('button', dataListHandler.options.$activeFiltersContainer).length > 0) {
            $('<li class="page-tags__list-item page-tags__list-item--inactive page-tags__list-item--clear">' +
                '<button class="page-tags__item-button remove-all" href="#">' + dataListHandler.options.localization.resetFilters + '</button>' +
            '</li>')
                .appendTo(dataListHandler.options.$activeFiltersContainer);

            dataListHandler.options.$activeFiltersContainer.show();
        }

        //handle click on active filter "pills"
        $('button', dataListHandler.options.$activeFiltersContainer).on('click', function (e) {

            e.preventDefault();

            var $this = $(this);
            var $filter = $($this.data('filter-selector'));

            if ($this.hasClass("remove-all")) {
                dataListHandler.search({ searchQuery: '', replaceResult: true, resetFilters: true });
                dataListHandler.options.$searchQueryInput.focus();
                return;
            }

            if ($this.hasClass("remove-query")) {
                dataListHandler.options.$searchQueryInput.val('');
            }

            if ($filter.is(':radio')) {
                $('input[name="' + $filter.attr('name') + '"].show-all').prop('checked', true)
            }
            else {
                $filter.prop('checked', false);
            }

            dataListHandler.search({ replaceResult: true });
        });
    },
    /*************************************************************/
    getFilterSelection: function (allowUrlParams) {

        var filters = [];

        $('div.accordion-item').each(function (idx1, groupElement) {

            groupElement = $(groupElement);
            var $$inp = $('input:checked:not(.show-all)', groupElement);

            var selectedFilters = $.map($$inp, function ($inp, i) { return $inp.value; })

            if (selectedFilters.length > 0) {
                var GroupFieldName = groupElement.data('filter-group');
                filters.push(GroupFieldName + '|' + selectedFilters.join('~'));
            }
        });

        //check query parameters for filter config
        if (filters.length == 0 && allowUrlParams) {
            filters = dataListHandler.getFiltersFromUrl();
        }

        return filters;
    },
    /*************************************************************/
    setResultCount: function (count) {

        var headingStart = dataListHandler.options.localization.filterResultHeading.intro;
        var headingEnd =
            count == 1
                ? dataListHandler.options.localization.filterResultHeading.hit
                : count == 0
                    ? ''
                    : dataListHandler.options.localization.filterResultHeading.hits;

        var headingRes =
            count == 0
                ? dataListHandler.options.localization.filterResultHeading.nohits
                : ' ' + count;

        dataListHandler.options.$searchResultCountContainer.text(headingStart + headingRes + headingEnd);
    },
    /*************************************************************/
    displayShowMoreButton: function (visible) {
        if (visible) {
            dataListHandler.options.$showMoreButton.show();
        }
        else {
            dataListHandler.options.$showMoreButton.hide();
        }
    },
    /*************************************************************/
    displayResetQueryButton: function (visible) {
        if (visible) {
            dataListHandler.options.$resetButton.show();
        }
        else {
            dataListHandler.options.$resetButton.hide();
        }
    },
    /*************************************************************/
    getUrlParameter: function (key) {
        return new URLSearchParams(window.location.search).get(key);
    },
    /*************************************************************/
    setUrlParameter: function (key, val) {
        var qs = new URLSearchParams(window.location.search);

        if (!val) {
            qs.delete(key);
        }
        else {
            qs.set(key, val);
        }

        var strQ = qs.toString();
        var q = window.location.pathname + (strQ.length > 0 ? ('?' + strQ) : '');

        history.pushState(null, '', q);
    },
    /*************************************************************/
    setXmlDownloadParameter: function (searchFilterB64, contextContentId) {

        var qs = new URLSearchParams();

        qs.set("searchFilterB64", searchFilterB64);
        qs.set("contextContentId", contextContentId)
        dataListHandler.options.$xmlDownloadLink.attr('href', '/resulttoxml?' + qs.toString());
    },
    /*************************************************************/
    getFiltersFromUrl: function () {
        var f = dataListHandler.getUrlParameter('f');
        return (f ? atob(dataListHandler.getUrlParameter('f')).split(';') : []);
    },
    /*************************************************************/
    getQueryFromUrl: function () {
        return dataListHandler.getUrlParameter('q');
    },
    /*************************************************************/
    getPageIndexFromUrl: function () {
        return dataListHandler.getUrlParameter('p');
    },
    objectToBinary: function (obj) {
        var string = JSON.stringify(obj);
        const codeUnits = new Uint16Array(string.length);
        for (let i = 0; i < codeUnits.length; i++) {
            codeUnits[i] = string.charCodeAt(i);
        }
        return btoa(String.fromCharCode(...new Uint8Array(codeUnits.buffer)));
    }
};
;
var readspeakerHandler = {
    init: function () {
        //console.log('rs_init2', $('#readspeaker_start'));
        $('#readspeaker_start').on('click', function (e) {
            //console.log('rs_click');
            //e.preventDefault();            
            $('.accordion-item__content').each(function (index) {
                $(this).css('display', 'block');
            });
        })
    },
    click: function () {
        //console.log('rs_click');
        $('.accordion-item__content').each(function (index) {
            //console.log('rs_accordion');
            $(this).css('display', 'block');
        });
    },
};
;
var emergencyMessageControl = {
    init: function () {
        localStorageStatusKey = 'emergencyCollapsed';
        if (localStorage.getItem(localStorageStatusKey) === null) {
            localStorage.setItem(localStorageStatusKey, $('.emergency').hasClass('emergency--active') ? 'false' : 'true');
        }
        else {
            if ((localStorage.getItem(localStorageStatusKey) === 'true') === $('.emergency').hasClass('emergency--active')) {
                $('.emergency').toggleClass('emergency--active');
            }
        }
        textHideAttr = $('#controlTextHide').attr('hidden');
        textShowAttr = $('#controlTextShow').attr('hidden');
        if (localStorage.getItem(localStorageStatusKey) === 'false') {
            if (typeof textHideAttr !== 'undefined' && textHideAttr !== false) $('#controlTextHide').removeAttr('hidden');
            if (typeof textShowAttr === 'undefined' || textShowAttr === false) $('#controlTextShow').attr('hidden', 'hidden');
        }
        else {
            $('#emergencyMessageContent').hide();
            if (typeof textHideAttr === 'undefined' || textHideAttr === false) $('#controlTextHide').attr('hidden', 'hidden');
            if (typeof textShowAttr !== 'undefined' && textShowAttr !== false) $('#controlTextShow').removeAttr('hidden');
        }
        $('#emergencyAccordionControl').replaceWith(function () {
            var btnAttrs = {};
            $.each(this.attributes, function (i, attr) {
                btnAttrs[attr.nodeName] = attr.nodeValue;
            });
            btnAttrs['aria-expanded'] = $(this).parents('.emergency--active').length ? 'true' : 'false';
            return $('<button />', btnAttrs)
                .append($(this).contents(), $('<span />', { 'aria-hidden': 'true' })
                    .addClass('emergency__toggle-icon far fa-' + ($(this).parents('.emergency--active').length ? 'chevron-up' : 'chevron-down'))
                )
        });
        $('#emergencyAccordionControl').on('click', function (e) {
            e.preventDefault();
            emergencyMessageControl.toggleAccordionSection($(this));
        });
    },
    toggleAccordionSection: function ($controlObj) {
        localStorage.setItem(localStorageStatusKey, (localStorage.getItem(localStorageStatusKey) === 'false') ? 'true' : 'false');
        $('#emergencyMessageContent').toggle();
        $controlObj.attr('aria-expanded', function () {
            return $(this).attr('aria-expanded') !== 'true';
        });
        $controlObj.children('.emergency__control-text').each(function () {
            attr = $(this).attr('hidden');
            if (typeof attr !== 'undefined' && attr !== false) {
                $(this).removeAttr('hidden');
            }
            else {
                $(this).attr('hidden', 'hidden');
            }
        });
        $('.emergency').toggleClass('emergency--active');
        $('.emergency__toggle-icon').toggleClass('fa-chevron-down fa-chevron-up');
    }
};
;
