/* Minification failed. Returning unminified contents.
(1379,9-10): run-time error JS1010: Expected identifier: .
(1379,9-10): run-time error JS1195: Expected expression: .
(1380,2-6): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(1409,18-19): run-time error JS1010: Expected identifier: .
(1409,18-19): run-time error JS1195: Expected expression: .
(1488,7-8): run-time error JS1010: Expected identifier: .
(1488,7-8): run-time error JS1195: Expected expression: .
(1515,7-8): run-time error JS1010: Expected identifier: .
(1515,7-8): run-time error JS1195: Expected expression: .
(1530,11-12): run-time error JS1010: Expected identifier: .
(1530,11-12): run-time error JS1195: Expected expression: .
(1534,11-12): run-time error JS1010: Expected identifier: .
(1534,11-12): run-time error JS1195: Expected expression: .
(1542,7-8): run-time error JS1010: Expected identifier: .
(1542,7-8): run-time error JS1195: Expected expression: .
(1976,7-8): run-time error JS1010: Expected identifier: .
(1976,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()
        });
    }
}
////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", "body");
        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, appendToElement) {
        //Not used as autocomplete at the moment, but old code in git history exist for this  but needs to be rewritten to work with newer jQuery
        $(selector).on("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 template = $("#rss-reader-template").html();

        var container = elementFactory.getRssContainer();
        ajaxHandler.getRssReaderDataItems(currentContentId, elementFactory.getBodyTag().data("gck"), language, function (data) {
            container.empty();
            container.append(_.template(template, { rssItems: data }));
        });
    }
};
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 far fa-' + ($(this).parents('.accordion-item--active').length ? 'minus' : 'plus'))
                )
                .toggleClass('accordion-item__heading-text accordion-item__heading-button');
        });
        $('.accordion-item__content').each(function () {
            if ($(this).parents('.accordion-item--active').length) {
                $(this).attr('aria-hidden', 'false');
            }
            else {
                $(this).hide().attr('aria-hidden', 'true');
            }
        });
        $('.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().attr('aria-hidden', function () {
            return $(this).attr('aria-hidden') !== 'true';
        });
        $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-minus fa-plus');
    }
};
;
//Hänvisas till i header.ascx
var accordionItems = new Array();

function init_accordion() {
    // Grab the accordion items from the page
    var divs = document.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].className == 'window_content') accordionItems.push(divs[i]);
    }

    // Assign onclick events to the accordion item headings
    for (var i = 0; i < accordionItems.length; i++) {
        var h2 = getFirstChildWithTagName(accordionItems[i], 'H2');
        h2.onclick = toggleAccordionItem;
    }

    // Hide all accordion item bodies except the first
    for (var i = 0; i < accordionItems.length; i++) {
        accordionItems[i].className = 'window_content hide';
    }
}

function toggleAccordionItem() {
    var itemClass = this.parentNode.className;

    // Hide all items
    for (var i = 0; i < accordionItems.length; i++) {
        accordionItems[i].className = 'window_content hide';
    }

    // Show this item if it was previously hidden
    if (itemClass == 'window_content hide') {
        this.parentNode.className = 'window_content';

    }
}

function getFirstChildWithTagName(element, tagName) {
    for (var i = 0; i < element.childNodes.length; i++) {
        if (element.childNodes[i].nodeName == tagName) return element.childNodes[i];
    }
}
;
var main = {
    init: function () {
        global.init();
        megamenuHandler.init();
        startBlockDropDown.init();
        clickableDivHandler.initButtonPuffBlocks();
        SmartphoneMenuHandler.init();

        if (helpers.isAuthenticated()) {
            contactHandler.init();
        }

        if (!helpers.isInEditMode()) {
            accordionHandler.init();
            init_accordion();
            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);;
/*! Magnific Popup - v1.1.0 - 2016-02-20
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2016 Dmitry Semenov; */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : window.jQuery || window.Zepto) }(function (a) { var b, c, d, e, f, g, h = "Close", i = "BeforeClose", j = "AfterClose", k = "BeforeAppend", l = "MarkupParse", m = "Open", n = "Change", o = "mfp", p = "." + o, q = "mfp-ready", r = "mfp-removing", s = "mfp-prevent-close", t = function () { }, u = !!window.jQuery, v = a(window), w = function (a, c) { b.ev.on(o + a + p, c) }, x = function (b, c, d, e) { var f = document.createElement("div"); return f.className = "mfp-" + b, d && (f.innerHTML = d), e ? c && c.appendChild(f) : (f = a(f), c && f.appendTo(c)), f }, y = function (c, d) { b.ev.triggerHandler(o + c, d), b.st.callbacks && (c = c.charAt(0).toLowerCase() + c.slice(1), b.st.callbacks[c] && b.st.callbacks[c].apply(b, a.isArray(d) ? d : [d])) }, z = function (c) { return c === g && b.currTemplate.closeBtn || (b.currTemplate.closeBtn = a(b.st.closeMarkup.replace("%title%", b.st.tClose)), g = c), b.currTemplate.closeBtn }, A = function () { a.magnificPopup.instance || (b = new t, b.init(), a.magnificPopup.instance = b) }, B = function () { var a = document.createElement("p").style, b = ["ms", "O", "Moz", "Webkit"]; if (void 0 !== a.transition) return !0; for (; b.length;) if (b.pop() + "Transition" in a) return !0; return !1 }; t.prototype = { constructor: t, init: function () { var c = navigator.appVersion; b.isLowIE = b.isIE8 = document.all && !document.addEventListener, b.isAndroid = /android/gi.test(c), b.isIOS = /iphone|ipad|ipod/gi.test(c), b.supportsTransition = B(), b.probablyMobile = b.isAndroid || b.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent), d = a(document), b.popupsCache = {} }, open: function (c) { var e; if (c.isObj === !1) { b.items = c.items.toArray(), b.index = 0; var g, h = c.items; for (e = 0; e < h.length; e++) if (g = h[e], g.parsed && (g = g.el[0]), g === c.el[0]) { b.index = e; break } } else b.items = a.isArray(c.items) ? c.items : [c.items], b.index = c.index || 0; if (b.isOpen) return void b.updateItemHTML(); b.types = [], f = "", c.mainEl && c.mainEl.length ? b.ev = c.mainEl.eq(0) : b.ev = d, c.key ? (b.popupsCache[c.key] || (b.popupsCache[c.key] = {}), b.currTemplate = b.popupsCache[c.key]) : b.currTemplate = {}, b.st = a.extend(!0, {}, a.magnificPopup.defaults, c), b.fixedContentPos = "auto" === b.st.fixedContentPos ? !b.probablyMobile : b.st.fixedContentPos, b.st.modal && (b.st.closeOnContentClick = !1, b.st.closeOnBgClick = !1, b.st.showCloseBtn = !1, b.st.enableEscapeKey = !1), b.bgOverlay || (b.bgOverlay = x("bg").on("click" + p, function () { b.close() }), b.wrap = x("wrap").attr("tabindex", -1).on("click" + p, function (a) { b._checkIfClose(a.target) && b.close() }), b.container = x("container", b.wrap)), b.contentContainer = x("content"), b.st.preloader && (b.preloader = x("preloader", b.container, b.st.tLoading)); var i = a.magnificPopup.modules; for (e = 0; e < i.length; e++) { var j = i[e]; j = j.charAt(0).toUpperCase() + j.slice(1), b["init" + j].call(b) } y("BeforeOpen"), b.st.showCloseBtn && (b.st.closeBtnInside ? (w(l, function (a, b, c, d) { c.close_replaceWith = z(d.type) }), f += " mfp-close-btn-in") : b.wrap.append(z())), b.st.alignTop && (f += " mfp-align-top"), b.fixedContentPos ? b.wrap.css({ overflow: b.st.overflowY, overflowX: "hidden", overflowY: b.st.overflowY }) : b.wrap.css({ top: v.scrollTop(), position: "absolute" }), (b.st.fixedBgPos === !1 || "auto" === b.st.fixedBgPos && !b.fixedContentPos) && b.bgOverlay.css({ height: d.height(), position: "absolute" }), b.st.enableEscapeKey && d.on("keyup" + p, function (a) { 27 === a.keyCode && b.close() }), v.on("resize" + p, function () { b.updateSize() }), b.st.closeOnContentClick || (f += " mfp-auto-cursor"), f && b.wrap.addClass(f); var k = b.wH = v.height(), n = {}; if (b.fixedContentPos && b._hasScrollBar(k)) { var o = b._getScrollbarSize(); o && (n.marginRight = o) } b.fixedContentPos && (b.isIE7 ? a("body, html").css("overflow", "hidden") : n.overflow = "hidden"); var r = b.st.mainClass; return b.isIE7 && (r += " mfp-ie7"), r && b._addClassToMFP(r), b.updateItemHTML(), y("BuildControls"), a("html").css(n), b.bgOverlay.add(b.wrap).prependTo(b.st.prependTo || a(document.body)), b._lastFocusedEl = document.activeElement, setTimeout(function () { b.content ? (b._addClassToMFP(q), b._setFocus()) : b.bgOverlay.addClass(q), d.on("focusin" + p, b._onFocusIn) }, 16), b.isOpen = !0, b.updateSize(k), y(m), c }, close: function () { b.isOpen && (y(i), b.isOpen = !1, b.st.removalDelay && !b.isLowIE && b.supportsTransition ? (b._addClassToMFP(r), setTimeout(function () { b._close() }, b.st.removalDelay)) : b._close()) }, _close: function () { y(h); var c = r + " " + q + " "; if (b.bgOverlay.detach(), b.wrap.detach(), b.container.empty(), b.st.mainClass && (c += b.st.mainClass + " "), b._removeClassFromMFP(c), b.fixedContentPos) { var e = { marginRight: "" }; b.isIE7 ? a("body, html").css("overflow", "") : e.overflow = "", a("html").css(e) } d.off("keyup" + p + " focusin" + p), b.ev.off(p), b.wrap.attr("class", "mfp-wrap").removeAttr("style"), b.bgOverlay.attr("class", "mfp-bg"), b.container.attr("class", "mfp-container"), !b.st.showCloseBtn || b.st.closeBtnInside && b.currTemplate[b.currItem.type] !== !0 || b.currTemplate.closeBtn && b.currTemplate.closeBtn.detach(), b.st.autoFocusLast && b._lastFocusedEl && a(b._lastFocusedEl).focus(), b.currItem = null, b.content = null, b.currTemplate = null, b.prevHeight = 0, y(j) }, updateSize: function (a) { if (b.isIOS) { var c = document.documentElement.clientWidth / window.innerWidth, d = window.innerHeight * c; b.wrap.css("height", d), b.wH = d } else b.wH = a || v.height(); b.fixedContentPos || b.wrap.css("height", b.wH), y("Resize") }, updateItemHTML: function () { var c = b.items[b.index]; b.contentContainer.detach(), b.content && b.content.detach(), c.parsed || (c = b.parseEl(b.index)); var d = c.type; if (y("BeforeChange", [b.currItem ? b.currItem.type : "", d]), b.currItem = c, !b.currTemplate[d]) { var f = b.st[d] ? b.st[d].markup : !1; y("FirstMarkupParse", f), f ? b.currTemplate[d] = a(f) : b.currTemplate[d] = !0 } e && e !== c.type && b.container.removeClass("mfp-" + e + "-holder"); var g = b["get" + d.charAt(0).toUpperCase() + d.slice(1)](c, b.currTemplate[d]); b.appendContent(g, d), c.preloaded = !0, y(n, c), e = c.type, b.container.prepend(b.contentContainer), y("AfterChange") }, appendContent: function (a, c) { b.content = a, a ? b.st.showCloseBtn && b.st.closeBtnInside && b.currTemplate[c] === !0 ? b.content.find(".mfp-close").length || b.content.append(z()) : b.content = a : b.content = "", y(k), b.container.addClass("mfp-" + c + "-holder"), b.contentContainer.append(b.content) }, parseEl: function (c) { var d, e = b.items[c]; if (e.tagName ? e = { el: a(e) } : (d = e.type, e = { data: e, src: e.src }), e.el) { for (var f = b.types, g = 0; g < f.length; g++) if (e.el.hasClass("mfp-" + f[g])) { d = f[g]; break } e.src = e.el.attr("data-mfp-src"), e.src || (e.src = e.el.attr("href")) } return e.type = d || b.st.type || "inline", e.index = c, e.parsed = !0, b.items[c] = e, y("ElementParse", e), b.items[c] }, addGroup: function (a, c) { var d = function (d) { d.mfpEl = this, b._openClick(d, a, c) }; c || (c = {}); var e = "click.magnificPopup"; c.mainEl = a, c.items ? (c.isObj = !0, a.off(e).on(e, d)) : (c.isObj = !1, c.delegate ? a.off(e).on(e, c.delegate, d) : (c.items = a, a.off(e).on(e, d))) }, _openClick: function (c, d, e) { var f = void 0 !== e.midClick ? e.midClick : a.magnificPopup.defaults.midClick; if (f || !(2 === c.which || c.ctrlKey || c.metaKey || c.altKey || c.shiftKey)) { var g = void 0 !== e.disableOn ? e.disableOn : a.magnificPopup.defaults.disableOn; if (g) if (a.isFunction(g)) { if (!g.call(b)) return !0 } else if (v.width() < g) return !0; c.type && (c.preventDefault(), b.isOpen && c.stopPropagation()), e.el = a(c.mfpEl), e.delegate && (e.items = d.find(e.delegate)), b.open(e) } }, updateStatus: function (a, d) { if (b.preloader) { c !== a && b.container.removeClass("mfp-s-" + c), d || "loading" !== a || (d = b.st.tLoading); var e = { status: a, text: d }; y("UpdateStatus", e), a = e.status, d = e.text, b.preloader.html(d), b.preloader.find("a").on("click", function (a) { a.stopImmediatePropagation() }), b.container.addClass("mfp-s-" + a), c = a } }, _checkIfClose: function (c) { if (!a(c).hasClass(s)) { var d = b.st.closeOnContentClick, e = b.st.closeOnBgClick; if (d && e) return !0; if (!b.content || a(c).hasClass("mfp-close") || b.preloader && c === b.preloader[0]) return !0; if (c === b.content[0] || a.contains(b.content[0], c)) { if (d) return !0 } else if (e && a.contains(document, c)) return !0; return !1 } }, _addClassToMFP: function (a) { b.bgOverlay.addClass(a), b.wrap.addClass(a) }, _removeClassFromMFP: function (a) { this.bgOverlay.removeClass(a), b.wrap.removeClass(a) }, _hasScrollBar: function (a) { return (b.isIE7 ? d.height() : document.body.scrollHeight) > (a || v.height()) }, _setFocus: function () { (b.st.focus ? b.content.find(b.st.focus).eq(0) : b.wrap).focus() }, _onFocusIn: function (c) { return c.target === b.wrap[0] || a.contains(b.wrap[0], c.target) ? void 0 : (b._setFocus(), !1) }, _parseMarkup: function (b, c, d) { var e; d.data && (c = a.extend(d.data, c)), y(l, [b, c, d]), a.each(c, function (c, d) { if (void 0 === d || d === !1) return !0; if (e = c.split("_"), e.length > 1) { var f = b.find(p + "-" + e[0]); if (f.length > 0) { var g = e[1]; "replaceWith" === g ? f[0] !== d[0] && f.replaceWith(d) : "img" === g ? f.is("img") ? f.attr("src", d) : f.replaceWith(a("<img>").attr("src", d).attr("class", f.attr("class"))) : f.attr(e[1], d) } } else b.find(p + "-" + c).html(d) }) }, _getScrollbarSize: function () { if (void 0 === b.scrollbarSize) { var a = document.createElement("div"); a.style.cssText = "width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;", document.body.appendChild(a), b.scrollbarSize = a.offsetWidth - a.clientWidth, document.body.removeChild(a) } return b.scrollbarSize } }, a.magnificPopup = { instance: null, proto: t.prototype, modules: [], open: function (b, c) { return A(), b = b ? a.extend(!0, {}, b) : {}, b.isObj = !0, b.index = c || 0, this.instance.open(b) }, close: function () { return a.magnificPopup.instance && a.magnificPopup.instance.close() }, registerModule: function (b, c) { c.options && (a.magnificPopup.defaults[b] = c.options), a.extend(this.proto, c.proto), this.modules.push(b) }, defaults: { disableOn: 0, key: null, midClick: !1, mainClass: "", preloader: !0, focus: "", closeOnContentClick: !1, closeOnBgClick: !0, closeBtnInside: !0, showCloseBtn: !0, enableEscapeKey: !0, modal: !1, alignTop: !1, removalDelay: 0, prependTo: null, fixedContentPos: "auto", fixedBgPos: "auto", overflowY: "auto", closeMarkup: '<button title="%title%" type="button" class="mfp-close">&#215;</button>', tClose: "Close (Esc)", tLoading: "Loading...", autoFocusLast: !0 } }, a.fn.magnificPopup = function (c) { A(); var d = a(this); if ("string" == typeof c) if ("open" === c) { var e, f = u ? d.data("magnificPopup") : d[0].magnificPopup, g = parseInt(arguments[1], 10) || 0; f.items ? e = f.items[g] : (e = d, f.delegate && (e = e.find(f.delegate)), e = e.eq(g)), b._openClick({ mfpEl: e }, d, f) } else b.isOpen && b[c].apply(b, Array.prototype.slice.call(arguments, 1)); else c = a.extend(!0, {}, c), u ? d.data("magnificPopup", c) : d[0].magnificPopup = c, b.addGroup(d, c); return d }; var C, D, E, F = "inline", G = function () { E && (D.after(E.addClass(C)).detach(), E = null) }; a.magnificPopup.registerModule(F, { options: { hiddenClass: "hide", markup: "", tNotFound: "Content not found" }, proto: { initInline: function () { b.types.push(F), w(h + "." + F, function () { G() }) }, getInline: function (c, d) { if (G(), c.src) { var e = b.st.inline, f = a(c.src); if (f.length) { var g = f[0].parentNode; g && g.tagName && (D || (C = e.hiddenClass, D = x(C), C = "mfp-" + C), E = f.after(D).detach().removeClass(C)), b.updateStatus("ready") } else b.updateStatus("error", e.tNotFound), f = a("<div>"); return c.inlineElement = f, f } return b.updateStatus("ready"), b._parseMarkup(d, {}, c), d } } }); var H, I = "ajax", J = function () { H && a(document.body).removeClass(H) }, K = function () { J(), b.req && b.req.abort() }; a.magnificPopup.registerModule(I, { options: { settings: null, cursor: "mfp-ajax-cur", tError: '<a href="%url%">The content</a> could not be loaded.' }, proto: { initAjax: function () { b.types.push(I), H = b.st.ajax.cursor, w(h + "." + I, K), w("BeforeChange." + I, K) }, getAjax: function (c) { H && a(document.body).addClass(H), b.updateStatus("loading"); var d = a.extend({ url: c.src, success: function (d, e, f) { var g = { data: d, xhr: f }; y("ParseAjax", g), b.appendContent(a(g.data), I), c.finished = !0, J(), b._setFocus(), setTimeout(function () { b.wrap.addClass(q) }, 16), b.updateStatus("ready"), y("AjaxContentAdded") }, error: function () { J(), c.finished = c.loadError = !0, b.updateStatus("error", b.st.ajax.tError.replace("%url%", c.src)) } }, b.st.ajax.settings); return b.req = a.ajax(d), "" } } }); var L, M = function (c) { if (c.data && void 0 !== c.data.title) return c.data.title; var d = b.st.image.titleSrc; if (d) { if (a.isFunction(d)) return d.call(b, c); if (c.el) return c.el.attr(d) || "" } return "" }; a.magnificPopup.registerModule("image", { options: { markup: '<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>', cursor: "mfp-zoom-out-cur", titleSrc: "title", verticalFit: !0, tError: '<a href="%url%">The image</a> could not be loaded.' }, proto: { initImage: function () { var c = b.st.image, d = ".image"; b.types.push("image"), w(m + d, function () { "image" === b.currItem.type && c.cursor && a(document.body).addClass(c.cursor) }), w(h + d, function () { c.cursor && a(document.body).removeClass(c.cursor), v.off("resize" + p) }), w("Resize" + d, b.resizeImage), b.isLowIE && w("AfterChange", b.resizeImage) }, resizeImage: function () { var a = b.currItem; if (a && a.img && b.st.image.verticalFit) { var c = 0; b.isLowIE && (c = parseInt(a.img.css("padding-top"), 10) + parseInt(a.img.css("padding-bottom"), 10)), a.img.css("max-height", b.wH - c) } }, _onImageHasSize: function (a) { a.img && (a.hasSize = !0, L && clearInterval(L), a.isCheckingImgSize = !1, y("ImageHasSize", a), a.imgHidden && (b.content && b.content.removeClass("mfp-loading"), a.imgHidden = !1)) }, findImageSize: function (a) { var c = 0, d = a.img[0], e = function (f) { L && clearInterval(L), L = setInterval(function () { return d.naturalWidth > 0 ? void b._onImageHasSize(a) : (c > 200 && clearInterval(L), c++, void (3 === c ? e(10) : 40 === c ? e(50) : 100 === c && e(500))) }, f) }; e(1) }, getImage: function (c, d) { var e = 0, f = function () { c && (c.img[0].complete ? (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("ready")), c.hasSize = !0, c.loaded = !0, y("ImageLoadComplete")) : (e++, 200 > e ? setTimeout(f, 100) : g())) }, g = function () { c && (c.img.off(".mfploader"), c === b.currItem && (b._onImageHasSize(c), b.updateStatus("error", h.tError.replace("%url%", c.src))), c.hasSize = !0, c.loaded = !0, c.loadError = !0) }, h = b.st.image, i = d.find(".mfp-img"); if (i.length) { var j = document.createElement("img"); j.className = "mfp-img", c.el && c.el.find("img").length && (j.alt = c.el.find("img").attr("alt")), c.img = a(j).on("load.mfploader", f).on("error.mfploader", g), j.src = c.src, i.is("img") && (c.img = c.img.clone()), j = c.img[0], j.naturalWidth > 0 ? c.hasSize = !0 : j.width || (c.hasSize = !1) } return b._parseMarkup(d, { title: M(c), img_replaceWith: c.img }, c), b.resizeImage(), c.hasSize ? (L && clearInterval(L), c.loadError ? (d.addClass("mfp-loading"), b.updateStatus("error", h.tError.replace("%url%", c.src))) : (d.removeClass("mfp-loading"), b.updateStatus("ready")), d) : (b.updateStatus("loading"), c.loading = !0, c.hasSize || (c.imgHidden = !0, d.addClass("mfp-loading"), b.findImageSize(c)), d) } } }); var N, O = function () { return void 0 === N && (N = void 0 !== document.createElement("p").style.MozTransform), N }; a.magnificPopup.registerModule("zoom", { options: { enabled: !1, easing: "ease-in-out", duration: 300, opener: function (a) { return a.is("img") ? a : a.find("img") } }, proto: { initZoom: function () { var a, c = b.st.zoom, d = ".zoom"; if (c.enabled && b.supportsTransition) { var e, f, g = c.duration, j = function (a) { var b = a.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"), d = "all " + c.duration / 1e3 + "s " + c.easing, e = { position: "fixed", zIndex: 9999, left: 0, top: 0, "-webkit-backface-visibility": "hidden" }, f = "transition"; return e["-webkit-" + f] = e["-moz-" + f] = e["-o-" + f] = e[f] = d, b.css(e), b }, k = function () { b.content.css("visibility", "visible") }; w("BuildControls" + d, function () { if (b._allowZoom()) { if (clearTimeout(e), b.content.css("visibility", "hidden"), a = b._getItemToZoom(), !a) return void k(); f = j(a), f.css(b._getOffset()), b.wrap.append(f), e = setTimeout(function () { f.css(b._getOffset(!0)), e = setTimeout(function () { k(), setTimeout(function () { f.remove(), a = f = null, y("ZoomAnimationEnded") }, 16) }, g) }, 16) } }), w(i + d, function () { if (b._allowZoom()) { if (clearTimeout(e), b.st.removalDelay = g, !a) { if (a = b._getItemToZoom(), !a) return; f = j(a) } f.css(b._getOffset(!0)), b.wrap.append(f), b.content.css("visibility", "hidden"), setTimeout(function () { f.css(b._getOffset()) }, 16) } }), w(h + d, function () { b._allowZoom() && (k(), f && f.remove(), a = null) }) } }, _allowZoom: function () { return "image" === b.currItem.type }, _getItemToZoom: function () { return b.currItem.hasSize ? b.currItem.img : !1 }, _getOffset: function (c) { var d; d = c ? b.currItem.img : b.st.zoom.opener(b.currItem.el || b.currItem); var e = d.offset(), f = parseInt(d.css("padding-top"), 10), g = parseInt(d.css("padding-bottom"), 10); e.top -= a(window).scrollTop() - f; var h = { width: d.width(), height: (u ? d.innerHeight() : d[0].offsetHeight) - g - f }; return O() ? h["-moz-transform"] = h.transform = "translate(" + e.left + "px," + e.top + "px)" : (h.left = e.left, h.top = e.top), h } } }); var P = "iframe", Q = "//about:blank", R = function (a) { if (b.currTemplate[P]) { var c = b.currTemplate[P].find("iframe"); c.length && (a || (c[0].src = Q), b.isIE8 && c.css("display", a ? "block" : "none")) } }; a.magnificPopup.registerModule(P, { options: { markup: '<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>', srcAction: "iframe_src", patterns: { youtube: { index: "youtube.com", id: "v=", src: "//www.youtube.com/embed/%id%?autoplay=1" }, vimeo: { index: "vimeo.com/", id: "/", src: "//player.vimeo.com/video/%id%?autoplay=1" }, gmaps: { index: "//maps.google.", src: "%id%&output=embed" } } }, proto: { initIframe: function () { b.types.push(P), w("BeforeChange", function (a, b, c) { b !== c && (b === P ? R() : c === P && R(!0)) }), w(h + "." + P, function () { R() }) }, getIframe: function (c, d) { var e = c.src, f = b.st.iframe; a.each(f.patterns, function () { return e.indexOf(this.index) > -1 ? (this.id && (e = "string" == typeof this.id ? e.substr(e.lastIndexOf(this.id) + this.id.length, e.length) : this.id.call(this, e)), e = this.src.replace("%id%", e), !1) : void 0 }); var g = {}; return f.srcAction && (g[f.srcAction] = e), b._parseMarkup(d, g, c), b.updateStatus("ready"), d } } }); var S = function (a) { var c = b.items.length; return a > c - 1 ? a - c : 0 > a ? c + a : a }, T = function (a, b, c) { return a.replace(/%curr%/gi, b + 1).replace(/%total%/gi, c) }; a.magnificPopup.registerModule("gallery", { options: { enabled: !1, arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', preload: [0, 2], navigateByImgClick: !0, arrows: !0, tPrev: "Previous (Left arrow key)", tNext: "Next (Right arrow key)", tCounter: "%curr% of %total%" }, proto: { initGallery: function () { var c = b.st.gallery, e = ".mfp-gallery"; return b.direction = !0, c && c.enabled ? (f += " mfp-gallery", w(m + e, function () { c.navigateByImgClick && b.wrap.on("click" + e, ".mfp-img", function () { return b.items.length > 1 ? (b.next(), !1) : void 0 }), d.on("keydown" + e, function (a) { 37 === a.keyCode ? b.prev() : 39 === a.keyCode && b.next() }) }), w("UpdateStatus" + e, function (a, c) { c.text && (c.text = T(c.text, b.currItem.index, b.items.length)) }), w(l + e, function (a, d, e, f) { var g = b.items.length; e.counter = g > 1 ? T(c.tCounter, f.index, g) : "" }), w("BuildControls" + e, function () { if (b.items.length > 1 && c.arrows && !b.arrowLeft) { var d = c.arrowMarkup, e = b.arrowLeft = a(d.replace(/%title%/gi, c.tPrev).replace(/%dir%/gi, "left")).addClass(s), f = b.arrowRight = a(d.replace(/%title%/gi, c.tNext).replace(/%dir%/gi, "right")).addClass(s); e.click(function () { b.prev() }), f.click(function () { b.next() }), b.container.append(e.add(f)) } }), w(n + e, function () { b._preloadTimeout && clearTimeout(b._preloadTimeout), b._preloadTimeout = setTimeout(function () { b.preloadNearbyImages(), b._preloadTimeout = null }, 16) }), void w(h + e, function () { d.off(e), b.wrap.off("click" + e), b.arrowRight = b.arrowLeft = null })) : !1 }, next: function () { b.direction = !0, b.index = S(b.index + 1), b.updateItemHTML() }, prev: function () { b.direction = !1, b.index = S(b.index - 1), b.updateItemHTML() }, goTo: function (a) { b.direction = a >= b.index, b.index = a, b.updateItemHTML() }, preloadNearbyImages: function () { var a, c = b.st.gallery.preload, d = Math.min(c[0], b.items.length), e = Math.min(c[1], b.items.length); for (a = 1; a <= (b.direction ? e : d) ; a++) b._preloadItem(b.index + a); for (a = 1; a <= (b.direction ? d : e) ; a++) b._preloadItem(b.index - a) }, _preloadItem: function (c) { if (c = S(c), !b.items[c].preloaded) { var d = b.items[c]; d.parsed || (d = b.parseEl(c)), y("LazyLoad", d), "image" === d.type && (d.img = a('<img class="mfp-img" />').on("load.mfploader", function () { d.hasSize = !0 }).on("error.mfploader", function () { d.hasSize = !0, d.loadError = !0, y("LazyLoadError", d) }).attr("src", d.src)), d.preloaded = !0 } } } }); var U = "retina"; a.magnificPopup.registerModule(U, { options: { replaceSrc: function (a) { return a.src.replace(/\.\w+$/, function (a) { return "@2x" + a }) }, ratio: 1 }, proto: { initRetina: function () { if (window.devicePixelRatio > 1) { var a = b.st.retina, c = a.ratio; c = isNaN(c) ? c() : c, c > 1 && (w("ImageHasSize." + U, function (a, b) { b.img.css({ "max-width": b.img[0].naturalWidth / c, width: "100%" }) }), w("ElementParse." + U, function (b, d) { d.src = a.replaceSrc(d, c) })) } } } }), A() });;
/* Tooltipster v3.3.0 */;(function(e,t,n){function s(t,n){this.bodyOverflowX;this.callbacks={hide:[],show:[]};this.checkInterval=null;this.Content;this.$el=e(t);this.$elProxy;this.elProxyPosition;this.enabled=true;this.options=e.extend({},i,n);this.mouseIsOverProxy=false;this.namespace="tooltipster-"+Math.round(Math.random()*1e5);this.Status="hidden";this.timerHide=null;this.timerShow=null;this.$tooltip;this.options.iconTheme=this.options.iconTheme.replace(".","");this.options.theme=this.options.theme.replace(".","");this._init()}function o(t,n){var r=true;e.each(t,function(e,i){if(typeof n[e]==="undefined"||t[e]!==n[e]){r=false;return false}});return r}function f(){return!a&&u}function l(){var e=n.body||n.documentElement,t=e.style,r="transition";if(typeof t[r]=="string"){return true}v=["Moz","Webkit","Khtml","O","ms"],r=r.charAt(0).toUpperCase()+r.substr(1);for(var i=0;i<v.length;i++){if(typeof t[v[i]+r]=="string"){return true}}return false}var r="tooltipster",i={animation:"fade",arrow:true,arrowColor:"",autoClose:true,content:null,contentAsHTML:false,contentCloning:true,debug:true,delay:200,minWidth:0,maxWidth:null,functionInit:function(e,t){},functionBefore:function(e,t){t()},functionReady:function(e,t){},functionAfter:function(e){},hideOnClick:false,icon:"(?)",iconCloning:true,iconDesktop:false,iconTouch:false,iconTheme:"tooltipster-icon",interactive:false,interactiveTolerance:350,multiple:false,offsetX:0,offsetY:0,onlyOne:false,position:"top",positionTracker:false,positionTrackerCallback:function(e){if(this.option("trigger")=="hover"&&this.option("autoClose")){this.hide()}},restoration:"current",speed:350,timer:0,theme:"tooltipster-default",touchDevices:true,trigger:"hover",updateAnimation:true};s.prototype={_init:function(){var t=this;if(n.querySelector){var r=null;if(t.$el.data("tooltipster-initialTitle")===undefined){r=t.$el.attr("title");if(r===undefined)r=null;t.$el.data("tooltipster-initialTitle",r)}if(t.options.content!==null){t._content_set(t.options.content)}else{t._content_set(r)}var i=t.options.functionInit.call(t.$el,t.$el,t.Content);if(typeof i!=="undefined")t._content_set(i);t.$el.removeAttr("title").addClass("tooltipstered");if(!u&&t.options.iconDesktop||u&&t.options.iconTouch){if(typeof t.options.icon==="string"){t.$elProxy=e('<span class="'+t.options.iconTheme+'"></span>');t.$elProxy.text(t.options.icon)}else{if(t.options.iconCloning)t.$elProxy=t.options.icon.clone(true);else t.$elProxy=t.options.icon}t.$elProxy.insertAfter(t.$el)}else{t.$elProxy=t.$el}if(t.options.trigger=="hover"){t.$elProxy.on("mouseenter."+t.namespace,function(){if(!f()||t.options.touchDevices){t.mouseIsOverProxy=true;t._show()}}).on("mouseleave."+t.namespace,function(){if(!f()||t.options.touchDevices){t.mouseIsOverProxy=false}});if(u&&t.options.touchDevices){t.$elProxy.on("touchstart."+t.namespace,function(){t._showNow()})}}else if(t.options.trigger=="click"){t.$elProxy.on("click."+t.namespace,function(){if(!f()||t.options.touchDevices){t._show()}})}}},_show:function(){var e=this;if(e.Status!="shown"&&e.Status!="appearing"){if(e.options.delay){e.timerShow=setTimeout(function(){if(e.options.trigger=="click"||e.options.trigger=="hover"&&e.mouseIsOverProxy){e._showNow()}},e.options.delay)}else e._showNow()}},_showNow:function(n){var r=this;r.options.functionBefore.call(r.$el,r.$el,function(){if(r.enabled&&r.Content!==null){if(n)r.callbacks.show.push(n);r.callbacks.hide=[];clearTimeout(r.timerShow);r.timerShow=null;clearTimeout(r.timerHide);r.timerHide=null;if(r.options.onlyOne){e(".tooltipstered").not(r.$el).each(function(t,n){var r=e(n),i=r.data("tooltipster-ns");e.each(i,function(e,t){var n=r.data(t),i=n.status(),s=n.option("autoClose");if(i!=="hidden"&&i!=="disappearing"&&s){n.hide()}})})}var i=function(){r.Status="shown";e.each(r.callbacks.show,function(e,t){t.call(r.$el)});r.callbacks.show=[]};if(r.Status!=="hidden"){var s=0;if(r.Status==="disappearing"){r.Status="appearing";if(l()){r.$tooltip.clearQueue().removeClass("tooltipster-dying").addClass("tooltipster-"+r.options.animation+"-show");if(r.options.speed>0)r.$tooltip.delay(r.options.speed);r.$tooltip.queue(i)}else{r.$tooltip.stop().fadeIn(i)}}else if(r.Status==="shown"){i()}}else{r.Status="appearing";var s=r.options.speed;r.bodyOverflowX=e("body").css("overflow-x");e("body").css("overflow-x","hidden");var o="tooltipster-"+r.options.animation,a="-webkit-transition-duration: "+r.options.speed+"ms; -webkit-animation-duration: "+r.options.speed+"ms; -moz-transition-duration: "+r.options.speed+"ms; -moz-animation-duration: "+r.options.speed+"ms; -o-transition-duration: "+r.options.speed+"ms; -o-animation-duration: "+r.options.speed+"ms; -ms-transition-duration: "+r.options.speed+"ms; -ms-animation-duration: "+r.options.speed+"ms; transition-duration: "+r.options.speed+"ms; animation-duration: "+r.options.speed+"ms;",f=r.options.minWidth?"min-width:"+Math.round(r.options.minWidth)+"px;":"",c=r.options.maxWidth?"max-width:"+Math.round(r.options.maxWidth)+"px;":"",h=r.options.interactive?"pointer-events: auto;":"";r.$tooltip=e('<div class="tooltipster-base '+r.options.theme+'" style="'+f+" "+c+" "+h+" "+a+'"><div class="tooltipster-content"></div></div>');if(l())r.$tooltip.addClass(o);r._content_insert();r.$tooltip.appendTo("body");r.reposition();r.options.functionReady.call(r.$el,r.$el,r.$tooltip);if(l()){r.$tooltip.addClass(o+"-show");if(r.options.speed>0)r.$tooltip.delay(r.options.speed);r.$tooltip.queue(i)}else{r.$tooltip.css("display","none").fadeIn(r.options.speed,i)}r._interval_set();e(t).on("scroll."+r.namespace+" resize."+r.namespace,function(){r.reposition()});if(r.options.autoClose){e("body").off("."+r.namespace);if(r.options.trigger=="hover"){if(u){setTimeout(function(){e("body").on("touchstart."+r.namespace,function(){r.hide()})},0)}if(r.options.interactive){if(u){r.$tooltip.on("touchstart."+r.namespace,function(e){e.stopPropagation()})}var p=null;r.$elProxy.add(r.$tooltip).on("mouseleave."+r.namespace+"-autoClose",function(){clearTimeout(p);p=setTimeout(function(){r.hide()},r.options.interactiveTolerance)}).on("mouseenter."+r.namespace+"-autoClose",function(){clearTimeout(p)})}else{r.$elProxy.on("mouseleave."+r.namespace+"-autoClose",function(){r.hide()})}if(r.options.hideOnClick){r.$elProxy.on("click."+r.namespace+"-autoClose",function(){r.hide()})}}else if(r.options.trigger=="click"){setTimeout(function(){e("body").on("click."+r.namespace+" touchstart."+r.namespace,function(){r.hide()})},0);if(r.options.interactive){r.$tooltip.on("click."+r.namespace+" touchstart."+r.namespace,function(e){e.stopPropagation()})}}}}if(r.options.timer>0){r.timerHide=setTimeout(function(){r.timerHide=null;r.hide()},r.options.timer+s)}}})},_interval_set:function(){var t=this;t.checkInterval=setInterval(function(){if(e("body").find(t.$el).length===0||e("body").find(t.$elProxy).length===0||t.Status=="hidden"||e("body").find(t.$tooltip).length===0){if(t.Status=="shown"||t.Status=="appearing")t.hide();t._interval_cancel()}else{if(t.options.positionTracker){var n=t._repositionInfo(t.$elProxy),r=false;if(o(n.dimension,t.elProxyPosition.dimension)){if(t.$elProxy.css("position")==="fixed"){if(o(n.position,t.elProxyPosition.position))r=true}else{if(o(n.offset,t.elProxyPosition.offset))r=true}}if(!r){t.reposition();t.options.positionTrackerCallback.call(t,t.$el)}}}},200)},_interval_cancel:function(){clearInterval(this.checkInterval);this.checkInterval=null},_content_set:function(e){if(typeof e==="object"&&e!==null&&this.options.contentCloning){e=e.clone(true)}this.Content=e},_content_insert:function(){var e=this,t=this.$tooltip.find(".tooltipster-content");if(typeof e.Content==="string"&&!e.options.contentAsHTML){t.text(e.Content)}else{t.empty().append(e.Content)}},_update:function(e){var t=this;t._content_set(e);if(t.Content!==null){if(t.Status!=="hidden"){t._content_insert();t.reposition();if(t.options.updateAnimation){if(l()){t.$tooltip.css({width:"","-webkit-transition":"all "+t.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-moz-transition":"all "+t.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-o-transition":"all "+t.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms","-ms-transition":"all "+t.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms",transition:"all "+t.options.speed+"ms, width 0ms, height 0ms, left 0ms, top 0ms"}).addClass("tooltipster-content-changing");setTimeout(function(){if(t.Status!="hidden"){t.$tooltip.removeClass("tooltipster-content-changing");setTimeout(function(){if(t.Status!=="hidden"){t.$tooltip.css({"-webkit-transition":t.options.speed+"ms","-moz-transition":t.options.speed+"ms","-o-transition":t.options.speed+"ms","-ms-transition":t.options.speed+"ms",transition:t.options.speed+"ms"})}},t.options.speed)}},t.options.speed)}else{t.$tooltip.fadeTo(t.options.speed,.5,function(){if(t.Status!="hidden"){t.$tooltip.fadeTo(t.options.speed,1)}})}}}}else{t.hide()}},_repositionInfo:function(e){return{dimension:{height:e.outerHeight(false),width:e.outerWidth(false)},offset:e.offset(),position:{left:parseInt(e.css("left")),top:parseInt(e.css("top"))}}},hide:function(n){var r=this;if(n)r.callbacks.hide.push(n);r.callbacks.show=[];clearTimeout(r.timerShow);r.timerShow=null;clearTimeout(r.timerHide);r.timerHide=null;var i=function(){e.each(r.callbacks.hide,function(e,t){t.call(r.$el)});r.callbacks.hide=[]};if(r.Status=="shown"||r.Status=="appearing"){r.Status="disappearing";var s=function(){r.Status="hidden";if(typeof r.Content=="object"&&r.Content!==null){r.Content.detach()}r.$tooltip.remove();r.$tooltip=null;e(t).off("."+r.namespace);e("body").off("."+r.namespace).css("overflow-x",r.bodyOverflowX);e("body").off("."+r.namespace);r.$elProxy.off("."+r.namespace+"-autoClose");r.options.functionAfter.call(r.$el,r.$el);i()};if(l()){r.$tooltip.clearQueue().removeClass("tooltipster-"+r.options.animation+"-show").addClass("tooltipster-dying");if(r.options.speed>0)r.$tooltip.delay(r.options.speed);r.$tooltip.queue(s)}else{r.$tooltip.stop().fadeOut(r.options.speed,s)}}else if(r.Status=="hidden"){i()}return r},show:function(e){this._showNow(e);return this},update:function(e){return this.content(e)},content:function(e){if(typeof e==="undefined"){return this.Content}else{this._update(e);return this}},reposition:function(){var n=this;if(e("body").find(n.$tooltip).length!==0){n.$tooltip.css("width","");n.elProxyPosition=n._repositionInfo(n.$elProxy);var r=null,i=e(t).width(),s=n.elProxyPosition,o=n.$tooltip.outerWidth(false),u=n.$tooltip.innerWidth()+1,a=n.$tooltip.outerHeight(false);if(n.$elProxy.is("area")){var f=n.$elProxy.attr("shape"),l=n.$elProxy.parent().attr("name"),c=e('img[usemap="#'+l+'"]'),h=c.offset().left,p=c.offset().top,d=n.$elProxy.attr("coords")!==undefined?n.$elProxy.attr("coords").split(","):undefined;if(f=="circle"){var v=parseInt(d[0]),m=parseInt(d[1]),g=parseInt(d[2]);s.dimension.height=g*2;s.dimension.width=g*2;s.offset.top=p+m-g;s.offset.left=h+v-g}else if(f=="rect"){var v=parseInt(d[0]),m=parseInt(d[1]),y=parseInt(d[2]),b=parseInt(d[3]);s.dimension.height=b-m;s.dimension.width=y-v;s.offset.top=p+m;s.offset.left=h+v}else if(f=="poly"){var w=[],E=[],S=0,x=0,T=0,N=0,C="even";for(var k=0;k<d.length;k++){var L=parseInt(d[k]);if(C=="even"){if(L>T){T=L;if(k===0){S=T}}if(L<S){S=L}C="odd"}else{if(L>N){N=L;if(k==1){x=N}}if(L<x){x=L}C="even"}}s.dimension.height=N-x;s.dimension.width=T-S;s.offset.top=p+x;s.offset.left=h+S}else{s.dimension.height=c.outerHeight(false);s.dimension.width=c.outerWidth(false);s.offset.top=p;s.offset.left=h}}var A=0,O=0,M=0,_=parseInt(n.options.offsetY),D=parseInt(n.options.offsetX),P=n.options.position;function H(){var n=e(t).scrollLeft();if(A-n<0){r=A-n;A=n}if(A+o-n>i){r=A-(i+n-o);A=i+n-o}}function B(n,r){if(s.offset.top-e(t).scrollTop()-a-_-12<0&&r.indexOf("top")>-1){P=n}if(s.offset.top+s.dimension.height+a+12+_>e(t).scrollTop()+e(t).height()&&r.indexOf("bottom")>-1){P=n;M=s.offset.top-a-_-12}}if(P=="top"){var j=s.offset.left+o-(s.offset.left+s.dimension.width);A=s.offset.left+D-j/2;M=s.offset.top-a-_-12;H();B("bottom","top")}if(P=="top-left"){A=s.offset.left+D;M=s.offset.top-a-_-12;H();B("bottom-left","top-left")}if(P=="top-right"){A=s.offset.left+s.dimension.width+D-o;M=s.offset.top-a-_-12;H();B("bottom-right","top-right")}if(P=="bottom"){var j=s.offset.left+o-(s.offset.left+s.dimension.width);A=s.offset.left-j/2+D;M=s.offset.top+s.dimension.height+_+12;H();B("top","bottom")}if(P=="bottom-left"){A=s.offset.left+D;M=s.offset.top+s.dimension.height+_+12;H();B("top-left","bottom-left")}if(P=="bottom-right"){A=s.offset.left+s.dimension.width+D-o;M=s.offset.top+s.dimension.height+_+12;H();B("top-right","bottom-right")}if(P=="left"){A=s.offset.left-D-o-12;O=s.offset.left+D+s.dimension.width+12;var F=s.offset.top+a-(s.offset.top+s.dimension.height);M=s.offset.top-F/2-_;if(A<0&&O+o>i){var I=parseFloat(n.$tooltip.css("border-width"))*2,q=o+A-I;n.$tooltip.css("width",q+"px");a=n.$tooltip.outerHeight(false);A=s.offset.left-D-q-12-I;F=s.offset.top+a-(s.offset.top+s.dimension.height);M=s.offset.top-F/2-_}else if(A<0){A=s.offset.left+D+s.dimension.width+12;r="left"}}if(P=="right"){A=s.offset.left+D+s.dimension.width+12;O=s.offset.left-D-o-12;var F=s.offset.top+a-(s.offset.top+s.dimension.height);M=s.offset.top-F/2-_;if(A+o>i&&O<0){var I=parseFloat(n.$tooltip.css("border-width"))*2,q=i-A-I;n.$tooltip.css("width",q+"px");a=n.$tooltip.outerHeight(false);F=s.offset.top+a-(s.offset.top+s.dimension.height);M=s.offset.top-F/2-_}else if(A+o>i){A=s.offset.left-D-o-12;r="right"}}if(n.options.arrow){var R="tooltipster-arrow-"+P;if(n.options.arrowColor.length<1){var U=n.$tooltip.css("background-color")}else{var U=n.options.arrowColor}if(!r){r=""}else if(r=="left"){R="tooltipster-arrow-right";r=""}else if(r=="right"){R="tooltipster-arrow-left";r=""}else{r="left:"+Math.round(r)+"px;"}if(P=="top"||P=="top-left"||P=="top-right"){var z=parseFloat(n.$tooltip.css("border-bottom-width")),W=n.$tooltip.css("border-bottom-color")}else if(P=="bottom"||P=="bottom-left"||P=="bottom-right"){var z=parseFloat(n.$tooltip.css("border-top-width")),W=n.$tooltip.css("border-top-color")}else if(P=="left"){var z=parseFloat(n.$tooltip.css("border-right-width")),W=n.$tooltip.css("border-right-color")}else if(P=="right"){var z=parseFloat(n.$tooltip.css("border-left-width")),W=n.$tooltip.css("border-left-color")}else{var z=parseFloat(n.$tooltip.css("border-bottom-width")),W=n.$tooltip.css("border-bottom-color")}if(z>1){z++}var X="";if(z!==0){var V="",J="border-color: "+W+";";if(R.indexOf("bottom")!==-1){V="margin-top: -"+Math.round(z)+"px;"}else if(R.indexOf("top")!==-1){V="margin-bottom: -"+Math.round(z)+"px;"}else if(R.indexOf("left")!==-1){V="margin-right: -"+Math.round(z)+"px;"}else if(R.indexOf("right")!==-1){V="margin-left: -"+Math.round(z)+"px;"}X='<span class="tooltipster-arrow-border" style="'+V+" "+J+';"></span>'}n.$tooltip.find(".tooltipster-arrow").remove();var K='<div class="'+R+' tooltipster-arrow" style="'+r+'">'+X+'<span style="border-color:'+U+';"></span></div>';n.$tooltip.append(K)}n.$tooltip.css({top:Math.round(M)+"px",left:Math.round(A)+"px"})}return n},enable:function(){this.enabled=true;return this},disable:function(){this.hide();this.enabled=false;return this},destroy:function(){var t=this;t.hide();if(t.$el[0]!==t.$elProxy[0]){t.$elProxy.remove()}t.$el.removeData(t.namespace).off("."+t.namespace);var n=t.$el.data("tooltipster-ns");if(n.length===1){var r=null;if(t.options.restoration==="previous"){r=t.$el.data("tooltipster-initialTitle")}else if(t.options.restoration==="current"){r=typeof t.Content==="string"?t.Content:e("<div></div>").append(t.Content).html()}if(r){t.$el.attr("title",r)}t.$el.removeClass("tooltipstered").removeData("tooltipster-ns").removeData("tooltipster-initialTitle")}else{n=e.grep(n,function(e,n){return e!==t.namespace});t.$el.data("tooltipster-ns",n)}return t},elementIcon:function(){return this.$el[0]!==this.$elProxy[0]?this.$elProxy[0]:undefined},elementTooltip:function(){return this.$tooltip?this.$tooltip[0]:undefined},option:function(e,t){if(typeof t=="undefined")return this.options[e];else{this.options[e]=t;return this}},status:function(){return this.Status}};e.fn[r]=function(){var t=arguments;if(this.length===0){if(typeof t[0]==="string"){var n=true;switch(t[0]){case"setDefaults":e.extend(i,t[1]);break;default:n=false;break}if(n)return true;else return this}else{return this}}else{if(typeof t[0]==="string"){var r="#*$~&";this.each(function(){var n=e(this).data("tooltipster-ns"),i=n?e(this).data(n[0]):null;if(i){if(typeof i[t[0]]==="function"){var s=i[t[0]](t[1],t[2])}else{throw new Error('Unknown method .tooltipster("'+t[0]+'")')}if(s!==i){r=s;return false}}else{throw new Error("You called Tooltipster's \""+t[0]+'" method on an uninitialized element')}});return r!=="#*$~&"?r:this}else{var o=[],u=t[0]&&typeof t[0].multiple!=="undefined",a=u&&t[0].multiple||!u&&i.multiple,f=t[0]&&typeof t[0].debug!=="undefined",l=f&&t[0].debug||!f&&i.debug;this.each(function(){var n=false,r=e(this).data("tooltipster-ns"),i=null;if(!r){n=true}else if(a){n=true}else if(l){console.log('Tooltipster: one or more tooltips are already attached to this element: ignoring. Use the "multiple" option to attach more tooltips.')}if(n){i=new s(this,t[0]);if(!r)r=[];r.push(i.namespace);e(this).data("tooltipster-ns",r);e(this).data(i.namespace,i)}o.push(i)});if(a)return o;else return this}}};var u=!!("ontouchstart"in t);var a=false;e("body").one("mousemove",function(){a=true})})(jQuery,window,document);;
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();
});
;
(function () {
    const ACCORDION_ITEM_HEADER = '.accordion__item-header';
    $(document).on('click', ACCORDION_ITEM_HEADER, function (e) {
        e.preventDefault();
        toggleAccordionHandlerItem($(this));
    });

    $(document).on('keydown',ACCORDION_ITEM_HEADER, function (e) {
       
        if (e.keyCode === 13 || e.keyCode === 32)
        {
            e.preventDefault();
            toggleAccordionHandlerItem($(this));
        }
    });

}());

function toggleAccordionHandlerItem($clickedElement) {
    var $clickedElementGrandParent = $clickedElement.parents('.accordion'),
        $clickedElementParent = $clickedElement.parents('.accordion__item');

    const ACTIVE_ELEMENT_CLASS = 'accordion__item--active',
        ACCORDION_ITEM_BODY_CLASS = '.accordion__item-body';

    if ($clickedElementParent.hasClass(ACTIVE_ELEMENT_CLASS))
    {
        $clickedElementParent.removeClass(ACTIVE_ELEMENT_CLASS);
        $clickedElement.attr('aria-expanded', 'false');
        $(ACCORDION_ITEM_BODY_CLASS, $clickedElementParent).slideUp('fast');
    }
    else {
        $('.accordion__item', $clickedElementGrandParent).removeClass(ACTIVE_ELEMENT_CLASS);
        $(ACCORDION_ITEM_BODY_CLASS, $clickedElementGrandParent).slideUp('fast');
        $clickedElementParent.addClass(ACTIVE_ELEMENT_CLASS);
        $('.accordion__item-header', $clickedElementGrandParent).attr('aria-expanded', 'false');
        $clickedElement.attr('aria-expanded', 'true');
        $(ACCORDION_ITEM_BODY_CLASS, $clickedElementParent).slideDown('fast');
        $('html, body').animate({
            scrollTop: $('#accordion').offset().top
        }, 200);
    }    
};
var startBlockDropDown = {
    init: function () {
        this.attachEvents();
    },
    attachEvents: function () {

        $('#start-dropdown-left').hide();
        $('#start-dropdown-right').hide();

        $(document).on('click', '#start-dropbutton-left', function (e) {
            e.stopPropagation()
        });
        $(document).on('click', '#start-dropbutton-right', function (e) {
            e.stopPropagation()
        });

        $(document).on('click', '#start-dropbutton-left', function (e) {
            if ($('#plus-minus-left').hasClass('fa-plus-circle')) {
                //Change Plus Icon
                $('#plus-minus-left').removeClass('fa-plus-circle').addClass('fa-minus-circle')
                //Expand modal
                if ($(window).width() < 991) {
                    var calculatedWidth = $('#start-dropbutton-left').width() - 51.6;
                    $('#start-dropdown-left').width(calculatedWidth);
                }
                else {
                    var calculatedWidth = $('#start-dropbutton-left').width() - 31.6;
                    $('#start-dropdown-left').width(calculatedWidth);
                }

                $("#start-dropbutton-left").css({ 'overflow': 'visible' });
                $('#start-dropbutton-left').children('.link-box').eq(0).css({ 'border-bottom-left-radius': '0px', 'border-bottom-right-radius': '0px' });
                $('#start-dropbutton-left').children('.link-box').eq(0).css({ 'border-bottom': 'hidden' });
                $("#start-dropdown-left").show();
            }
            else if ($('#plus-minus-left').hasClass('fa-minus-circle')) {
                $('#plus-minus-left').removeClass('fa-minus-circle').addClass('fa-plus-circle')
                //Collapse modal
                $("#start-dropbutton-left").css({ 'overflow': 'hidden' });
                $('#start-dropbutton-left').children('.link-box').eq(0).css({ 'border-bottom-left-radius': '10px', 'border-bottom-right-radius': '10px' });
                $('#start-dropbutton-left').children('.link-box').eq(0).css({ 'border-bottom': '' });
                $("#start-dropdown-left").hide();
            }
        });

        $(document).on('click', '#start-dropbutton-right', function (e) {
            if ($('#plus-minus-right').hasClass('fa-plus-circle')) {
                //Change Plus Icon
                $('#plus-minus-right').removeClass('fa-plus-circle').addClass('fa-minus-circle')
                //Expand modal
                if ($(window).width() < 991) {
                    var calculatedWidth = $('#start-dropbutton-right').width() - 51.6;
                    $('#start-dropdown-right').width(calculatedWidth);
                }
                else {
                    var calculatedWidth = $('#start-dropbutton-right').width() - 31.6;
                    $('#start-dropdown-right').width(calculatedWidth);
                }

                $("#start-dropbutton-right").css({ 'overflow': 'visible' });
                $('#start-dropbutton-right').children('.link-box').eq(0).css({ 'border-bottom-left-radius': '0px', 'border-bottom-right-radius': '0px' });
                $('#start-dropbutton-right').children('.link-box').eq(0).css({ 'border-bottom': 'hidden' });
                $("#start-dropdown-right").show();
            }
            else if ($('#plus-minus-right').hasClass('fa-minus-circle')) {
                $('#plus-minus-right').removeClass('fa-minus-circle').addClass('fa-plus-circle')
                //Collapse modal
                $("#start-dropbutton-right").css({ 'overflow': 'hidden' });
                $('#start-dropbutton-right').children('.link-box').eq(0).css({ 'border-bottom-left-radius': '10px', 'border-bottom-right-radius': '10px' });
                $('#start-dropbutton-right').children('.link-box').eq(0).css({ 'border-bottom': '' });
                $("#start-dropdown-right").hide();
            }
        });
    }
};
////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();
                }

            });
            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) {

        options = $.extend({
            isInit: false,
            searchQuery: '',
            sortOrder: dataListHandler.options.sortOrder,
            replaceResult: false,
            resetFilters: false,
            allowUrlParams: false,
            language: dataListHandler.options.language,
            skip: 0,
            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('findRequest', 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) {

            console.log('response', response);

            //
            dataListHandler.options.$searchQueryInput.val(options.searchQuery);
            dataListHandler.displayResetQueryButton(dataListHandler.options.$searchQueryInput.val());

            if (options.isInit) {
                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();
                dataListHandler.currentPageIdx = pageIdx ? pageIdx : 1;

                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) {
                    dataListHandler.currentPageIdx = response.Data.Results.length / dataListHandler.options.resultPageSize;
                }
                //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 
            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)
                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--active">' +
                '<span class="accordion-item__heading">' +
                    '<span aria-controls="' + accordionContentId + '" class="accordion-item__heading-text" id="' + accordionHeadingId + '">' +
                        '<span class="accordion-item__heading-icon fas fa-sliders-h fa-fw" aria-hidden="true"></span>' +
                facetGroup.GroupName +
                (!facetGroup.Description ? '' : '<span class="filter-tooltip" title="' + facetGroup.Description + '"><i class="fa fa-info-circle"></i></span>') +
                    '</span>' +                    
                '</span>' +
                '<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)
        $('.filter-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)));
    }
};
;
